Organize weights, data and tools with verified catalogs
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +46 -77
- STATUS.json +15 -6
- WEIGHTS.md +0 -137
- data/README.md +51 -0
- data/aliases.jsonl +0 -0
- data/index.jsonl +0 -0
- load_weights.py +0 -17
- tools/__init__.py +0 -0
- tools/load_weights.py +40 -0
- tools/materialize_data.py +60 -0
- tools/model_code/LICENSE +199 -0
- tools/model_code/__init__.py +0 -0
- tools/model_code/recorded/__init__.py +0 -0
- tools/model_code/recorded/arm/__init__.py +0 -0
- tools/model_code/recorded/arm/hr_mot.py +1245 -0
- tools/model_code/recorded/arm/wan22/__init__.py +0 -0
- tools/model_code/recorded/arm/wan22/helpers/__init__.py +0 -0
- tools/model_code/recorded/arm/wan22/helpers/gradient.py +26 -0
- tools/model_code/recorded/arm/wan22/mot.py +606 -0
- tools/model_code/recorded/arm/wan22/schedulers/__init__.py +0 -0
- tools/model_code/recorded/arm/wan22/schedulers/scheduler_continuous.py +96 -0
- tools/model_code/recorded/arm/wan22/wan_video_dit.py +781 -0
- tools/model_code/recorded/carrier/__init__.py +0 -0
- tools/model_code/recorded/carrier/hr_mot.py +1293 -0
- tools/model_code/recorded/carrier/wan22/__init__.py +0 -0
- tools/model_code/recorded/carrier/wan22/helpers/__init__.py +0 -0
- tools/model_code/recorded/carrier/wan22/helpers/gradient.py +26 -0
- tools/model_code/recorded/carrier/wan22/mot.py +606 -0
- tools/model_code/recorded/carrier/wan22/schedulers/__init__.py +0 -0
- tools/model_code/recorded/carrier/wan22/schedulers/scheduler_continuous.py +96 -0
- tools/model_code/recorded/carrier/wan22/wan_video_dit.py +781 -0
- tools/model_code/recorded/coupling/__init__.py +0 -0
- tools/model_code/recorded/coupling/hr_mot.py +1385 -0
- tools/model_code/recorded/coupling/wan22/__init__.py +0 -0
- tools/model_code/recorded/coupling/wan22/helpers/__init__.py +0 -0
- tools/model_code/recorded/coupling/wan22/helpers/gradient.py +26 -0
- tools/model_code/recorded/coupling/wan22/mot.py +761 -0
- tools/model_code/recorded/coupling/wan22/schedulers/__init__.py +0 -0
- tools/model_code/recorded/coupling/wan22/schedulers/scheduler_continuous.py +96 -0
- tools/model_code/recorded/coupling/wan22/wan_video_dit.py +781 -0
- tools/model_code/recorded/language/__init__.py +0 -0
- tools/model_code/recorded/language/hr_mot.py +1401 -0
- tools/model_code/recorded/language/wan22/__init__.py +0 -0
- tools/model_code/recorded/language/wan22/helpers/__init__.py +0 -0
- tools/model_code/recorded/language/wan22/helpers/gradient.py +26 -0
- tools/model_code/recorded/language/wan22/mot.py +606 -0
- tools/model_code/recorded/language/wan22/schedulers/__init__.py +0 -0
- tools/model_code/recorded/language/wan22/schedulers/scheduler_continuous.py +96 -0
- tools/model_code/recorded/language/wan22/wan_video_dit.py +781 -0
- tools/model_code/recorded/main/__init__.py +0 -0
README.md
CHANGED
|
@@ -1,94 +1,63 @@
|
|
| 1 |
---
|
| 2 |
-
pretty_name: VorA
|
| 3 |
language:
|
| 4 |
- en
|
| 5 |
tags:
|
| 6 |
- robotics
|
| 7 |
-
- multimodal-learning
|
| 8 |
- model-weights
|
| 9 |
- simulation
|
| 10 |
---
|
| 11 |
# VorA
|
| 12 |
|
| 13 |
-
Final model weights and
|
| 14 |
-
|
| 15 |
-
**Upload in progress.**
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
|
| 28 |
-
|
|
| 29 |
-
|
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
Browse [`WEIGHTS.md`](WEIGHTS.md) for the complete model list and download paths.
|
| 38 |
-
`motion` in a directory name denotes numerical demonstration actions. The
|
| 39 |
-
independent None model is shared between fixed and adaptive comparisons where
|
| 40 |
-
its inputs and training labels coincide; it is stored only once.
|
| 41 |
-
|
| 42 |
-
## Layout
|
| 43 |
-
|
| 44 |
-
```text
|
| 45 |
-
weights/
|
| 46 |
-
recorded/{main,future_coupling,language}/
|
| 47 |
-
synthetic_2d/{throwing,rebound,pushing}/
|
| 48 |
-
synthetic_3d/{gate,bank,ramp}/
|
| 49 |
-
curling/
|
| 50 |
-
data/
|
| 51 |
-
recorded/{raw,instruction_annotations,hand_arm_masks,language}/
|
| 52 |
-
synthetic_2d/
|
| 53 |
-
synthetic_3d/
|
| 54 |
-
curling/
|
| 55 |
-
indexes/
|
| 56 |
-
models.json
|
| 57 |
-
data_files.jsonl
|
| 58 |
-
data_aliases.jsonl
|
| 59 |
-
load_weights.py
|
| 60 |
-
materialize_data.py
|
| 61 |
-
```
|
| 62 |
|
| 63 |
-
|
| 64 |
|
| 65 |
```python
|
| 66 |
-
from load_weights import
|
| 67 |
|
| 68 |
-
|
| 69 |
-
"weights/recorded/
|
| 70 |
-
revision="<
|
| 71 |
)
|
| 72 |
-
# Construct the corresponding architecture using metadata, then:
|
| 73 |
-
# model.load_state_dict(state_dict, strict=True)
|
| 74 |
```
|
| 75 |
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
[H&R dataset](https://huggingface.co/datasets/dannyXSC/HumanAndRobot).
|
| 93 |
-
Synthetic tasks contain simulator-generated observations and labels. Original
|
| 94 |
-
upstream terms continue to apply; this repository does not replace them.
|
|
|
|
| 1 |
---
|
| 2 |
+
pretty_name: VorA
|
| 3 |
language:
|
| 4 |
- en
|
| 5 |
tags:
|
| 6 |
- robotics
|
|
|
|
| 7 |
- model-weights
|
| 8 |
- simulation
|
| 9 |
---
|
| 10 |
# VorA
|
| 11 |
|
| 12 |
+
Final model weights and their training and evaluation data.
|
| 13 |
+
|
| 14 |
+
**Upload in progress.** See [transfer status](STATUS.json). Catalog entries may appear before their files finish uploading.
|
| 15 |
+
|
| 16 |
+
| Directory | Contents |
|
| 17 |
+
| --- | --- |
|
| 18 |
+
| [weights/](weights/README.md) | 131 final models, grouped by task |
|
| 19 |
+
| [data/](data/README.md) | Recordings, synthetic inputs, labels and evaluation splits |
|
| 20 |
+
| [tools/](tools/) | Model definitions, loading and data restoration |
|
| 21 |
+
|
| 22 |
+
## Weights
|
| 23 |
+
|
| 24 |
+
Each model has two files: `<variant>_seed<N>.safetensors` and its matching `.json` configuration. For example, `weights/recorded/full_seed0.safetensors`.
|
| 25 |
+
|
| 26 |
+
| Task | Models |
|
| 27 |
+
| --- | --- |
|
| 28 |
+
| `recorded` | Full, Video, Action, None, hand–arm video |
|
| 29 |
+
| `coupling` | Coupled/decoupled attention with two context-exposure settings |
|
| 30 |
+
| `language` | Language and independent None |
|
| 31 |
+
| `throwing`, `rebound`, `pushing` | Fixed and adaptive demonstrations |
|
| 32 |
+
| `gate`, `bank`, `ramp` | 3D policies; `q16` and `q32` identify different input formats |
|
| 33 |
+
| `curling` | None, Motion, Video, Full; three seeds each |
|
| 34 |
+
|
| 35 |
+
Only final selected weights are included. Intermediate checkpoints, initial weights and optimizer states are omitted. Tensor values were checked against their originals, and every model passed strict state-dictionary loading. The [model index](weights/index.json) records sizes and SHA-256 checksums.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
+
Download `tools/` from a single repository revision, then:
|
| 38 |
|
| 39 |
```python
|
| 40 |
+
from tools.load_weights import load_model
|
| 41 |
|
| 42 |
+
model, config = load_model(
|
| 43 |
+
"weights/recorded/full_seed0",
|
| 44 |
+
revision="<commit-sha>",
|
| 45 |
)
|
|
|
|
|
|
|
| 46 |
```
|
| 47 |
|
| 48 |
+
Install PyTorch, safetensors, huggingface_hub, einops and tqdm. The loader constructs the matching architecture; preprocessing and input masks must follow that model's configuration. Recorded models also require their compatible pretrained visual encoder for RGB input.
|
| 49 |
+
|
| 50 |
+
## Data
|
| 51 |
+
|
| 52 |
+
Files with identical SHA-256 checksums are stored once. The [data index](data/index.jsonl) maps every required path to its stored file; shared paths are restored automatically. Large NumPy arrays use lossless `.npy.zst` compression. Numeric values and dtypes are preserved.
|
| 53 |
+
|
| 54 |
+
Download `tools/materialize_data.py` and `data/index.jsonl`, install `huggingface_hub` and `zstandard`, then choose a group:
|
| 55 |
+
|
| 56 |
+
```bash
|
| 57 |
+
python tools/materialize_data.py --group synthetic_2d/throwing \
|
| 58 |
+
--output ./datasets --revision <commit-sha>
|
| 59 |
+
```
|
| 60 |
+
|
| 61 |
+
Use `--dry-run` to see the download size first. The script verifies checksums before and after decompression. See the [data guide](data/README.md) for available groups.
|
| 62 |
+
|
| 63 |
+
Recorded sequences originate from the upstream [H&R dataset](https://huggingface.co/datasets/dannyXSC/HumanAndRobot). Upstream terms continue to apply. Synthetic tasks contain simulator-generated observations and labels.
|
|
|
|
|
|
|
|
|
STATUS.json
CHANGED
|
@@ -1,9 +1,18 @@
|
|
| 1 |
{
|
| 2 |
-
"
|
| 3 |
"complete": false,
|
| 4 |
-
"
|
| 5 |
-
"
|
| 6 |
-
"
|
| 7 |
-
"
|
| 8 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"status": "uploading",
|
| 3 |
"complete": false,
|
| 4 |
+
"models": 131,
|
| 5 |
+
"model_bytes": 26505703880,
|
| 6 |
+
"models_tensor_verified": 131,
|
| 7 |
+
"models_strict_loading_verified": 131,
|
| 8 |
+
"data": {
|
| 9 |
+
"logical_files": 5038,
|
| 10 |
+
"unique_files": 4025,
|
| 11 |
+
"duplicate_files_removed": 1013,
|
| 12 |
+
"logical_bytes": 183167881936,
|
| 13 |
+
"unique_uncompressed_bytes": 165400674588,
|
| 14 |
+
"stored_bytes": 117418541181
|
| 15 |
+
},
|
| 16 |
+
"checksums": "weights/index.json and data/index.jsonl",
|
| 17 |
+
"note": "Files listed in catalogs may still be transferring."
|
| 18 |
}
|
WEIGHTS.md
DELETED
|
@@ -1,137 +0,0 @@
|
|
| 1 |
-
# Final model index
|
| 2 |
-
|
| 3 |
-
All entries refer to final model parameters. A shared baseline is listed once.
|
| 4 |
-
|
| 5 |
-
| Model directory | Final update | Size (MB) | SHA-256 |
|
| 6 |
-
| --- | ---: | ---: | --- |
|
| 7 |
-
| [weights/curling/full/seed0](weights/curling/full/seed0) | 3,000 | 0.84 | `6cc42571a7b621c0593451acfa0fdec591c6dd530948cd586845ec0b91f27546` |
|
| 8 |
-
| [weights/curling/full/seed1](weights/curling/full/seed1) | 3,000 | 0.84 | `da2c4083a2e907643eafc6c57cb579b6075500be8a01384c8a869eb0f533f8d5` |
|
| 9 |
-
| [weights/curling/full/seed2](weights/curling/full/seed2) | 3,000 | 0.84 | `db6f454560fd9a9163e7eb220c2c74617f7be14016ea0d0f60dfe00a870acf99` |
|
| 10 |
-
| [weights/curling/motion/seed0](weights/curling/motion/seed0) | 3,000 | 0.84 | `4ff75c601c617bd7a4b1d0f2556b8cb5a6ba6170175efb8b9d93a6fb27114b02` |
|
| 11 |
-
| [weights/curling/motion/seed1](weights/curling/motion/seed1) | 3,000 | 0.84 | `10b5296dd3278588f9145e0ee6cbb7e78b0f5583375d3fef4a42c2517d8135f2` |
|
| 12 |
-
| [weights/curling/motion/seed2](weights/curling/motion/seed2) | 3,000 | 0.84 | `776ae55bc43e020fb785ad2c7098b957232482e016677b40667a84af4b5f587d` |
|
| 13 |
-
| [weights/curling/none/seed0](weights/curling/none/seed0) | 3,000 | 0.84 | `e26244994cde0742d8fe412b119f54471ae6652ea100e9e0cffaacc13610b39b` |
|
| 14 |
-
| [weights/curling/none/seed1](weights/curling/none/seed1) | 3,000 | 0.84 | `3af3d408e27e8a96576bcbff08e140f0fc3ac28310b48de21627a3878f077440` |
|
| 15 |
-
| [weights/curling/none/seed2](weights/curling/none/seed2) | 3,000 | 0.84 | `7f8e1565745b467abce387fecde3d9cfec373ee8eafc51b94b3f773472e6382d` |
|
| 16 |
-
| [weights/curling/video/seed0](weights/curling/video/seed0) | 3,000 | 0.84 | `cda182daea191f02ba02ddf9c29e222ed001b09bae0f0faa90e1fe409d8b8b97` |
|
| 17 |
-
| [weights/curling/video/seed1](weights/curling/video/seed1) | 3,000 | 0.84 | `dd7d339e075785f132c4b3626d1c2b706c20ae20d3940a7ec2ce3c0dfa6046b4` |
|
| 18 |
-
| [weights/curling/video/seed2](weights/curling/video/seed2) | 3,000 | 0.84 | `cdc4a5542a2118e29ae00d78fceff20476e6414bf6fde46380484361814de42a` |
|
| 19 |
-
| [weights/recorded/future_coupling/coupled_demo50/seed0](weights/recorded/future_coupling/coupled_demo50/seed0) | 10,000 | 2371.79 | `16d8b9918ae7f31ce04a95be872faf8e10aeb67beda8f87eaedff0798d7a5a64` |
|
| 20 |
-
| [weights/recorded/future_coupling/coupled_nodemo/seed0](weights/recorded/future_coupling/coupled_nodemo/seed0) | 10,000 | 2371.79 | `0b5aab7499a0094aad70998ab369a0ab9b36e2f5dc86595a5d5ffd96526518f7` |
|
| 21 |
-
| [weights/recorded/future_coupling/decoupled_demo50/seed0](weights/recorded/future_coupling/decoupled_demo50/seed0) | 10,000 | 2371.79 | `276f43b228a33fe67cf07c7404add85df340d553ad766d2880271003d51ee5e3` |
|
| 22 |
-
| [weights/recorded/future_coupling/decoupled_nodemo/seed0](weights/recorded/future_coupling/decoupled_nodemo/seed0) | 10,000 | 2371.79 | `9ecf3ad9fc9f619fdb62b5e6597e30bb6ede6b16c7acf9d6e0d51c14315825fd` |
|
| 23 |
-
| [weights/recorded/language/language/seed0](weights/recorded/language/language/seed0) | 10,000 | 2374.01 | `207b3aacd67c3ff29bee7ba4a75314311266bfd2e86570801dd8acb320ef1cc0` |
|
| 24 |
-
| [weights/recorded/language/none/seed0](weights/recorded/language/none/seed0) | 10,000 | 2374.01 | `53bfe4a27a6ce905f63ad1faa507ee17c848d31f2e76c73c71b6a84bd34c9cc5` |
|
| 25 |
-
| [weights/recorded/main/action/seed0](weights/recorded/main/action/seed0) | 10,000 | 2371.79 | `0c6e5c764ed85f74b74cd8ed18821ec1d2943e018f1a415cc8ca1b0f0ce569b2` |
|
| 26 |
-
| [weights/recorded/main/full/seed0](weights/recorded/main/full/seed0) | 10,000 | 2371.79 | `429e838e6df398ae43a19756479aab7e84ea4ea44f3cf075fdaa124cecc5a14f` |
|
| 27 |
-
| [weights/recorded/main/hand_arm_video/seed0](weights/recorded/main/hand_arm_video/seed0) | 10,000 | 2371.79 | `b05edd31d3dcfca2c7a96314e9eb1dd9757479ea7853afe51e2bb7046b8f122b` |
|
| 28 |
-
| [weights/recorded/main/none/seed0](weights/recorded/main/none/seed0) | 10,000 | 2371.79 | `d5c75395744cc4db95c3e5cf3fc4950edf3aa10f8b692a8a28a9bc55ce1c0b4b` |
|
| 29 |
-
| [weights/recorded/main/video/seed0](weights/recorded/main/video/seed0) | 10,000 | 2371.79 | `8aaeb09dd0c01f20eeef1c827190f207f26e70bfd9077fefedde84b2fa6421c0` |
|
| 30 |
-
| [weights/synthetic_2d/pushing/adaptive/full/seed0](weights/synthetic_2d/pushing/adaptive/full/seed0) | 4,096 | 1.84 | `52d87398c4d71555251f1640d73b2f9b79a3f58f808dca055cf7165966f6c507` |
|
| 31 |
-
| [weights/synthetic_2d/pushing/adaptive/motion/seed0](weights/synthetic_2d/pushing/adaptive/motion/seed0) | 4,096 | 1.84 | `656afa2b1e2bd97fc437680b6c6415c4db22b2aecf6f876bbecc418917cafbfe` |
|
| 32 |
-
| [weights/synthetic_2d/pushing/adaptive/video/seed0](weights/synthetic_2d/pushing/adaptive/video/seed0) | 4,096 | 1.84 | `54334b5bde2110a4a581b66af0b52b55cc943d1c0140d72f1643649cca17757d` |
|
| 33 |
-
| [weights/synthetic_2d/pushing/fixed/full/seed0](weights/synthetic_2d/pushing/fixed/full/seed0) | 4,096 | 1.84 | `07fcb3c1aea3ad250b8c9876b0fd1b7c7a9c60a2da8539a4ff0a66064c4ffc57` |
|
| 34 |
-
| [weights/synthetic_2d/pushing/fixed/full/seed1](weights/synthetic_2d/pushing/fixed/full/seed1) | 4,096 | 1.84 | `feece4a9acfdc7c6eec6908d6dc03e3ce9c9e81ccee26bfbb1da2ec69d68ee50` |
|
| 35 |
-
| [weights/synthetic_2d/pushing/fixed/full/seed2](weights/synthetic_2d/pushing/fixed/full/seed2) | 4,096 | 1.84 | `f96777eebe8047ad31459ee344eff657ec3e0ebbbec9c87a7f658e3310b7d90d` |
|
| 36 |
-
| [weights/synthetic_2d/pushing/fixed/motion/seed0](weights/synthetic_2d/pushing/fixed/motion/seed0) | 4,096 | 1.84 | `91da5181ed9f7b5dc4c186aba3ffd101ddccf053fecf66b881ab5284b2c75c6b` |
|
| 37 |
-
| [weights/synthetic_2d/pushing/fixed/motion/seed1](weights/synthetic_2d/pushing/fixed/motion/seed1) | 4,096 | 1.84 | `0dbdf181223c719a9a29560aef4a607ad3bdfc9de10f003e78f6804c96bf65d7` |
|
| 38 |
-
| [weights/synthetic_2d/pushing/fixed/motion/seed2](weights/synthetic_2d/pushing/fixed/motion/seed2) | 4,096 | 1.84 | `f0e2b3ce70ad2daadc935eafc6cd3bece9ae414d6c8ba23a5dcb4bc36b73e76f` |
|
| 39 |
-
| [weights/synthetic_2d/pushing/fixed/none/seed0](weights/synthetic_2d/pushing/fixed/none/seed0) | 4,096 | 1.84 | `f9679f22c7624f40291b0e4d89b3b82d511dbc4ed0b34e549dcec56da0ff873e` |
|
| 40 |
-
| [weights/synthetic_2d/pushing/fixed/none/seed1](weights/synthetic_2d/pushing/fixed/none/seed1) | 4,096 | 1.84 | `bbee64f82ffac205ed247e44e73a4f0bb9a7777181cb7b3454ea478043516772` |
|
| 41 |
-
| [weights/synthetic_2d/pushing/fixed/none/seed2](weights/synthetic_2d/pushing/fixed/none/seed2) | 4,096 | 1.84 | `a0a2efea92d3b59ebb79b09021f65738d1979869d0c9ac466ea4e759930d09ab` |
|
| 42 |
-
| [weights/synthetic_2d/pushing/fixed/video/seed0](weights/synthetic_2d/pushing/fixed/video/seed0) | 4,096 | 1.84 | `bc9800afeff468fdfd7546ab97056656e03e821553001446a43fa4cef1c90ee5` |
|
| 43 |
-
| [weights/synthetic_2d/pushing/fixed/video/seed1](weights/synthetic_2d/pushing/fixed/video/seed1) | 4,096 | 1.84 | `fdf5289d9e6103c2f25a9ee6bc24aa3f59bee5fb5554541e61e89ad4c0f9d508` |
|
| 44 |
-
| [weights/synthetic_2d/pushing/fixed/video/seed2](weights/synthetic_2d/pushing/fixed/video/seed2) | 4,096 | 1.84 | `da57091858e671ce39c94981aa409f65cb7ad221e3810f3f9a2f84735346b0f0` |
|
| 45 |
-
| [weights/synthetic_2d/rebound/adaptive/full/seed0](weights/synthetic_2d/rebound/adaptive/full/seed0) | 4,096 | 0.98 | `b30e2ae7eae86feb5ef9e07e3fdee0159c25e4658ad99170fe0698ca23074ff6` |
|
| 46 |
-
| [weights/synthetic_2d/rebound/adaptive/motion/seed0](weights/synthetic_2d/rebound/adaptive/motion/seed0) | 4,096 | 0.98 | `92b15a81e71ed585c661b53a4365da14691abda24cd3f6abaa91c5326be76767` |
|
| 47 |
-
| [weights/synthetic_2d/rebound/adaptive/video/seed0](weights/synthetic_2d/rebound/adaptive/video/seed0) | 4,096 | 0.98 | `2bd4ed3261b3fd0e0b33aa4d61912a01400de9a4ad7aae98a1ff51875cb938d2` |
|
| 48 |
-
| [weights/synthetic_2d/rebound/fixed/full/seed0](weights/synthetic_2d/rebound/fixed/full/seed0) | 4,096 | 0.98 | `2bafc74f4e11854804287be82edce08e71f295e4b793e2d518724d81fd656759` |
|
| 49 |
-
| [weights/synthetic_2d/rebound/fixed/full/seed1](weights/synthetic_2d/rebound/fixed/full/seed1) | 4,096 | 0.98 | `a8535b23b65ddb1bf8907ae5b67038da0c074ef6b680b646703addb05eb238b0` |
|
| 50 |
-
| [weights/synthetic_2d/rebound/fixed/full/seed2](weights/synthetic_2d/rebound/fixed/full/seed2) | 4,096 | 0.98 | `5e92c39a83b90983bfcd494c15d7c53e8e65e65ab59aa557819d67b4a1513ee6` |
|
| 51 |
-
| [weights/synthetic_2d/rebound/fixed/motion/seed0](weights/synthetic_2d/rebound/fixed/motion/seed0) | 4,096 | 0.98 | `2c699563dd572112ea4b10b6a86dfc3a17b0aaa1127ca91e36f000abbbdd5c5f` |
|
| 52 |
-
| [weights/synthetic_2d/rebound/fixed/motion/seed1](weights/synthetic_2d/rebound/fixed/motion/seed1) | 4,096 | 0.98 | `35caf67412150bf9ac457cf01e860c199f7c21593e584a18fa7171e5482c2237` |
|
| 53 |
-
| [weights/synthetic_2d/rebound/fixed/motion/seed2](weights/synthetic_2d/rebound/fixed/motion/seed2) | 4,096 | 0.98 | `28b2ae27077ff65125bd42baaaef80aa615515ae359362627ea46eb1d0d7b9f0` |
|
| 54 |
-
| [weights/synthetic_2d/rebound/fixed/none/seed0](weights/synthetic_2d/rebound/fixed/none/seed0) | 4,096 | 0.98 | `dd1c1b924809d6d1f7a383fb6d786685c64af70ce0b3fda59a0f2d9003e5ac6a` |
|
| 55 |
-
| [weights/synthetic_2d/rebound/fixed/none/seed1](weights/synthetic_2d/rebound/fixed/none/seed1) | 4,096 | 0.98 | `de1c4e288f754eb8cc0df533ce6eee78a67d6fef853e6a7ed4d13f082354e451` |
|
| 56 |
-
| [weights/synthetic_2d/rebound/fixed/none/seed2](weights/synthetic_2d/rebound/fixed/none/seed2) | 4,096 | 0.98 | `84f31d504e74b0c329ac623faf28ba8d4b0c38f87b494fe81eab31ceaa08a0cd` |
|
| 57 |
-
| [weights/synthetic_2d/rebound/fixed/video/seed0](weights/synthetic_2d/rebound/fixed/video/seed0) | 4,096 | 0.98 | `e5820fa95486e6a9a35aeaf66f121d8b1fba6425f39b4d57daaa834d0d718909` |
|
| 58 |
-
| [weights/synthetic_2d/rebound/fixed/video/seed1](weights/synthetic_2d/rebound/fixed/video/seed1) | 4,096 | 0.98 | `af4ac858ce56fe040d6c2f679530d63df8f0a65e9ae01230ca8eaaf3e3864b84` |
|
| 59 |
-
| [weights/synthetic_2d/rebound/fixed/video/seed2](weights/synthetic_2d/rebound/fixed/video/seed2) | 4,096 | 0.98 | `72cff21e5dbfc6c63faef24a446eab7edd6c3e11518ca2d0fe96068e93f3ca1a` |
|
| 60 |
-
| [weights/synthetic_2d/throwing/adaptive/full/seed0](weights/synthetic_2d/throwing/adaptive/full/seed0) | 4,096 | 1.39 | `968d17c90b183d80d6f61132e8b99dbaf07efc13bf1aaf247f187f8ef87bf8dd` |
|
| 61 |
-
| [weights/synthetic_2d/throwing/adaptive/full/seed1](weights/synthetic_2d/throwing/adaptive/full/seed1) | 4,096 | 1.39 | `76078a74b039175d49e0c19acfec56be87e342e3a4c0685baa5c74b0883319e9` |
|
| 62 |
-
| [weights/synthetic_2d/throwing/adaptive/full/seed2](weights/synthetic_2d/throwing/adaptive/full/seed2) | 4,096 | 1.39 | `88dafb402758f2d279be2e4a22592216d39de7e9f46f5de158969c2b34886394` |
|
| 63 |
-
| [weights/synthetic_2d/throwing/adaptive/motion/seed0](weights/synthetic_2d/throwing/adaptive/motion/seed0) | 4,096 | 1.39 | `bf7e9bf58780095dcd4fca41276ba663b4335631b377026ca8186d18f975d25d` |
|
| 64 |
-
| [weights/synthetic_2d/throwing/adaptive/motion/seed1](weights/synthetic_2d/throwing/adaptive/motion/seed1) | 4,096 | 1.39 | `2e1fefd36204a60d10c78d95b6d5db105844ba573bd53a34083258170426d37d` |
|
| 65 |
-
| [weights/synthetic_2d/throwing/adaptive/motion/seed2](weights/synthetic_2d/throwing/adaptive/motion/seed2) | 4,096 | 1.39 | `8b9b4b2956855eee4d6c72f14bb121149473d3637b512b0e998740a694f41d15` |
|
| 66 |
-
| [weights/synthetic_2d/throwing/adaptive/video/seed0](weights/synthetic_2d/throwing/adaptive/video/seed0) | 4,096 | 1.39 | `34bf426c8931fc25212dd792831957f604e0deef5e4dfbd0eec2b3f66a3bcd55` |
|
| 67 |
-
| [weights/synthetic_2d/throwing/adaptive/video/seed1](weights/synthetic_2d/throwing/adaptive/video/seed1) | 4,096 | 1.39 | `7bf1372c934f368c91abc81437cc4be9ce5d7a167d5a83c59da324664ca2ecb6` |
|
| 68 |
-
| [weights/synthetic_2d/throwing/adaptive/video/seed2](weights/synthetic_2d/throwing/adaptive/video/seed2) | 4,096 | 1.39 | `30263bca12f989a448647a2bb294eb02748e41536f5f95b1d1eec23cfa84b023` |
|
| 69 |
-
| [weights/synthetic_2d/throwing/fixed/full/seed0](weights/synthetic_2d/throwing/fixed/full/seed0) | 4,096 | 1.39 | `8f6b8bb70d9a6d6352590ec26d08b1d96b8964a3e4bd3523468f46c3becdd518` |
|
| 70 |
-
| [weights/synthetic_2d/throwing/fixed/full/seed1](weights/synthetic_2d/throwing/fixed/full/seed1) | 4,096 | 1.39 | `9b62b3f6dc645f677a3c240da5f8f84341b88d0f4f73d9a93108b2a7aa5880a3` |
|
| 71 |
-
| [weights/synthetic_2d/throwing/fixed/full/seed2](weights/synthetic_2d/throwing/fixed/full/seed2) | 4,096 | 1.39 | `04f7dd6c703d1778adf6e8be14cf87cd00447fcbb8af49814d5cd8cbeda2f37b` |
|
| 72 |
-
| [weights/synthetic_2d/throwing/fixed/motion/seed0](weights/synthetic_2d/throwing/fixed/motion/seed0) | 4,096 | 1.39 | `7295dfbbf385739d2fe1f7ef8649da0b7434b28f8cff02b115edda13fec0030e` |
|
| 73 |
-
| [weights/synthetic_2d/throwing/fixed/motion/seed1](weights/synthetic_2d/throwing/fixed/motion/seed1) | 4,096 | 1.39 | `e98c1a2ad12869b1d2a79a912fd092515b9d95ab5fb8b036258633716203ec58` |
|
| 74 |
-
| [weights/synthetic_2d/throwing/fixed/motion/seed2](weights/synthetic_2d/throwing/fixed/motion/seed2) | 4,096 | 1.39 | `7f8bc21681533379a73c8d066090895d3835cfe89161dd10d0b9bc0377001b41` |
|
| 75 |
-
| [weights/synthetic_2d/throwing/fixed/none/seed0](weights/synthetic_2d/throwing/fixed/none/seed0) | 4,096 | 1.39 | `3c9baaedfd0a41bebf28d91c4a4ec27a64ded80ea18ed6e239ff2b8d775bf09e` |
|
| 76 |
-
| [weights/synthetic_2d/throwing/fixed/none/seed1](weights/synthetic_2d/throwing/fixed/none/seed1) | 4,096 | 1.39 | `b128b1ee5caf06b57dce536d7b1959df8ee0ed9a191e4c714b73ab79e7d6af86` |
|
| 77 |
-
| [weights/synthetic_2d/throwing/fixed/none/seed2](weights/synthetic_2d/throwing/fixed/none/seed2) | 4,096 | 1.39 | `48b5e3b7ae32a47c65ad60df94aeaf376cc78bdb579e0209dfc5466bd7f1acc8` |
|
| 78 |
-
| [weights/synthetic_2d/throwing/fixed/video/seed0](weights/synthetic_2d/throwing/fixed/video/seed0) | 4,096 | 1.39 | `3e9bde715049f929c5ff16f29f1a9b38799d4b69274d2131d9484f91b490c2f1` |
|
| 79 |
-
| [weights/synthetic_2d/throwing/fixed/video/seed1](weights/synthetic_2d/throwing/fixed/video/seed1) | 4,096 | 1.39 | `36e19fa834ac566a3519dada36073de8ff13d69f68b1a5b3d192abbd80f6f7d1` |
|
| 80 |
-
| [weights/synthetic_2d/throwing/fixed/video/seed2](weights/synthetic_2d/throwing/fixed/video/seed2) | 4,096 | 1.39 | `a460eae54ada858a3cd14825532e3436e7600675310dd61ba440670ca33db769` |
|
| 81 |
-
| [weights/synthetic_3d/bank/adaptive_shared_q32/full/seed0](weights/synthetic_3d/bank/adaptive_shared_q32/full/seed0) | 4,096 | 5.79 | `9a57b48e728915411d2f1f00c7a05f21f97116338c7e6fc482bcfa6b3992bb4c` |
|
| 82 |
-
| [weights/synthetic_3d/bank/adaptive_shared_q32/motion/seed0](weights/synthetic_3d/bank/adaptive_shared_q32/motion/seed0) | 4,096 | 5.79 | `67f1478ffc02b3e4b2f1c90eb5e8ca4d1c3cb7264fb8e5b4cb7429075548ec87` |
|
| 83 |
-
| [weights/synthetic_3d/bank/adaptive_shared_q32/video/seed0](weights/synthetic_3d/bank/adaptive_shared_q32/video/seed0) | 4,096 | 5.79 | `95c154e919191a2a95638605bec59e1b0bdbccb9c613d20e1f7c183213fb5578` |
|
| 84 |
-
| [weights/synthetic_3d/bank/fixed_q16/full/seed0](weights/synthetic_3d/bank/fixed_q16/full/seed0) | 4,096 | 5.77 | `2d412518a2c4eff263c0c1589318bfe9e4d27b56fdb271b39223e9a34ef28c0c` |
|
| 85 |
-
| [weights/synthetic_3d/bank/fixed_q16/full/seed1](weights/synthetic_3d/bank/fixed_q16/full/seed1) | 4,096 | 5.77 | `a1d3c1079b498fcc0fc504f5655a4994090ad37bf5b7efde87bcbf31f315db06` |
|
| 86 |
-
| [weights/synthetic_3d/bank/fixed_q16/full/seed2](weights/synthetic_3d/bank/fixed_q16/full/seed2) | 4,096 | 5.77 | `36010313caaaa1351c7f0dc1f970aa6bac96984739fc46570e6cede8e0d1287f` |
|
| 87 |
-
| [weights/synthetic_3d/bank/fixed_q16/motion/seed0](weights/synthetic_3d/bank/fixed_q16/motion/seed0) | 4,096 | 5.77 | `5d26feaafa769a29a1a6b87551cfc4a59de9eb289cb38ab4ba0a2d6d3e138fcf` |
|
| 88 |
-
| [weights/synthetic_3d/bank/fixed_q16/motion/seed1](weights/synthetic_3d/bank/fixed_q16/motion/seed1) | 4,096 | 5.77 | `28016874b28b4f3db8bacb1eaf299d2e6f912bd88769a3d117414a11b7c82c46` |
|
| 89 |
-
| [weights/synthetic_3d/bank/fixed_q16/motion/seed2](weights/synthetic_3d/bank/fixed_q16/motion/seed2) | 4,096 | 5.77 | `5051778620814a61e747ad71612a304191f99e475884e40e7d823114041410bf` |
|
| 90 |
-
| [weights/synthetic_3d/bank/fixed_q16/none/seed0](weights/synthetic_3d/bank/fixed_q16/none/seed0) | 4,096 | 5.77 | `e80d282d2812f5393ac4950db6ae153e643396f5182de7fc86c5137d15ef8729` |
|
| 91 |
-
| [weights/synthetic_3d/bank/fixed_q16/none/seed1](weights/synthetic_3d/bank/fixed_q16/none/seed1) | 4,096 | 5.77 | `b634c106ae8ea607a698a65dd719f424551d0cbe8e100b806b33bb489c334012` |
|
| 92 |
-
| [weights/synthetic_3d/bank/fixed_q16/none/seed2](weights/synthetic_3d/bank/fixed_q16/none/seed2) | 4,096 | 5.77 | `275d660aff521b8c5d8fbdb3379eea6305eb86780e7fb5598e5f6b41bae5a965` |
|
| 93 |
-
| [weights/synthetic_3d/bank/fixed_q16/video/seed0](weights/synthetic_3d/bank/fixed_q16/video/seed0) | 4,096 | 5.77 | `b138a1a37a528688d70fed96bb336c5d09b6c168f30253272fc8dd4d94a04c0c` |
|
| 94 |
-
| [weights/synthetic_3d/bank/fixed_q16/video/seed1](weights/synthetic_3d/bank/fixed_q16/video/seed1) | 4,096 | 5.77 | `3d604329f08fa341f7684ad3035aad00e8812e102b1b236fda42b59cbf8f5f49` |
|
| 95 |
-
| [weights/synthetic_3d/bank/fixed_q16/video/seed2](weights/synthetic_3d/bank/fixed_q16/video/seed2) | 4,096 | 5.77 | `8ca30dc06ae9d7ad86b5c15ca9cf3170fa53f3d6e551d95513da2c9a78afbc1f` |
|
| 96 |
-
| [weights/synthetic_3d/bank/fixed_shared_q32/full/seed0](weights/synthetic_3d/bank/fixed_shared_q32/full/seed0) | 4,096 | 5.79 | `9e1ac2675480abdb22633468cb0d8d672e9417ac28f1c67daffdae7e0d8967c4` |
|
| 97 |
-
| [weights/synthetic_3d/bank/fixed_shared_q32/motion/seed0](weights/synthetic_3d/bank/fixed_shared_q32/motion/seed0) | 4,096 | 5.79 | `1b9062b46921b4eae6106bf9d43cf8e7fb000a1190e472162faf838e54e2ddd2` |
|
| 98 |
-
| [weights/synthetic_3d/bank/fixed_shared_q32/none/seed0](weights/synthetic_3d/bank/fixed_shared_q32/none/seed0) | 4,096 | 5.79 | `7ca99d25bb4c3022befdc55983709a1f0f04ceb6918ffd4f4ac44d0fc0b70162` |
|
| 99 |
-
| [weights/synthetic_3d/bank/fixed_shared_q32/video/seed0](weights/synthetic_3d/bank/fixed_shared_q32/video/seed0) | 4,096 | 5.79 | `6ac792b3a2086f676c61091508b132b44b541bb5b795f46aa64fcacd8a12fdd6` |
|
| 100 |
-
| [weights/synthetic_3d/gate/adaptive_shared_q32/full/seed0](weights/synthetic_3d/gate/adaptive_shared_q32/full/seed0) | 4,096 | 5.79 | `7fd02079cdd33e656cac93e7ed13683212a8a1212d46c32db3765276084bb773` |
|
| 101 |
-
| [weights/synthetic_3d/gate/adaptive_shared_q32/motion/seed0](weights/synthetic_3d/gate/adaptive_shared_q32/motion/seed0) | 4,096 | 5.79 | `ddb85a04d008a1b1ee60b4b108403365b3d0d7ec6ab102a34e7b7ad585f26dd5` |
|
| 102 |
-
| [weights/synthetic_3d/gate/adaptive_shared_q32/video/seed0](weights/synthetic_3d/gate/adaptive_shared_q32/video/seed0) | 4,096 | 5.79 | `6e166b1eb627062ec89583c10d524ebcfcde2e622ea3895aacf90e82cd3e1fa0` |
|
| 103 |
-
| [weights/synthetic_3d/gate/fixed_q16/full/seed0](weights/synthetic_3d/gate/fixed_q16/full/seed0) | 4,096 | 5.77 | `00b1918e0fc98ace8b227827d1b2598ae29488827cbdb0adeabccbe52e30629f` |
|
| 104 |
-
| [weights/synthetic_3d/gate/fixed_q16/full/seed1](weights/synthetic_3d/gate/fixed_q16/full/seed1) | 4,096 | 5.77 | `e6629f64f0d98afdca0de83920d126363be98b864c38bae53978e19b9f512219` |
|
| 105 |
-
| [weights/synthetic_3d/gate/fixed_q16/full/seed2](weights/synthetic_3d/gate/fixed_q16/full/seed2) | 4,096 | 5.77 | `48a9ae32f450d95f80fa9e0a7876f299ba9a28d3870f099c00ad7b96a90f9d84` |
|
| 106 |
-
| [weights/synthetic_3d/gate/fixed_q16/motion/seed0](weights/synthetic_3d/gate/fixed_q16/motion/seed0) | 4,096 | 5.77 | `9dedfe9972679f605dd4afeebc75fba8a8c8a7b90c6cda8c63d7b0a367a56708` |
|
| 107 |
-
| [weights/synthetic_3d/gate/fixed_q16/motion/seed1](weights/synthetic_3d/gate/fixed_q16/motion/seed1) | 4,096 | 5.77 | `50ad635008fa1300ccc65683d7d84d1051fe7976cee28b83f457c354d90842f5` |
|
| 108 |
-
| [weights/synthetic_3d/gate/fixed_q16/motion/seed2](weights/synthetic_3d/gate/fixed_q16/motion/seed2) | 4,096 | 5.77 | `33fb0abc13e53b6aea49fe66bd85ab5d0efb190ef2ef70228b6f2727271311d1` |
|
| 109 |
-
| [weights/synthetic_3d/gate/fixed_q16/none/seed0](weights/synthetic_3d/gate/fixed_q16/none/seed0) | 4,096 | 5.77 | `5c10a50980a1656d950d499f11ba526ee7849c43ce79f1aacf29da32386fdca9` |
|
| 110 |
-
| [weights/synthetic_3d/gate/fixed_q16/none/seed1](weights/synthetic_3d/gate/fixed_q16/none/seed1) | 4,096 | 5.77 | `17e246085947cd8c7d61183b30da4da42b3c24be5afb5cca48befc2ca074c899` |
|
| 111 |
-
| [weights/synthetic_3d/gate/fixed_q16/none/seed2](weights/synthetic_3d/gate/fixed_q16/none/seed2) | 4,096 | 5.77 | `90fd37bb807df1298b794a5cec1e8c992197728a5bcbef2d267b966a195f3a2e` |
|
| 112 |
-
| [weights/synthetic_3d/gate/fixed_q16/video/seed0](weights/synthetic_3d/gate/fixed_q16/video/seed0) | 4,096 | 5.77 | `6cf2241ff5ea327fce1e9e0dc63235fdad90f9e78ff0c82b0ce0ef462f0849c7` |
|
| 113 |
-
| [weights/synthetic_3d/gate/fixed_q16/video/seed1](weights/synthetic_3d/gate/fixed_q16/video/seed1) | 4,096 | 5.77 | `a8990c43502f6c13583bfd7bbdc52ef414524863db68cc1ddd6cc5ff9101431e` |
|
| 114 |
-
| [weights/synthetic_3d/gate/fixed_q16/video/seed2](weights/synthetic_3d/gate/fixed_q16/video/seed2) | 4,096 | 5.77 | `4a79c467e018b047799644e8e1885a1b5a5f844fc46a6270509d3ed338359b24` |
|
| 115 |
-
| [weights/synthetic_3d/gate/fixed_shared_q32/full/seed0](weights/synthetic_3d/gate/fixed_shared_q32/full/seed0) | 4,096 | 5.79 | `21d356787b964db6c456a66699f734156ab5d2898fb89bd2d4ef5c875658cc0f` |
|
| 116 |
-
| [weights/synthetic_3d/gate/fixed_shared_q32/motion/seed0](weights/synthetic_3d/gate/fixed_shared_q32/motion/seed0) | 4,096 | 5.79 | `dba654cd700d032aaf0a58d5a41e098c6c06cb65955684f4ba977e743236bced` |
|
| 117 |
-
| [weights/synthetic_3d/gate/fixed_shared_q32/none/seed0](weights/synthetic_3d/gate/fixed_shared_q32/none/seed0) | 4,096 | 5.79 | `07b6667bad02f99e01c6a7d1bfc716e77d774d7b0febf7eb94a0498214eec248` |
|
| 118 |
-
| [weights/synthetic_3d/gate/fixed_shared_q32/video/seed0](weights/synthetic_3d/gate/fixed_shared_q32/video/seed0) | 4,096 | 5.79 | `60a3da07d3a4921bc15d2e8f230c2b7fd788c44e71e30e691040e9f5444b8509` |
|
| 119 |
-
| [weights/synthetic_3d/ramp/adaptive_shared_q32/full/seed0](weights/synthetic_3d/ramp/adaptive_shared_q32/full/seed0) | 4,096 | 5.79 | `b760350e8da6f0ba8a8c5c877b2cecd4d429b8a4b986e01dfc5f02a9276fb0ad` |
|
| 120 |
-
| [weights/synthetic_3d/ramp/adaptive_shared_q32/motion/seed0](weights/synthetic_3d/ramp/adaptive_shared_q32/motion/seed0) | 4,096 | 5.79 | `c651c44aaf73e2f8c22279b649dc2eed031f30ca78c0c89d60adf28eccc8cd23` |
|
| 121 |
-
| [weights/synthetic_3d/ramp/adaptive_shared_q32/video/seed0](weights/synthetic_3d/ramp/adaptive_shared_q32/video/seed0) | 4,096 | 5.79 | `e9e72a847680c9c181eb41662ad2ce191c7ad7319d5dd7204512d4e787c085f2` |
|
| 122 |
-
| [weights/synthetic_3d/ramp/fixed_q16/full/seed0](weights/synthetic_3d/ramp/fixed_q16/full/seed0) | 4,096 | 5.77 | `4f88e116acac2aaeacc1526d23cd045c92570478a291702263458d8a37ff9a0c` |
|
| 123 |
-
| [weights/synthetic_3d/ramp/fixed_q16/full/seed1](weights/synthetic_3d/ramp/fixed_q16/full/seed1) | 4,096 | 5.77 | `3780f236ba3bab7661a77c2bd9d863236be564eaacbc84da68d1eb5c69af6a98` |
|
| 124 |
-
| [weights/synthetic_3d/ramp/fixed_q16/full/seed2](weights/synthetic_3d/ramp/fixed_q16/full/seed2) | 4,096 | 5.77 | `aaa73102e835480ac175fc39263f86e3f8b66ece1c7da14409cb500598a22e28` |
|
| 125 |
-
| [weights/synthetic_3d/ramp/fixed_q16/motion/seed0](weights/synthetic_3d/ramp/fixed_q16/motion/seed0) | 4,096 | 5.77 | `0a8da0bb4b40dd0453102eb4f8496e25913cae88353f8c7ffd318f2fb799f8df` |
|
| 126 |
-
| [weights/synthetic_3d/ramp/fixed_q16/motion/seed1](weights/synthetic_3d/ramp/fixed_q16/motion/seed1) | 4,096 | 5.77 | `3a56fc2ab4ef155e0b97f969d9069053844c1547eb51ad2c5cfc4c28beec75da` |
|
| 127 |
-
| [weights/synthetic_3d/ramp/fixed_q16/motion/seed2](weights/synthetic_3d/ramp/fixed_q16/motion/seed2) | 4,096 | 5.77 | `74f88a2e60b88013b2ebd662f3bf2d6d19a67b6dc18d24a5dedc8ac59e57ae06` |
|
| 128 |
-
| [weights/synthetic_3d/ramp/fixed_q16/none/seed0](weights/synthetic_3d/ramp/fixed_q16/none/seed0) | 4,096 | 5.77 | `3c1a4ee946d818c46a68e934ce8792f4c8efb2caba7a59b338c434c221bee3ec` |
|
| 129 |
-
| [weights/synthetic_3d/ramp/fixed_q16/none/seed1](weights/synthetic_3d/ramp/fixed_q16/none/seed1) | 4,096 | 5.77 | `787d1be5c8c5d2740c72bfeb54539872fbfe192f7439c5248d12b6c785048e7e` |
|
| 130 |
-
| [weights/synthetic_3d/ramp/fixed_q16/none/seed2](weights/synthetic_3d/ramp/fixed_q16/none/seed2) | 4,096 | 5.77 | `2074f63bb2557c708eba727eb010f0153d94354744122d07eafed4861a756f2f` |
|
| 131 |
-
| [weights/synthetic_3d/ramp/fixed_q16/video/seed0](weights/synthetic_3d/ramp/fixed_q16/video/seed0) | 4,096 | 5.77 | `fb79116a81384d92c05a2de0e2d0fe72d34b63e5dd21839338e37f91201a1095` |
|
| 132 |
-
| [weights/synthetic_3d/ramp/fixed_q16/video/seed1](weights/synthetic_3d/ramp/fixed_q16/video/seed1) | 4,096 | 5.77 | `3a0493a34d2a9e76fc98af20b95de9c4bac8058079ed5eef6b3d172d2374c507` |
|
| 133 |
-
| [weights/synthetic_3d/ramp/fixed_q16/video/seed2](weights/synthetic_3d/ramp/fixed_q16/video/seed2) | 4,096 | 5.77 | `7935b069621e9cb603eaeb7fafa3bdf59a09b0201435b9e5d8685b76f72b45d9` |
|
| 134 |
-
| [weights/synthetic_3d/ramp/fixed_shared_q32/full/seed0](weights/synthetic_3d/ramp/fixed_shared_q32/full/seed0) | 4,096 | 5.79 | `67beea38f9376233fb780ba94d9347a8b434e5109a09b544add30c3b38748dca` |
|
| 135 |
-
| [weights/synthetic_3d/ramp/fixed_shared_q32/motion/seed0](weights/synthetic_3d/ramp/fixed_shared_q32/motion/seed0) | 4,096 | 5.79 | `a154b3030b24704b4dac34f1002cf1c382998a1153654ca4bdf02f2b106ceefa` |
|
| 136 |
-
| [weights/synthetic_3d/ramp/fixed_shared_q32/none/seed0](weights/synthetic_3d/ramp/fixed_shared_q32/none/seed0) | 4,096 | 5.79 | `8f4b1ddb327b6f123222cafa403eafaf3389645de27b5cafc179163ee9e39dae` |
|
| 137 |
-
| [weights/synthetic_3d/ramp/fixed_shared_q32/video/seed0](weights/synthetic_3d/ramp/fixed_shared_q32/video/seed0) | 4,096 | 5.79 | `3823184639ae0c1e846fd9c025b19d6b400d3e274c36af25f68b6db260003f77` |
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Dataset guide
|
| 2 |
+
|
| 3 |
+
Data are grouped by task and input protocol. The file index records each logical
|
| 4 |
+
path, its canonical stored path, compression, byte count and SHA-256 checksum.
|
| 5 |
+
Aliases refer to identical content, not merely matching filenames or shapes.
|
| 6 |
+
|
| 7 |
+
| Directory | Contents |
|
| 8 |
+
| --- | --- |
|
| 9 |
+
| `recorded/raw/` | Original aligned human/robot recordings, observations, measured motion and timestamps |
|
| 10 |
+
| `recorded/instruction_annotations/` | Instruction annotations used to identify recordings |
|
| 11 |
+
| `recorded/hand_arm_masks/` | Final hand–arm masks; array values preserved, local-path attributes removed |
|
| 12 |
+
| `recorded/language/` | Captions, segment alignment and caption-query manifest |
|
| 13 |
+
| `recorded/language/rgb_data/` | Exact caption-aligned RGB/state arrays, record order and normalization statistics |
|
| 14 |
+
| `synthetic_2d/{throwing,rebound,pushing}/` | Fixed/adaptive training inputs and labels, with split names retained |
|
| 15 |
+
| `synthetic_2d/paired_evaluation/` | Matched ID/OOD evaluation records for the three 2D tasks |
|
| 16 |
+
| `synthetic_3d/{gate,bank,ramp}/fixed_q16/train/` | Exact training shards for the original 16D-query policies |
|
| 17 |
+
| `synthetic_3d/paired_evaluation/` | Shared demonstrations and paired geometric conditions for those policies |
|
| 18 |
+
| `synthetic_3d/{gate,bank,ramp}/{fixed,adaptive}_shared_q32/` | Training and evaluation inputs with a common numerical source specification |
|
| 19 |
+
| `curling/` | Training and confirmation data with scene and target-direction splits |
|
| 20 |
+
|
| 21 |
+
The 16D-query and 32D-query policies have different input contracts. Do not
|
| 22 |
+
substitute one dataset or checkpoint family for the other. Likewise, caption
|
| 23 |
+
RGB arrays are query-aligned observations, not precomputed VAE latents.
|
| 24 |
+
|
| 25 |
+
Large uncompressed NumPy arrays use lossless Zstandard storage (`.npy.zst`).
|
| 26 |
+
Both compressed-file and decompressed-content checksums are provided. No array
|
| 27 |
+
is resized, quantized or converted to a different numeric dtype for transfer.
|
| 28 |
+
Recordings retain their existing HDF5 compression.
|
| 29 |
+
|
| 30 |
+
## Download and restore
|
| 31 |
+
|
| 32 |
+
Install `huggingface_hub` and `zstandard`, then download this script and the
|
| 33 |
+
`data/index.jsonl` file from the same revision. Preview the required transfer:
|
| 34 |
+
|
| 35 |
+
```bash
|
| 36 |
+
python tools/materialize_data.py --group synthetic_2d/throwing \
|
| 37 |
+
--output ./data --revision <commit-sha> --dry-run
|
| 38 |
+
```
|
| 39 |
+
|
| 40 |
+
Remove `--dry-run` to download and restore. The script verifies stored and
|
| 41 |
+
uncompressed checksums, creates the requested layout, and uses local hardlinks
|
| 42 |
+
for identical files within that selection. Treat restored shared files as
|
| 43 |
+
read-only, or copy a file before editing it.
|
| 44 |
+
|
| 45 |
+
Recorded raw data and caption-aligned windows are different representations.
|
| 46 |
+
They are retained separately because they serve different loaders. Exact copies
|
| 47 |
+
across source servers and repeated synthetic inputs are stored once.
|
| 48 |
+
|
| 49 |
+
Metadata cleanup removes personal paths, annotator identities, internal URLs and
|
| 50 |
+
operational fields. Numerical observations and targets are preserved. Original
|
| 51 |
+
server provenance and the selection audit remain outside this repository.
|
data/aliases.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
data/index.jsonl
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
load_weights.py
DELETED
|
@@ -1,17 +0,0 @@
|
|
| 1 |
-
"""Load safe tensor parameters and portable inference metadata."""
|
| 2 |
-
from pathlib import Path
|
| 3 |
-
import json
|
| 4 |
-
|
| 5 |
-
def load_weights(model_path, *, revision, repo_id='DocD0c/VorA', local_root=None):
|
| 6 |
-
from safetensors.torch import load_file
|
| 7 |
-
if local_root is None:
|
| 8 |
-
from huggingface_hub import hf_hub_download
|
| 9 |
-
def resolve(name):
|
| 10 |
-
return hf_hub_download(repo_id,model_path+'/'+name,repo_type='dataset',revision=revision)
|
| 11 |
-
else:
|
| 12 |
-
def resolve(name):return str(Path(local_root)/model_path/name)
|
| 13 |
-
metadata=json.loads(Path(resolve('config.json')).read_text())
|
| 14 |
-
state_dict=load_file(resolve('model.safetensors'),device='cpu')
|
| 15 |
-
assert len(state_dict)==metadata['release']['tensor_count']
|
| 16 |
-
assert sum(x.numel() for x in state_dict.values())==metadata['release']['parameter_elements']
|
| 17 |
-
return state_dict,metadata
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
tools/__init__.py
ADDED
|
File without changes
|
tools/load_weights.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Load safe tensor parameters and portable inference metadata."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
def load_weights(model_path, *, revision, repo_id='DocD0c/VorA', local_root=None):
|
| 6 |
+
from safetensors.torch import load_file
|
| 7 |
+
if local_root is None:
|
| 8 |
+
from huggingface_hub import hf_hub_download
|
| 9 |
+
def resolve(name):
|
| 10 |
+
return hf_hub_download(repo_id,model_path+name,repo_type='dataset',revision=revision)
|
| 11 |
+
else:
|
| 12 |
+
def resolve(name):return str(Path(local_root)/(model_path+name))
|
| 13 |
+
metadata=json.loads(Path(resolve('.json')).read_text())
|
| 14 |
+
state_dict=load_file(resolve('.safetensors'),device='cpu')
|
| 15 |
+
assert len(state_dict)==metadata['release']['tensor_count']
|
| 16 |
+
assert sum(x.numel() for x in state_dict.values())==metadata['release']['parameter_elements']
|
| 17 |
+
return state_dict,metadata
|
| 18 |
+
|
| 19 |
+
def model_module(model_path):
|
| 20 |
+
group,variant=model_path.removeprefix('weights/').split('/')
|
| 21 |
+
prefix=__package__+'.model_code.' if __package__ else 'model_code.'
|
| 22 |
+
if group in ('recorded','coupling','language'):
|
| 23 |
+
family=group
|
| 24 |
+
if group=='recorded':
|
| 25 |
+
family='carrier' if variant.startswith(('action_','none_')) else 'arm' if variant.startswith('hand_arm_') else 'main'
|
| 26 |
+
return prefix+'recorded.'+family+'.hr_mot'
|
| 27 |
+
if group in ('throwing','rebound','pushing','curling'):return prefix+'synthetic.'+group
|
| 28 |
+
if group in ('gate','bank','ramp'):return prefix+'synthetic.spatial_'+('q16' if variant.startswith('fixed_q16_') else 'q32')
|
| 29 |
+
raise ValueError('Unknown model family: '+model_path)
|
| 30 |
+
|
| 31 |
+
def load_model(model_path, *, revision, repo_id='DocD0c/VorA', local_root=None):
|
| 32 |
+
import importlib
|
| 33 |
+
state,metadata=load_weights(model_path,revision=revision,repo_id=repo_id,local_root=local_root)
|
| 34 |
+
module=importlib.import_module(model_module(model_path))
|
| 35 |
+
if model_path.split('/')[1] in ('recorded','coupling','language'):
|
| 36 |
+
model=module.HRMoTFlowModel(module.HRMoTConfig(**metadata['config']))
|
| 37 |
+
else:
|
| 38 |
+
model=(module.Model if hasattr(module,'Model') else module.Policy)()
|
| 39 |
+
model.load_state_dict(state,strict=True)
|
| 40 |
+
return model.eval(),metadata
|
tools/materialize_data.py
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download a dataset group, verify checksums, decompress it and restore shared paths."""
|
| 2 |
+
import argparse,hashlib,json,os,tempfile,shutil
|
| 3 |
+
from pathlib import Path,PurePosixPath
|
| 4 |
+
|
| 5 |
+
def sha(path):
|
| 6 |
+
h=hashlib.sha256()
|
| 7 |
+
with open(path,'rb') as f:
|
| 8 |
+
for b in iter(lambda:f.read(8*1024*1024),b''):h.update(b)
|
| 9 |
+
return h.hexdigest()
|
| 10 |
+
|
| 11 |
+
def within(root,name):
|
| 12 |
+
parts=PurePosixPath(name)
|
| 13 |
+
if parts.is_absolute() or '..' in parts.parts:raise ValueError('Unsafe path')
|
| 14 |
+
path=root.joinpath(*parts.parts)
|
| 15 |
+
if not path.resolve().is_relative_to(root.resolve()):raise ValueError('Destination escapes output directory')
|
| 16 |
+
return path
|
| 17 |
+
|
| 18 |
+
def main():
|
| 19 |
+
ap=argparse.ArgumentParser(description=__doc__)
|
| 20 |
+
ap.add_argument('--group',required=True,help='Path below data/, e.g. synthetic_2d/throwing')
|
| 21 |
+
ap.add_argument('--output',type=Path,required=True)
|
| 22 |
+
ap.add_argument('--revision',required=True,help='Repository commit SHA')
|
| 23 |
+
ap.add_argument('--repo-id',default='DocD0c/VorA')
|
| 24 |
+
ap.add_argument('--index-root',type=Path,default=Path(__file__).resolve().parent.parent)
|
| 25 |
+
ap.add_argument('--local-repository',type=Path,help='Read stored files from this checkout instead of downloading')
|
| 26 |
+
ap.add_argument('--dry-run',action='store_true')
|
| 27 |
+
args=ap.parse_args()
|
| 28 |
+
entries=[json.loads(x) for x in (args.index_root/'data/index.jsonl').open()]
|
| 29 |
+
prefix='data/'+args.group.strip('/')+'/'
|
| 30 |
+
selected=[x for x in entries if x['path'].startswith(prefix)]
|
| 31 |
+
objects={x['sha256']:x for x in selected}
|
| 32 |
+
print(json.dumps({'logical_files':len(selected),'unique_contents':len(objects),'download_bytes':sum(x['stored_size'] for x in objects.values()),'uncompressed_unique_bytes':sum(x['size'] for x in objects.values())}))
|
| 33 |
+
if args.dry_run:return
|
| 34 |
+
if not selected:raise SystemExit('No matching dataset group')
|
| 35 |
+
args.output.mkdir(parents=True,exist_ok=True);restored={}
|
| 36 |
+
for entry in selected:
|
| 37 |
+
target=within(args.output,entry['path'].removeprefix('data/'));target.parent.mkdir(parents=True,exist_ok=True)
|
| 38 |
+
if target.exists():
|
| 39 |
+
if sha(target)!=entry['sha256']:raise RuntimeError('Existing file checksum mismatch: '+str(target))
|
| 40 |
+
restored.setdefault(entry['sha256'],target);continue
|
| 41 |
+
if entry['sha256'] in restored:
|
| 42 |
+
os.link(restored[entry['sha256']],target);continue
|
| 43 |
+
if args.local_repository:source=within(args.local_repository,entry['stored_path'])
|
| 44 |
+
else:
|
| 45 |
+
from huggingface_hub import hf_hub_download
|
| 46 |
+
source=Path(hf_hub_download(args.repo_id,entry['stored_path'],repo_type='dataset',revision=args.revision))
|
| 47 |
+
if source.stat().st_size!=entry['stored_size'] or sha(source)!=entry['stored_sha256']:raise RuntimeError('Stored file checksum mismatch')
|
| 48 |
+
fd,tmp=tempfile.mkstemp(prefix='.materialize-',dir=target.parent)
|
| 49 |
+
try:
|
| 50 |
+
with os.fdopen(fd,'wb') as dst,source.open('rb') as src:
|
| 51 |
+
if entry['compression']=='zstd':
|
| 52 |
+
import zstandard
|
| 53 |
+
zstandard.ZstdDecompressor().copy_stream(src,dst)
|
| 54 |
+
else:shutil.copyfileobj(src,dst,8*1024*1024)
|
| 55 |
+
if Path(tmp).stat().st_size!=entry['size'] or sha(tmp)!=entry['sha256']:raise RuntimeError('Restored content checksum mismatch')
|
| 56 |
+
os.link(tmp,target)
|
| 57 |
+
finally:os.unlink(tmp)
|
| 58 |
+
restored[entry['sha256']]=target
|
| 59 |
+
print('Dataset restored; every selected file verified. Shared hardlinks must be treated as read-only.')
|
| 60 |
+
if __name__=='__main__':main()
|
tools/model_code/LICENSE
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
Apache License
|
| 2 |
+
Version 2.0, January 2004
|
| 3 |
+
|
| 4 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 5 |
+
|
| 6 |
+
1. Definitions.
|
| 7 |
+
|
| 8 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 9 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 10 |
+
|
| 11 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 12 |
+
the copyright owner that is granting the License.
|
| 13 |
+
|
| 14 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 15 |
+
other entities that control, are controlled by, or are under common
|
| 16 |
+
control with that entity. For the purposes of this definition,
|
| 17 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 18 |
+
direction or management of such entity, whether by contract or
|
| 19 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 20 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 21 |
+
|
| 22 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 23 |
+
exercising permissions granted by this License.
|
| 24 |
+
|
| 25 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 26 |
+
including but not limited to software source code, documentation
|
| 27 |
+
source, and configuration files.
|
| 28 |
+
|
| 29 |
+
"Object" form shall mean any form resulting from mechanical
|
| 30 |
+
transformation or translation of a Source form, including but
|
| 31 |
+
not limited to compiled object code, generated documentation,
|
| 32 |
+
and conversions to other media types.
|
| 33 |
+
|
| 34 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 35 |
+
Object form, made available under the License, as indicated by a
|
| 36 |
+
copyright notice that is included in or attached to the work
|
| 37 |
+
(an example is provided in the Appendix below).
|
| 38 |
+
|
| 39 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 40 |
+
form, that is based on (or derived from) the Work and for which the
|
| 41 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 42 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 43 |
+
of this License, Derivative Works shall not include works that remain
|
| 44 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 45 |
+
the Work and Derivative Works thereof.
|
| 46 |
+
|
| 47 |
+
"Contribution" shall mean any work of authorship, including
|
| 48 |
+
the original version of the Work and any modifications or additions
|
| 49 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 50 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 51 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 52 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 53 |
+
means any form of electronic, verbal, or written communication sent
|
| 54 |
+
to the Licensor or its representatives, including but not limited to
|
| 55 |
+
communication on electronic mailing lists, source code control systems,
|
| 56 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 57 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 58 |
+
excluding communication that is conspicuously marked or otherwise
|
| 59 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 60 |
+
|
| 61 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 62 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 63 |
+
subsequently incorporated within the Work.
|
| 64 |
+
|
| 65 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 66 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 67 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 68 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 69 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 70 |
+
Work and such Derivative Works in Source or Object form.
|
| 71 |
+
|
| 72 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 73 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 74 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 75 |
+
(except as stated in this section) patent license to make, have made,
|
| 76 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 77 |
+
where such license applies only to those patent claims licensable
|
| 78 |
+
by such Contributor that are necessarily infringed by their
|
| 79 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 80 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 81 |
+
institute patent litigation against any entity (including a
|
| 82 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 83 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 84 |
+
or contributory patent infringement, then any patent licenses
|
| 85 |
+
granted to You under this License for that Work shall terminate
|
| 86 |
+
as of the date such litigation is filed.
|
| 87 |
+
|
| 88 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 89 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 90 |
+
modifications, and in Source or Object form, provided that You
|
| 91 |
+
meet the following conditions:
|
| 92 |
+
|
| 93 |
+
(a) You must give any other recipients of the Work or
|
| 94 |
+
Derivative Works a copy of this License; and
|
| 95 |
+
|
| 96 |
+
(b) You must cause any modified files to carry prominent notices
|
| 97 |
+
stating that You changed the files; and
|
| 98 |
+
|
| 99 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 100 |
+
that You distribute, all copyright, patent, trademark, and
|
| 101 |
+
attribution notices from the Source form of the Work,
|
| 102 |
+
excluding those notices that do not pertain to any part of
|
| 103 |
+
the Derivative Works; and
|
| 104 |
+
|
| 105 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 106 |
+
distribution, then any Derivative Works that You distribute must
|
| 107 |
+
include a readable copy of the attribution notices contained
|
| 108 |
+
within such NOTICE file, excluding those notices that do not
|
| 109 |
+
pertain to any part of the Derivative Works, in at least one
|
| 110 |
+
of the following places: within a NOTICE text file distributed
|
| 111 |
+
as part of the Derivative Works; within the Source form or
|
| 112 |
+
documentation, if provided along with the Derivative Works; or,
|
| 113 |
+
within a display generated by the Derivative Works, if and
|
| 114 |
+
wherever such third-party notices normally appear. The contents
|
| 115 |
+
of the NOTICE file are for informational purposes only and
|
| 116 |
+
do not modify the License. You may add Your own attribution
|
| 117 |
+
notices within Derivative Works that You distribute, alongside
|
| 118 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 119 |
+
that such additional attribution notices cannot be construed
|
| 120 |
+
as modifying the License.
|
| 121 |
+
|
| 122 |
+
You may add Your own copyright statement to Your modifications and
|
| 123 |
+
may provide additional or different license terms and conditions
|
| 124 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 125 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 126 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 127 |
+
the conditions stated in this License.
|
| 128 |
+
|
| 129 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 130 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 131 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 132 |
+
this License, without any additional terms or conditions.
|
| 133 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 134 |
+
the terms of any separate license agreement you may have executed
|
| 135 |
+
with Licensor regarding such Contributions.
|
| 136 |
+
|
| 137 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 138 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 139 |
+
except as required for reasonable and customary use in describing the
|
| 140 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 141 |
+
|
| 142 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 143 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 144 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 145 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 146 |
+
implied, including, without limitation, any warranties or conditions
|
| 147 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 148 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 149 |
+
appropriateness of using or redistributing the Work and assume any
|
| 150 |
+
risks associated with Your exercise of permissions under this License.
|
| 151 |
+
|
| 152 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 153 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 154 |
+
unless required by applicable law (such as deliberate and grossly
|
| 155 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 156 |
+
liable to You for damages, including any direct, indirect, special,
|
| 157 |
+
incidental, or consequential damages of any character arising as a
|
| 158 |
+
result of this License or out of the use or inability to use the
|
| 159 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 160 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 161 |
+
other commercial damages or losses), even if such Contributor
|
| 162 |
+
has been advised of the possibility of such damages.
|
| 163 |
+
|
| 164 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 165 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 166 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 167 |
+
or other liability obligations and/or rights consistent with this
|
| 168 |
+
License. However, in accepting such obligations, You may act only
|
| 169 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 170 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 171 |
+
defend, and hold each Contributor harmless for any liability
|
| 172 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 173 |
+
of your accepting any such warranty or additional liability.
|
| 174 |
+
|
| 175 |
+
END OF TERMS AND CONDITIONS
|
| 176 |
+
|
| 177 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 178 |
+
|
| 179 |
+
To apply the Apache License to your work, attach the following
|
| 180 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 181 |
+
replaced with your own identifying information. (Don't include
|
| 182 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 183 |
+
comment syntax for the file format. We also recommend that a
|
| 184 |
+
file or class name and description of purpose be included on the
|
| 185 |
+
same "printed page" as the copyright notice for easier
|
| 186 |
+
identification within third-party archives.
|
| 187 |
+
|
| 188 |
+
Copyright [yyyy] [name of copyright owner]
|
| 189 |
+
|
| 190 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 191 |
+
you may not use this file except in compliance with the License.
|
| 192 |
+
You may obtain a copy of the License at
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
Unless required by applicable law or agreed to in writing, software
|
| 196 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 197 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 198 |
+
See the License for the specific language governing permissions and
|
| 199 |
+
limitations under the License.
|
tools/model_code/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/arm/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/arm/hr_mot.py
ADDED
|
@@ -0,0 +1,1245 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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transformers flow model: ~0.6B, FastWAM-style, trained from scratch.
|
| 2 |
+
|
| 3 |
+
Architecture follows FastWAM and departs from it in exactly one place.
|
| 4 |
+
|
| 5 |
+
Same as FastWAM:
|
| 6 |
+
* The whole ordered segment goes through the frozen Wan2.2 48-channel VAE in
|
| 7 |
+
one pass, so its causal 3D convolutions apply both compressions: 16x spatial
|
| 8 |
+
and 4:1 temporal. [B,3,T,H,W] -> [B,48,1+(T-1)/4,h,w], with z0<-f0,
|
| 9 |
+
z1<-f1..4, z2<-f5..8. The DiT never sees RGB.
|
| 10 |
+
* Latents are patchified (1, 2, 2) into spatial tokens that survive all the way
|
| 11 |
+
through the transformer -- there is no per-frame bottleneck.
|
| 12 |
+
* Video and action are two separate experts (Mixture of Transformers): each owns
|
| 13 |
+
its own weights, and they are joined by one mixed self-attention per layer.
|
| 14 |
+
* Per-block AdaLN-Zero style modulation from a per-token timestep, plus RoPE
|
| 15 |
+
(3D over frame/height/width for video, 1D over horizon for action).
|
| 16 |
+
* Rectified-flow / flow-matching objective with the shift-based continuous
|
| 17 |
+
scheduler: x_t = (1-s) x_0 + s eps, target eps - x_0.
|
| 18 |
+
* Generation is the same joint iterative flow integration in latent + action
|
| 19 |
+
space. `HRMoTFlowModel.generate` is the latent-space core; the VAE decode and
|
| 20 |
+
state un-normalization live in `hr_inference.generate_rollout`, because the
|
| 21 |
+
VAE is deliberately kept outside this module.
|
| 22 |
+
|
| 23 |
+
Different from FastWAM:
|
| 24 |
+
* FastWAM passes human context through cross-attention. Here the ground-truth
|
| 25 |
+
human frames are VAE-encoded and placed *in the self-attention sequence* as
|
| 26 |
+
clean condition tokens, so the robot-future video and action tokens attend to
|
| 27 |
+
them directly. There is no text encoder and no cross-attention at all.
|
| 28 |
+
|
| 29 |
+
Token layout for T=9 RGB frames per stream (3 latent steps, 2 predicted):
|
| 30 |
+
|
| 31 |
+
video expert covers RGB
|
| 32 |
+
[0] robot z0 clean, t=0 condition f0
|
| 33 |
+
[1..3] human z0.. clean, t=0 condition f0 / f1-4 / f5-8
|
| 34 |
+
[4..5] robot z1.. NOISY, t=s prediction f1-4 / f5-8
|
| 35 |
+
action expert
|
| 36 |
+
[0] robot state t0 clean condition
|
| 37 |
+
[1..32] human hand motion t1..t32 clean condition
|
| 38 |
+
[33..64] robot states t1..t32 NOISY prediction
|
| 39 |
+
|
| 40 |
+
Only the robot's future latent steps and states are denoised; the robot z0 latent
|
| 41 |
+
step is restored as clean condition, exactly as FastWAM does.
|
| 42 |
+
|
| 43 |
+
Attention visibility: condition tokens see condition tokens only; prediction
|
| 44 |
+
tokens (robot-future video and robot-future action) see everything.
|
| 45 |
+
|
| 46 |
+
Human-condition availability is an extra mask layer on top of that structure,
|
| 47 |
+
not a change to it. Robot z0 is always present; by default all three human
|
| 48 |
+
latent steps, including human z0, are maskable, giving 2^Tz patterns (8 for
|
| 49 |
+
Tz=3). Masking is whole-step: all `tokens_per_frame` tokens of a human latent
|
| 50 |
+
step are dropped together,
|
| 51 |
+
never a scattered subset of patches. A missing frame is excluded as a key/value
|
| 52 |
+
so nothing reads it, its own query row is diagonal-only and discarded, and its
|
| 53 |
+
RoPE position is *not* renumbered -- the step covering f5-8 stays at position 32
|
| 54 |
+
even when the f1-4 step is absent. Supplied frames additionally carry a 0/1 availability embedding.
|
| 55 |
+
Training and inference build the mask through the same function, so at inference
|
| 56 |
+
any number of human frames can be supplied.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
from __future__ import annotations
|
| 60 |
+
|
| 61 |
+
from dataclasses import asdict, dataclass, field
|
| 62 |
+
import math
|
| 63 |
+
from typing import Optional, Sequence
|
| 64 |
+
|
| 65 |
+
import torch
|
| 66 |
+
from einops import rearrange
|
| 67 |
+
from torch import nn
|
| 68 |
+
from torch.nn import functional as F
|
| 69 |
+
|
| 70 |
+
from .wan22.mot import MoT
|
| 71 |
+
from .wan22.schedulers.scheduler_continuous import WanContinuousFlowMatchScheduler
|
| 72 |
+
from .wan22.wan_video_dit import (
|
| 73 |
+
GateModule,
|
| 74 |
+
SelfAttention,
|
| 75 |
+
precompute_freqs_cis,
|
| 76 |
+
precompute_freqs_cis_3d,
|
| 77 |
+
sinusoidal_embedding_1d,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
ROLE_ROBOT_CURRENT = 0
|
| 81 |
+
ROLE_HUMAN_CONTEXT = 1
|
| 82 |
+
ROLE_ROBOT_FUTURE = 2
|
| 83 |
+
NUM_ROLES = 3
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass(frozen=True)
|
| 87 |
+
class HRMoTConfig:
|
| 88 |
+
"""Shapes for the ~0.6B H&R MoT. Only trainable modules are counted."""
|
| 89 |
+
|
| 90 |
+
# Latent geometry, fixed by the frozen Wan2.2 VAE and the chosen image size.
|
| 91 |
+
latent_channels: int = 48
|
| 92 |
+
latent_height: int = 14
|
| 93 |
+
latent_width: int = 24
|
| 94 |
+
patch_height: int = 2
|
| 95 |
+
patch_width: int = 2
|
| 96 |
+
|
| 97 |
+
# Ordered RGB segment length handed to the VAE, per stream. The Wan2.2 VAE
|
| 98 |
+
# folds each run of 4 frames into one latent step, so T=9 -> 3 latent steps:
|
| 99 |
+
# z0 <- f0, z1 <- f1..4, z2 <- f5..8. The robot's z0 is the clean current
|
| 100 |
+
# condition; z1.. are what gets denoised.
|
| 101 |
+
num_rgb_frames: int = 9
|
| 102 |
+
vae_temporal_factor: int = 4
|
| 103 |
+
|
| 104 |
+
# Control steps between consecutive video frames. FastWAM keeps every 4th of
|
| 105 |
+
# 33 control steps as a video frame, so 9 frames span 32 steps (1.09 s at the
|
| 106 |
+
# data's 29.4 fps). Reading 9 contiguous frames instead spans 8 steps = 0.27 s,
|
| 107 |
+
# in which almost nothing happens: the gripper changes in 6.4% of 8-step
|
| 108 |
+
# windows versus 25.4% of 32-step ones.
|
| 109 |
+
frame_stride: int = 4
|
| 110 |
+
|
| 111 |
+
# Contiguous robot action steps predicted per sample, covering the video span.
|
| 112 |
+
action_horizon: int = 32
|
| 113 |
+
|
| 114 |
+
action_dim: int = 7
|
| 115 |
+
|
| 116 |
+
# Clean anchors for the action expert. Without them it predicts an absolute
|
| 117 |
+
# end-effector pose (x spans 103..346 mm) with no idea where the arm is now
|
| 118 |
+
# and no aligned human counterpart, having to infer both from pixels through
|
| 119 |
+
# the shared attention. Measured on the anchorless baseline, removing the
|
| 120 |
+
# human cost the action branch +362% -- far more than it cost video, the
|
| 121 |
+
# signature of an unanchored pathway.
|
| 122 |
+
# robot_state_f0 [7] where the arm is at t0
|
| 123 |
+
# human_action t1..tH [action_horizon, 84] raw wrist frame + hand coords
|
| 124 |
+
# False reproduces the anchorless baseline.
|
| 125 |
+
use_state_context: bool = True
|
| 126 |
+
# Keep the action-side robot-current anchor while hard-masking every mapped
|
| 127 |
+
# human-motion token. This defines the same-size human-video-only control:
|
| 128 |
+
# all modules and parameters remain present, but no 84-D human signal is a
|
| 129 |
+
# readable key/value for any prediction query.
|
| 130 |
+
use_human_motion_context: bool = True
|
| 131 |
+
human_action_dim: int = 84
|
| 132 |
+
|
| 133 |
+
# Whether the human z0 latent step may also be dropped. With it pinned on, the
|
| 134 |
+
# "no human context at all" path is never trained, its availability embedding
|
| 135 |
+
# row never receives gradient, and any measurement of that condition is out of
|
| 136 |
+
# distribution. Pinning it also lets the model lean entirely on the
|
| 137 |
+
# same-moment cross-embodiment correspondence instead of reading the
|
| 138 |
+
# demonstration. Droppable by default, as part of the same 10% regularizer.
|
| 139 |
+
droppable_human_current: bool = True
|
| 140 |
+
|
| 141 |
+
# Shared across experts -- MoT mixes attention, so head geometry must match.
|
| 142 |
+
num_layers: int = 22
|
| 143 |
+
num_heads: int = 10
|
| 144 |
+
attn_head_dim: int = 128
|
| 145 |
+
|
| 146 |
+
video_hidden_dim: int = 1280
|
| 147 |
+
video_ffn_dim: int = 5120
|
| 148 |
+
action_hidden_dim: int = 640
|
| 149 |
+
action_ffn_dim: int = 2560
|
| 150 |
+
|
| 151 |
+
freq_dim: int = 256
|
| 152 |
+
max_rope_position: int = 1024
|
| 153 |
+
eps: float = 1e-6
|
| 154 |
+
|
| 155 |
+
gradient_checkpointing: bool = True
|
| 156 |
+
|
| 157 |
+
# Human-condition availability. Robot z0 is never masked. Human z0 is
|
| 158 |
+
# droppable by default together with both human-future latent steps, yielding
|
| 159 |
+
# 2^3 = 8 patterns; --pin-human-current restores the legacy 4-pattern contract.
|
| 160 |
+
#
|
| 161 |
+
# This is a *regularizer*, not a curriculum: the point is that the model can
|
| 162 |
+
# still be asked for fewer human steps at inference, not that it should train
|
| 163 |
+
# mostly on degraded context. Dropping context on half the samples actively
|
| 164 |
+
# weakens the human pathway, which is the pathway under study. Default is 0.9
|
| 165 |
+
# full context, i.e. a 10% dropout rate.
|
| 166 |
+
full_human_context_prob: float = 0.9
|
| 167 |
+
|
| 168 |
+
# Flow-matching schedule (FastWAM defaults).
|
| 169 |
+
video_train_shift: float = 5.0
|
| 170 |
+
video_infer_shift: float = 5.0
|
| 171 |
+
action_train_shift: float = 5.0
|
| 172 |
+
action_infer_shift: float = 5.0
|
| 173 |
+
num_train_timesteps: int = 1000
|
| 174 |
+
|
| 175 |
+
# The video loss averages over ~250k scalars per sample and the action loss
|
| 176 |
+
# over ~21. Summing the two raw means gives the video term a far smaller and
|
| 177 |
+
# noisier per-element gradient, which is one of the failures the previous run
|
| 178 |
+
# hit. These weights are the knob for that balance.
|
| 179 |
+
loss_lambda_video: float = 1.0
|
| 180 |
+
loss_lambda_action: float = 1.0
|
| 181 |
+
|
| 182 |
+
def validate(self) -> None:
|
| 183 |
+
if self.use_state_context and self.human_action_dim != 84:
|
| 184 |
+
raise ValueError(
|
| 185 |
+
"raw H&R human motion must be 84-D "
|
| 186 |
+
"(transformed_hand_frames + transformed_hand_coords); "
|
| 187 |
+
f"got human_action_dim={self.human_action_dim}"
|
| 188 |
+
)
|
| 189 |
+
if self.frame_stride < 1:
|
| 190 |
+
raise ValueError(f"frame_stride must be >= 1, got {self.frame_stride}")
|
| 191 |
+
if self.action_horizon != self.video_span:
|
| 192 |
+
raise ValueError(
|
| 193 |
+
"action_horizon must equal the video span "
|
| 194 |
+
f"(num_rgb_frames-1)*frame_stride = {self.video_span}, "
|
| 195 |
+
f"got {self.action_horizon}"
|
| 196 |
+
)
|
| 197 |
+
if self.latent_height % self.patch_height or self.latent_width % self.patch_width:
|
| 198 |
+
raise ValueError(
|
| 199 |
+
f"latent size ({self.latent_height}, {self.latent_width}) must be divisible "
|
| 200 |
+
f"by DiT patch ({self.patch_height}, {self.patch_width})"
|
| 201 |
+
)
|
| 202 |
+
if self.num_rgb_frames < 5 or (self.num_rgb_frames - 1) % self.vae_temporal_factor:
|
| 203 |
+
raise ValueError(
|
| 204 |
+
"num_rgb_frames must be >=5 with (T-1) % "
|
| 205 |
+
f"{self.vae_temporal_factor} == 0, got {self.num_rgb_frames}"
|
| 206 |
+
)
|
| 207 |
+
# Guard the indices actually used, not the frame count: the video stream
|
| 208 |
+
# indexes `frame_rope_positions` and the action stream indexes up to
|
| 209 |
+
# num_action_tokens, either of which can exceed num_rgb_frames.
|
| 210 |
+
highest = max((*self.frame_rope_positions, self.num_action_tokens))
|
| 211 |
+
if highest >= self.max_rope_position:
|
| 212 |
+
raise ValueError(
|
| 213 |
+
f"RoPE position {highest} exceeds the precomputed table "
|
| 214 |
+
f"({self.max_rope_position})"
|
| 215 |
+
)
|
| 216 |
+
# rope_apply consumes head_dim/2 complex frequencies; the 3D split must
|
| 217 |
+
# add back up to exactly that or the rotation silently misaligns.
|
| 218 |
+
head_dim = self.attn_head_dim
|
| 219 |
+
f_dim = head_dim - 2 * (head_dim // 3)
|
| 220 |
+
complex_total = (f_dim // 2) + 2 * ((head_dim // 3) // 2)
|
| 221 |
+
if complex_total != head_dim // 2:
|
| 222 |
+
raise ValueError(
|
| 223 |
+
f"attn_head_dim={head_dim} does not split evenly into 3D RoPE "
|
| 224 |
+
f"({complex_total} complex frequencies, need {head_dim // 2}); "
|
| 225 |
+
"use a value such as 96 or 128"
|
| 226 |
+
)
|
| 227 |
+
for name, dim in (
|
| 228 |
+
("video_hidden_dim", self.video_hidden_dim),
|
| 229 |
+
("action_hidden_dim", self.action_hidden_dim),
|
| 230 |
+
):
|
| 231 |
+
if dim <= 0:
|
| 232 |
+
raise ValueError(f"{name} must be positive")
|
| 233 |
+
if self.num_layers <= 0 or self.num_heads <= 0:
|
| 234 |
+
raise ValueError("num_layers and num_heads must be positive")
|
| 235 |
+
|
| 236 |
+
@property
|
| 237 |
+
def num_latent_steps(self) -> int:
|
| 238 |
+
"""1 + (T-1)/4 per stream."""
|
| 239 |
+
return 1 + (self.num_rgb_frames - 1) // self.vae_temporal_factor
|
| 240 |
+
|
| 241 |
+
@property
|
| 242 |
+
def num_horizons(self) -> int:
|
| 243 |
+
"""Predicted robot latent steps: everything after the clean z0."""
|
| 244 |
+
return self.num_latent_steps - 1
|
| 245 |
+
|
| 246 |
+
@property
|
| 247 |
+
def video_span(self) -> int:
|
| 248 |
+
"""Control steps covered by the video window."""
|
| 249 |
+
return (self.num_rgb_frames - 1) * self.frame_stride
|
| 250 |
+
|
| 251 |
+
@property
|
| 252 |
+
def num_action_tokens(self) -> int:
|
| 253 |
+
"""One robot state per predicted control step."""
|
| 254 |
+
return self.action_horizon
|
| 255 |
+
|
| 256 |
+
@property
|
| 257 |
+
def latent_step_frames(self) -> tuple[int, ...]:
|
| 258 |
+
"""Last CONTROL STEP each latent step covers.
|
| 259 |
+
|
| 260 |
+
The VAE folds 4 video frames into one latent step and each video frame is
|
| 261 |
+
`frame_stride` control steps apart, so a latent step spans
|
| 262 |
+
`4 * frame_stride` control steps: with stride 4 that is 0 / 16 / 32.
|
| 263 |
+
Expressing this in control steps rather than video-frame index is what
|
| 264 |
+
lets a predicted robot latent step share a RoPE position with the human
|
| 265 |
+
latent step covering the same real time.
|
| 266 |
+
"""
|
| 267 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 268 |
+
return (0, *((index + 1) * span for index in range(self.num_latent_steps - 1)))
|
| 269 |
+
|
| 270 |
+
@property
|
| 271 |
+
def tokens_per_frame(self) -> int:
|
| 272 |
+
return (self.latent_height // self.patch_height) * (self.latent_width // self.patch_width)
|
| 273 |
+
|
| 274 |
+
@property
|
| 275 |
+
def num_action_condition_tokens(self) -> int:
|
| 276 |
+
"""Robot state at t0 plus one human-motion token per control step."""
|
| 277 |
+
return (1 + self.num_action_tokens) if self.use_state_context else 0
|
| 278 |
+
|
| 279 |
+
@property
|
| 280 |
+
def num_action_sequence(self) -> int:
|
| 281 |
+
return self.num_action_condition_tokens + self.num_action_tokens
|
| 282 |
+
|
| 283 |
+
@property
|
| 284 |
+
def action_rope_positions(self) -> tuple[int, ...]:
|
| 285 |
+
"""Control-step index per action token, condition block first.
|
| 286 |
+
|
| 287 |
+
A predicted state at step i shares its RoPE position with the human motion
|
| 288 |
+
at step i, mirroring how a predicted robot latent step shares a position
|
| 289 |
+
with the human latent step covering the same real time.
|
| 290 |
+
"""
|
| 291 |
+
future = tuple(range(1, self.num_action_tokens + 1))
|
| 292 |
+
if not self.use_state_context:
|
| 293 |
+
return future
|
| 294 |
+
return (0, *future, *future)
|
| 295 |
+
|
| 296 |
+
def human_action_latent_step(self) -> tuple[int, ...]:
|
| 297 |
+
"""Which human latent step each human-motion token follows for availability.
|
| 298 |
+
|
| 299 |
+
Control steps 1..16 fall inside latent step 1, 17..32 inside step 2, so a
|
| 300 |
+
masked human latent step masks the action tokens covering the same real
|
| 301 |
+
time. Clamped in case the horizon ever overruns the video span.
|
| 302 |
+
"""
|
| 303 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 304 |
+
last = self.num_latent_steps - 1
|
| 305 |
+
return tuple(min(1 + (index // span), last) for index in range(self.num_action_tokens))
|
| 306 |
+
|
| 307 |
+
@property
|
| 308 |
+
def num_condition_frames(self) -> int:
|
| 309 |
+
"""robot z0 + every human latent step."""
|
| 310 |
+
return 1 + self.num_latent_steps
|
| 311 |
+
|
| 312 |
+
@property
|
| 313 |
+
def num_video_frames(self) -> int:
|
| 314 |
+
"""condition slots + predicted robot latent steps."""
|
| 315 |
+
return self.num_condition_frames + self.num_horizons
|
| 316 |
+
|
| 317 |
+
@property
|
| 318 |
+
def num_condition_tokens(self) -> int:
|
| 319 |
+
return self.num_condition_frames * self.tokens_per_frame
|
| 320 |
+
|
| 321 |
+
@property
|
| 322 |
+
def num_video_tokens(self) -> int:
|
| 323 |
+
return self.num_video_frames * self.tokens_per_frame
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def frame_rope_positions(self) -> tuple[int, ...]:
|
| 327 |
+
"""Temporal RoPE index per latent-step slot, in RGB-frame units.
|
| 328 |
+
|
| 329 |
+
A predicted robot latent step shares its temporal position with the human
|
| 330 |
+
latent step covering the same frames; the role embedding is what separates
|
| 331 |
+
them. That alignment is the point.
|
| 332 |
+
"""
|
| 333 |
+
steps = self.latent_step_frames
|
| 334 |
+
return (steps[0], *steps, *steps[1:])
|
| 335 |
+
|
| 336 |
+
@property
|
| 337 |
+
def frame_roles(self) -> tuple[int, ...]:
|
| 338 |
+
return (
|
| 339 |
+
ROLE_ROBOT_CURRENT,
|
| 340 |
+
*([ROLE_HUMAN_CONTEXT] * self.num_latent_steps),
|
| 341 |
+
*([ROLE_ROBOT_FUTURE] * self.num_horizons),
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
def to_dict(self) -> dict[str, object]:
|
| 345 |
+
return asdict(self)
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def build_condition_prediction_mask(
|
| 349 |
+
*,
|
| 350 |
+
num_condition_tokens: int,
|
| 351 |
+
num_video_tokens: int,
|
| 352 |
+
num_action_tokens: int,
|
| 353 |
+
device: torch.device | None = None,
|
| 354 |
+
) -> torch.Tensor:
|
| 355 |
+
"""Visibility over the concatenated [video, action] MoT sequence.
|
| 356 |
+
|
| 357 |
+
Condition queries (robot current + human ground truth) see condition keys
|
| 358 |
+
only, so the clean context never leaks information from the noisy targets.
|
| 359 |
+
Prediction queries (robot future video + robot future action) see everything.
|
| 360 |
+
"""
|
| 361 |
+
|
| 362 |
+
if not 0 < num_condition_tokens <= num_video_tokens:
|
| 363 |
+
raise ValueError(
|
| 364 |
+
f"num_condition_tokens={num_condition_tokens} must be in (0, {num_video_tokens}]"
|
| 365 |
+
)
|
| 366 |
+
if num_action_tokens <= 0:
|
| 367 |
+
raise ValueError("num_action_tokens must be positive")
|
| 368 |
+
total = num_video_tokens + num_action_tokens
|
| 369 |
+
mask = torch.zeros((total, total), dtype=torch.bool, device=device)
|
| 370 |
+
mask[:num_condition_tokens, :num_condition_tokens] = True
|
| 371 |
+
mask[num_condition_tokens:, :] = True
|
| 372 |
+
return mask
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def build_availability_attention_mask(
|
| 376 |
+
config: "HRMoTConfig",
|
| 377 |
+
human_mask: torch.Tensor,
|
| 378 |
+
*,
|
| 379 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 380 |
+
device: torch.device | None = None,
|
| 381 |
+
) -> torch.Tensor:
|
| 382 |
+
"""Per-sample [B, 1, S, S] visibility over the concatenated [video, action] sequence.
|
| 383 |
+
|
| 384 |
+
`human_mask` is [B, 1+K] with True = that human video step was
|
| 385 |
+
supplied. `human_motion_mask` has the same shape and controls the mapped
|
| 386 |
+
84-D motion tokens. It defaults to `human_mask`, preserving the joint-mask
|
| 387 |
+
training contract and every existing caller.
|
| 388 |
+
|
| 389 |
+
Rows follow the group-level contract:
|
| 390 |
+
|
| 391 |
+
valid condition (R0, H0, available H*) -> valid condition only
|
| 392 |
+
missing condition (masked-out H*) -> itself only, output discarded
|
| 393 |
+
prediction (robot future + state) -> valid condition + prediction
|
| 394 |
+
|
| 395 |
+
Missing frames are excluded as keys entirely, so no query ever reads them.
|
| 396 |
+
Their own rows are diagonal-only purely to keep the softmax well defined; a
|
| 397 |
+
fully-False row would produce NaN.
|
| 398 |
+
"""
|
| 399 |
+
|
| 400 |
+
tokens_per_frame = config.tokens_per_frame
|
| 401 |
+
human_slots = config.num_latent_steps
|
| 402 |
+
batch = human_mask.shape[0]
|
| 403 |
+
if human_mask.shape != (batch, human_slots):
|
| 404 |
+
raise ValueError(f"human_mask must be [B, {human_slots}], got {tuple(human_mask.shape)}")
|
| 405 |
+
device = device if device is not None else human_mask.device
|
| 406 |
+
human_mask = human_mask.to(device=device, dtype=torch.bool)
|
| 407 |
+
if human_motion_mask is None:
|
| 408 |
+
human_motion_mask = human_mask
|
| 409 |
+
if human_motion_mask.shape != (batch, human_slots):
|
| 410 |
+
raise ValueError(
|
| 411 |
+
f"human_motion_mask must be [B, {human_slots}], got "
|
| 412 |
+
f"{tuple(human_motion_mask.shape)}"
|
| 413 |
+
)
|
| 414 |
+
human_motion_mask = human_motion_mask.to(device=device, dtype=torch.bool)
|
| 415 |
+
|
| 416 |
+
# --- video side: robot z0, human z0.., then the predicted robot steps ------
|
| 417 |
+
frame_available = torch.ones((batch, config.num_video_frames), dtype=torch.bool, device=device)
|
| 418 |
+
frame_available[:, 1 : 1 + human_slots] = human_mask
|
| 419 |
+
is_condition_frame = torch.zeros(config.num_video_frames, dtype=torch.bool, device=device)
|
| 420 |
+
is_condition_frame[: config.num_condition_frames] = True
|
| 421 |
+
|
| 422 |
+
valid = (frame_available & is_condition_frame[None, :]).repeat_interleave(
|
| 423 |
+
tokens_per_frame, dim=1
|
| 424 |
+
)
|
| 425 |
+
missing = ((~frame_available) & is_condition_frame[None, :]).repeat_interleave(
|
| 426 |
+
tokens_per_frame, dim=1
|
| 427 |
+
)
|
| 428 |
+
prediction = (
|
| 429 |
+
(~is_condition_frame)[None, :].expand(batch, -1).repeat_interleave(tokens_per_frame, dim=1)
|
| 430 |
+
)
|
| 431 |
+
|
| 432 |
+
# --- action side: optional clean anchors, then the predicted states --------
|
| 433 |
+
if config.use_state_context:
|
| 434 |
+
# The robot anchor at t0 is always available.
|
| 435 |
+
robot_now = torch.ones((batch, 1), dtype=torch.bool, device=device)
|
| 436 |
+
# A human-motion token inherits the availability of the latent step whose
|
| 437 |
+
# control steps it covers, so masking a human step masks its motion too.
|
| 438 |
+
steps = torch.tensor(config.human_action_latent_step(), dtype=torch.long, device=device)
|
| 439 |
+
human_now = human_motion_mask[:, steps]
|
| 440 |
+
action_valid = torch.cat((robot_now, human_now), dim=1)
|
| 441 |
+
action_missing = torch.cat((torch.zeros_like(robot_now), ~human_now), dim=1)
|
| 442 |
+
else:
|
| 443 |
+
action_valid = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 444 |
+
action_missing = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 445 |
+
action_prediction = torch.ones(
|
| 446 |
+
(batch, config.num_action_tokens), dtype=torch.bool, device=device
|
| 447 |
+
)
|
| 448 |
+
zeros_pred = torch.zeros_like(action_prediction)
|
| 449 |
+
|
| 450 |
+
valid = torch.cat((valid, action_valid, zeros_pred), dim=1)
|
| 451 |
+
missing = torch.cat((missing, action_missing, zeros_pred), dim=1)
|
| 452 |
+
prediction = torch.cat((prediction, torch.zeros_like(action_valid), action_prediction), dim=1)
|
| 453 |
+
|
| 454 |
+
total = valid.shape[1]
|
| 455 |
+
mask = valid[:, :, None] & valid[:, None, :]
|
| 456 |
+
mask |= prediction[:, :, None] & (valid | prediction)[:, None, :]
|
| 457 |
+
mask |= missing[:, :, None] & torch.eye(total, dtype=torch.bool, device=device)[None]
|
| 458 |
+
return mask.unsqueeze(1)
|
| 459 |
+
|
| 460 |
+
|
| 461 |
+
class HRDiTBlock(nn.Module):
|
| 462 |
+
"""FastWAM's DiT block minus cross-attention: all conditioning is in-sequence."""
|
| 463 |
+
|
| 464 |
+
def __init__(
|
| 465 |
+
self,
|
| 466 |
+
hidden_dim: int,
|
| 467 |
+
attn_head_dim: int,
|
| 468 |
+
num_heads: int,
|
| 469 |
+
ffn_dim: int,
|
| 470 |
+
eps: float = 1e-6,
|
| 471 |
+
) -> None:
|
| 472 |
+
super().__init__()
|
| 473 |
+
self.hidden_dim = hidden_dim
|
| 474 |
+
self.attn_head_dim = attn_head_dim
|
| 475 |
+
self.num_heads = num_heads
|
| 476 |
+
self.ffn_dim = ffn_dim
|
| 477 |
+
|
| 478 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 479 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 480 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 481 |
+
self.ffn = nn.Sequential(
|
| 482 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 483 |
+
nn.GELU(approximate="tanh"),
|
| 484 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 485 |
+
)
|
| 486 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 487 |
+
self.gate = GateModule()
|
| 488 |
+
|
| 489 |
+
|
| 490 |
+
class HRHead(nn.Module):
|
| 491 |
+
"""Final AdaLN-modulated projection, driven by the same per-token timestep."""
|
| 492 |
+
|
| 493 |
+
def __init__(self, hidden_dim: int, out_dim: int, eps: float = 1e-6) -> None:
|
| 494 |
+
super().__init__()
|
| 495 |
+
self.norm = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 496 |
+
self.head = nn.Linear(hidden_dim, out_dim)
|
| 497 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, hidden_dim) / hidden_dim**0.5)
|
| 498 |
+
|
| 499 |
+
def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 500 |
+
# x, t: [B, S, hidden]
|
| 501 |
+
modulation = self.modulation.unsqueeze(0).to(dtype=t.dtype, device=t.device)
|
| 502 |
+
shift, scale = (modulation + t.unsqueeze(2)).chunk(2, dim=2)
|
| 503 |
+
return self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
class _ExpertBase(nn.Module):
|
| 507 |
+
"""Shared timestep-modulation plumbing and the MoT-required attributes."""
|
| 508 |
+
|
| 509 |
+
def __init__(
|
| 510 |
+
self,
|
| 511 |
+
*,
|
| 512 |
+
hidden_dim: int,
|
| 513 |
+
ffn_dim: int,
|
| 514 |
+
num_layers: int,
|
| 515 |
+
num_heads: int,
|
| 516 |
+
attn_head_dim: int,
|
| 517 |
+
freq_dim: int,
|
| 518 |
+
eps: float,
|
| 519 |
+
gradient_checkpointing: bool,
|
| 520 |
+
) -> None:
|
| 521 |
+
super().__init__()
|
| 522 |
+
self.hidden_dim = hidden_dim
|
| 523 |
+
self.num_heads = num_heads
|
| 524 |
+
self.attn_head_dim = attn_head_dim
|
| 525 |
+
self.freq_dim = freq_dim
|
| 526 |
+
self.use_gradient_checkpointing = bool(gradient_checkpointing)
|
| 527 |
+
|
| 528 |
+
self.blocks = nn.ModuleList(
|
| 529 |
+
HRDiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 530 |
+
for _ in range(num_layers)
|
| 531 |
+
)
|
| 532 |
+
self.time_embedding = nn.Sequential(
|
| 533 |
+
nn.Linear(freq_dim, hidden_dim),
|
| 534 |
+
nn.SiLU(),
|
| 535 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 536 |
+
)
|
| 537 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 538 |
+
self._rope_cache: dict[tuple[torch.device, int], torch.Tensor] = {}
|
| 539 |
+
|
| 540 |
+
def embed_timesteps(self, token_timesteps: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 541 |
+
"""[B, S] per-token flow time -> (t [B, S, D], t_mod [B, S, 6, D])."""
|
| 542 |
+
|
| 543 |
+
batch, seq_len = token_timesteps.shape
|
| 544 |
+
embedded = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1).float())
|
| 545 |
+
t = self.time_embedding(embedded).reshape(batch, seq_len, self.hidden_dim)
|
| 546 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 547 |
+
return t, t_mod
|
| 548 |
+
|
| 549 |
+
|
| 550 |
+
class HRVideoExpert(_ExpertBase):
|
| 551 |
+
"""Video expert over per-frame Wan2.2 latents with 3D RoPE and role embeddings."""
|
| 552 |
+
|
| 553 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 554 |
+
super().__init__(
|
| 555 |
+
hidden_dim=config.video_hidden_dim,
|
| 556 |
+
ffn_dim=config.video_ffn_dim,
|
| 557 |
+
num_layers=config.num_layers,
|
| 558 |
+
num_heads=config.num_heads,
|
| 559 |
+
attn_head_dim=config.attn_head_dim,
|
| 560 |
+
freq_dim=config.freq_dim,
|
| 561 |
+
eps=config.eps,
|
| 562 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 563 |
+
)
|
| 564 |
+
self.config = config
|
| 565 |
+
patch = (1, config.patch_height, config.patch_width)
|
| 566 |
+
self.patch_size = patch
|
| 567 |
+
self.patch_embedding = nn.Conv3d(
|
| 568 |
+
config.latent_channels, config.video_hidden_dim, kernel_size=patch, stride=patch
|
| 569 |
+
)
|
| 570 |
+
self.role_embedding = nn.Parameter(torch.zeros(NUM_ROLES, config.video_hidden_dim))
|
| 571 |
+
# Availability code read by the *prediction* tokens. It has to live here,
|
| 572 |
+
# not on the human slots: under the hard mask nothing can read a missing
|
| 573 |
+
# frame, so a marker placed on it would be permanently unreachable and
|
| 574 |
+
# carry zero gradient. One embedding per (human slot, available?) pair,
|
| 575 |
+
# summed, tells the predictor exactly which human frames were supplied.
|
| 576 |
+
self.availability_embedding = nn.Parameter(
|
| 577 |
+
torch.zeros(config.num_latent_steps, 2, config.video_hidden_dim)
|
| 578 |
+
)
|
| 579 |
+
self.head = HRHead(
|
| 580 |
+
config.video_hidden_dim,
|
| 581 |
+
config.latent_channels * config.patch_height * config.patch_width,
|
| 582 |
+
config.eps,
|
| 583 |
+
)
|
| 584 |
+
# Kept off the module buffer registry: complex tensors do not survive DDP
|
| 585 |
+
# buffer broadcast cleanly, and these are deterministic constants anyway.
|
| 586 |
+
self._freqs_3d = precompute_freqs_cis_3d(config.attn_head_dim, end=config.max_rope_position)
|
| 587 |
+
|
| 588 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 589 |
+
"""[num_video_tokens, 1, head_dim/2] complex, in frame-major token order."""
|
| 590 |
+
|
| 591 |
+
key = (device, 0)
|
| 592 |
+
cached = self._rope_cache.get(key)
|
| 593 |
+
if cached is not None:
|
| 594 |
+
return cached
|
| 595 |
+
config = self.config
|
| 596 |
+
grid_h = config.latent_height // config.patch_height
|
| 597 |
+
grid_w = config.latent_width // config.patch_width
|
| 598 |
+
f_freqs, h_freqs, w_freqs = (x.to(device) for x in self._freqs_3d)
|
| 599 |
+
positions = torch.tensor(config.frame_rope_positions, dtype=torch.long, device=device)
|
| 600 |
+
num_frames = positions.numel()
|
| 601 |
+
freqs = torch.cat(
|
| 602 |
+
(
|
| 603 |
+
f_freqs[positions]
|
| 604 |
+
.view(num_frames, 1, 1, -1)
|
| 605 |
+
.expand(num_frames, grid_h, grid_w, -1),
|
| 606 |
+
h_freqs[:grid_h].view(1, grid_h, 1, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 607 |
+
w_freqs[:grid_w].view(1, 1, grid_w, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 608 |
+
),
|
| 609 |
+
dim=-1,
|
| 610 |
+
).reshape(num_frames * grid_h * grid_w, 1, -1)
|
| 611 |
+
self._rope_cache[key] = freqs
|
| 612 |
+
return freqs
|
| 613 |
+
|
| 614 |
+
def embed(self, latents: torch.Tensor, human_mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 615 |
+
"""[B, N, C, h, w] latents -> [B, N*tokens_per_frame, D] tokens.
|
| 616 |
+
|
| 617 |
+
`human_mask` is [B, 1+K] with True = this human frame is provided. Frames
|
| 618 |
+
marked False are replaced by `absent_human_embedding`, so they keep their
|
| 619 |
+
slot, role and RoPE position but carry no information from any episode.
|
| 620 |
+
"""
|
| 621 |
+
|
| 622 |
+
config = self.config
|
| 623 |
+
if latents.ndim != 5:
|
| 624 |
+
raise ValueError(f"latents must be [B, N, C, h, w], got {tuple(latents.shape)}")
|
| 625 |
+
if latents.shape[1] != config.num_video_frames:
|
| 626 |
+
raise ValueError(
|
| 627 |
+
f"expected {config.num_video_frames} video frames, got {latents.shape[1]}"
|
| 628 |
+
)
|
| 629 |
+
if latents.shape[2:] != (
|
| 630 |
+
config.latent_channels,
|
| 631 |
+
config.latent_height,
|
| 632 |
+
config.latent_width,
|
| 633 |
+
):
|
| 634 |
+
raise ValueError(
|
| 635 |
+
f"latent shape {tuple(latents.shape[2:])} does not match config "
|
| 636 |
+
f"({config.latent_channels}, {config.latent_height}, {config.latent_width})"
|
| 637 |
+
)
|
| 638 |
+
# patch_size[0] == 1, so the conv never mixes two frames together.
|
| 639 |
+
x = self.patch_embedding(latents.permute(0, 2, 1, 3, 4))
|
| 640 |
+
tokens = rearrange(x, "b d n h w -> b n (h w) d")
|
| 641 |
+
if human_mask is not None:
|
| 642 |
+
start = 1 # human latent steps occupy [1, 1 + num_latent_steps)
|
| 643 |
+
end = 1 + config.num_latent_steps
|
| 644 |
+
if human_mask.shape != (tokens.shape[0], end - start):
|
| 645 |
+
raise ValueError(
|
| 646 |
+
f"human_mask must be [B, {end - start}], got {tuple(human_mask.shape)}"
|
| 647 |
+
)
|
| 648 |
+
keep = human_mask[:, :, None, None].to(torch.bool).to(tokens.device)
|
| 649 |
+
# Whole-frame masking: every token of a human frame is dropped
|
| 650 |
+
# together, never a scattered subset of patches. The hard attention
|
| 651 |
+
# mask already makes these unreadable; zeroing also removes the data.
|
| 652 |
+
human = tokens[:, start:end] * keep.to(tokens.dtype)
|
| 653 |
+
# Availability code onto the robot-future (prediction) frames.
|
| 654 |
+
slots = torch.arange(end - start, device=tokens.device)
|
| 655 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 656 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 657 |
+
].sum(dim=1)[:, None, None, :]
|
| 658 |
+
future = tokens[:, end:] + code
|
| 659 |
+
tokens = torch.cat((tokens[:, :start], human, future), dim=1)
|
| 660 |
+
roles = torch.tensor(config.frame_roles, dtype=torch.long, device=latents.device)
|
| 661 |
+
tokens = tokens + self.role_embedding[roles][None, :, None, :].to(tokens.dtype)
|
| 662 |
+
return rearrange(tokens, "b n s d -> b (n s) d")
|
| 663 |
+
|
| 664 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor, num_frames: int) -> torch.Tensor:
|
| 665 |
+
"""[B, N*tokens_per_frame, D] -> [B, N, C, h, w] velocity in latent space."""
|
| 666 |
+
|
| 667 |
+
config = self.config
|
| 668 |
+
grid_h = config.latent_height // config.patch_height
|
| 669 |
+
grid_w = config.latent_width // config.patch_width
|
| 670 |
+
x = self.head(tokens, t)
|
| 671 |
+
return rearrange(
|
| 672 |
+
x,
|
| 673 |
+
"b (n h w) (c ph pw) -> b n c (h ph) (w pw)",
|
| 674 |
+
n=num_frames,
|
| 675 |
+
h=grid_h,
|
| 676 |
+
w=grid_w,
|
| 677 |
+
ph=config.patch_height,
|
| 678 |
+
pw=config.patch_width,
|
| 679 |
+
)
|
| 680 |
+
|
| 681 |
+
|
| 682 |
+
class HRActionExpert(_ExpertBase):
|
| 683 |
+
"""Action expert over one token per future horizon, with 1D RoPE on the horizon."""
|
| 684 |
+
|
| 685 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 686 |
+
super().__init__(
|
| 687 |
+
hidden_dim=config.action_hidden_dim,
|
| 688 |
+
ffn_dim=config.action_ffn_dim,
|
| 689 |
+
num_layers=config.num_layers,
|
| 690 |
+
num_heads=config.num_heads,
|
| 691 |
+
attn_head_dim=config.attn_head_dim,
|
| 692 |
+
freq_dim=config.freq_dim,
|
| 693 |
+
eps=config.eps,
|
| 694 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 695 |
+
)
|
| 696 |
+
self.config = config
|
| 697 |
+
self.action_embedding = nn.Linear(config.action_dim, config.action_hidden_dim)
|
| 698 |
+
self.availability_embedding = nn.Parameter(
|
| 699 |
+
torch.zeros(config.num_latent_steps, 2, config.action_hidden_dim)
|
| 700 |
+
)
|
| 701 |
+
if config.use_state_context:
|
| 702 |
+
# The robot anchor reuses action_embedding: it is the same 7-D
|
| 703 |
+
# quantity, so the same projection is the right one. Human hand
|
| 704 |
+
# motion is a different 84-D modality and gets its own projection.
|
| 705 |
+
self.human_action_embedding = nn.Linear(
|
| 706 |
+
config.human_action_dim, config.action_hidden_dim
|
| 707 |
+
)
|
| 708 |
+
self.action_role_embedding = nn.Parameter(
|
| 709 |
+
torch.zeros(NUM_ROLES, config.action_hidden_dim)
|
| 710 |
+
)
|
| 711 |
+
self.head = HRHead(config.action_hidden_dim, config.action_dim, config.eps)
|
| 712 |
+
self._freqs_1d = precompute_freqs_cis(config.attn_head_dim, end=config.max_rope_position)
|
| 713 |
+
|
| 714 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 715 |
+
key = (device, 0)
|
| 716 |
+
cached = self._rope_cache.get(key)
|
| 717 |
+
if cached is not None:
|
| 718 |
+
return cached
|
| 719 |
+
positions = torch.tensor(self.config.action_rope_positions, dtype=torch.long, device=device)
|
| 720 |
+
freqs = self._freqs_1d.to(device)[positions].view(positions.numel(), 1, -1)
|
| 721 |
+
self._rope_cache[key] = freqs
|
| 722 |
+
return freqs
|
| 723 |
+
|
| 724 |
+
def embed(
|
| 725 |
+
self,
|
| 726 |
+
actions: torch.Tensor,
|
| 727 |
+
human_mask: torch.Tensor | None = None,
|
| 728 |
+
robot_current_state: torch.Tensor | None = None,
|
| 729 |
+
human_future_action: torch.Tensor | None = None,
|
| 730 |
+
) -> torch.Tensor:
|
| 731 |
+
"""-> [B, num_action_sequence, D], condition block first when enabled."""
|
| 732 |
+
|
| 733 |
+
config = self.config
|
| 734 |
+
if actions.ndim != 3 or actions.shape[1:] != (
|
| 735 |
+
config.num_action_tokens,
|
| 736 |
+
config.action_dim,
|
| 737 |
+
):
|
| 738 |
+
raise ValueError(
|
| 739 |
+
f"actions must be [B, {config.num_action_tokens}, {config.action_dim}], "
|
| 740 |
+
f"got {tuple(actions.shape)}"
|
| 741 |
+
)
|
| 742 |
+
predicted = self.action_embedding(actions)
|
| 743 |
+
if config.use_state_context:
|
| 744 |
+
if robot_current_state is None or human_future_action is None:
|
| 745 |
+
raise ValueError(
|
| 746 |
+
"use_state_context requires robot_current_state and 84-D human_future_action"
|
| 747 |
+
)
|
| 748 |
+
if robot_current_state.shape[1:] != (config.action_dim,):
|
| 749 |
+
raise ValueError(
|
| 750 |
+
f"robot_current_state must be [B, {config.action_dim}], "
|
| 751 |
+
f"got {tuple(robot_current_state.shape)}"
|
| 752 |
+
)
|
| 753 |
+
if human_future_action.shape[1:] != (
|
| 754 |
+
config.num_action_tokens,
|
| 755 |
+
config.human_action_dim,
|
| 756 |
+
):
|
| 757 |
+
raise ValueError(
|
| 758 |
+
f"human_future_action must be [B, {config.num_action_tokens}, "
|
| 759 |
+
f"{config.human_action_dim}], got {tuple(human_future_action.shape)}"
|
| 760 |
+
)
|
| 761 |
+
role = self.action_role_embedding.to(predicted.dtype)
|
| 762 |
+
anchor = self.action_embedding(robot_current_state)[:, None, :]
|
| 763 |
+
anchor = anchor + role[ROLE_ROBOT_CURRENT]
|
| 764 |
+
human = self.human_action_embedding(human_future_action) + role[ROLE_HUMAN_CONTEXT]
|
| 765 |
+
if human_mask is not None:
|
| 766 |
+
# Zero a masked step's human-motion tokens as well; the hard attention
|
| 767 |
+
# mask already makes them unreadable, this also drops the data.
|
| 768 |
+
steps = torch.tensor(config.human_action_latent_step(), device=human.device)
|
| 769 |
+
keep = human_mask.to(human.device)[:, steps][:, :, None]
|
| 770 |
+
human = human * keep.to(human.dtype)
|
| 771 |
+
predicted = predicted + role[ROLE_ROBOT_FUTURE]
|
| 772 |
+
tokens = torch.cat((anchor, human, predicted), dim=1)
|
| 773 |
+
else:
|
| 774 |
+
tokens = predicted
|
| 775 |
+
if human_mask is not None:
|
| 776 |
+
slots = torch.arange(human_mask.shape[1], device=tokens.device)
|
| 777 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 778 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 779 |
+
].sum(dim=1)[:, None, :]
|
| 780 |
+
tokens = tokens + code
|
| 781 |
+
return tokens
|
| 782 |
+
|
| 783 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 784 |
+
return self.head(tokens, t)
|
| 785 |
+
|
| 786 |
+
|
| 787 |
+
class HRMoTFlowModel(nn.Module):
|
| 788 |
+
"""The trainable ~0.6B model. VAE encoding happens outside, in the trainer."""
|
| 789 |
+
|
| 790 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 791 |
+
super().__init__()
|
| 792 |
+
config.validate()
|
| 793 |
+
self.config = config
|
| 794 |
+
# MoT owns the experts. Registering them a second time on this module
|
| 795 |
+
# would duplicate every tensor in state_dict, so they are reached through
|
| 796 |
+
# properties instead of attributes.
|
| 797 |
+
self.mot = MoT(
|
| 798 |
+
mixtures={"video": HRVideoExpert(config), "action": HRActionExpert(config)},
|
| 799 |
+
mot_checkpoint_mixed_attn=config.gradient_checkpointing,
|
| 800 |
+
)
|
| 801 |
+
self.train_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 802 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_train_shift
|
| 803 |
+
)
|
| 804 |
+
self.infer_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 805 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_infer_shift
|
| 806 |
+
)
|
| 807 |
+
self.train_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 808 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_train_shift
|
| 809 |
+
)
|
| 810 |
+
self.infer_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 811 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_infer_shift
|
| 812 |
+
)
|
| 813 |
+
self.reset_parameters()
|
| 814 |
+
|
| 815 |
+
@property
|
| 816 |
+
def video_expert(self) -> HRVideoExpert:
|
| 817 |
+
return self.mot.mixtures["video"]
|
| 818 |
+
|
| 819 |
+
@property
|
| 820 |
+
def action_expert(self) -> HRActionExpert:
|
| 821 |
+
return self.mot.mixtures["action"]
|
| 822 |
+
|
| 823 |
+
def reset_parameters(self) -> None:
|
| 824 |
+
"""Random init only. No pretrained weights enter the trainable model."""
|
| 825 |
+
|
| 826 |
+
def init_linear(module: nn.Module) -> None:
|
| 827 |
+
if isinstance(module, (nn.Linear, nn.Conv3d)):
|
| 828 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 829 |
+
if module.bias is not None:
|
| 830 |
+
nn.init.zeros_(module.bias)
|
| 831 |
+
|
| 832 |
+
self.apply(init_linear)
|
| 833 |
+
nn.init.normal_(self.video_expert.role_embedding, mean=0.0, std=0.02)
|
| 834 |
+
for expert in (self.video_expert, self.action_expert):
|
| 835 |
+
nn.init.normal_(expert.availability_embedding, mean=0.0, std=0.02)
|
| 836 |
+
if self.config.use_state_context:
|
| 837 |
+
nn.init.normal_(self.action_expert.action_role_embedding, mean=0.0, std=0.02)
|
| 838 |
+
# Wan/DiT init: `modulation` keeps its randn/sqrt(dim) scale (set in the
|
| 839 |
+
# block) and residual output projections are down-scaled by depth so a
|
| 840 |
+
# 22-layer stack does not blow up at step 0.
|
| 841 |
+
residual_std = 0.02 / math.sqrt(2.0 * self.config.num_layers)
|
| 842 |
+
# The final head is initialized *near* zero rather than at zero. Exactly
|
| 843 |
+
# zero makes the model emit zero velocity, which is stable, but it also
|
| 844 |
+
# makes d(loss)/d(head input) identically zero: on the first step only the
|
| 845 |
+
# two head tensors per expert receive gradient and the other 679 do not.
|
| 846 |
+
# A tiny nonzero scale keeps the near-zero start and lets gradient reach
|
| 847 |
+
# every parameter from step 1.
|
| 848 |
+
head_std = 1e-4
|
| 849 |
+
for expert in (self.video_expert, self.action_expert):
|
| 850 |
+
for block in expert.blocks:
|
| 851 |
+
nn.init.normal_(block.self_attn.o.weight, mean=0.0, std=residual_std)
|
| 852 |
+
nn.init.normal_(block.ffn[-1].weight, mean=0.0, std=residual_std)
|
| 853 |
+
nn.init.normal_(expert.head.head.weight, mean=0.0, std=head_std)
|
| 854 |
+
nn.init.zeros_(expert.head.head.bias)
|
| 855 |
+
|
| 856 |
+
def attention_mask(
|
| 857 |
+
self,
|
| 858 |
+
human_mask: torch.Tensor,
|
| 859 |
+
*,
|
| 860 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 861 |
+
device: torch.device,
|
| 862 |
+
) -> torch.Tensor:
|
| 863 |
+
return build_availability_attention_mask(
|
| 864 |
+
self.config,
|
| 865 |
+
human_mask,
|
| 866 |
+
human_motion_mask=human_motion_mask,
|
| 867 |
+
device=device,
|
| 868 |
+
)
|
| 869 |
+
|
| 870 |
+
def human_availability_patterns(self, device: torch.device) -> torch.Tensor:
|
| 871 |
+
"""Every availability pattern over the maskable human latent steps.
|
| 872 |
+
|
| 873 |
+
All 2^Tz patterns when the human current step is droppable, otherwise the
|
| 874 |
+
2^(Tz-1) patterns that keep it.
|
| 875 |
+
"""
|
| 876 |
+
|
| 877 |
+
slots = self.config.num_latent_steps
|
| 878 |
+
if not self.config.droppable_human_current:
|
| 879 |
+
slots -= 1
|
| 880 |
+
codes = torch.arange(2**slots, device=device)
|
| 881 |
+
bits = torch.arange(slots, device=device)
|
| 882 |
+
return ((codes[:, None] >> bits[None, :]) & 1).bool()
|
| 883 |
+
|
| 884 |
+
def sample_human_mask(
|
| 885 |
+
self,
|
| 886 |
+
batch: int,
|
| 887 |
+
*,
|
| 888 |
+
device: torch.device,
|
| 889 |
+
generator: Optional[torch.Generator] = None,
|
| 890 |
+
) -> torch.Tensor:
|
| 891 |
+
"""[B, Tz] bool. True = that human latent step is supplied.
|
| 892 |
+
|
| 893 |
+
`full_human_context_prob` of the batch gets the complete context so
|
| 894 |
+
full-context quality does not regress; the rest are drawn *uniformly* over
|
| 895 |
+
every other pattern. This is a regularizer, not a curriculum.
|
| 896 |
+
|
| 897 |
+
When `droppable_human_current` is set, the human z0 step is included in
|
| 898 |
+
the draw, so "no human context at all" is a trained condition rather than
|
| 899 |
+
an out-of-distribution query, and the model cannot lean entirely on the
|
| 900 |
+
same-moment cross-embodiment correspondence.
|
| 901 |
+
"""
|
| 902 |
+
|
| 903 |
+
config = self.config
|
| 904 |
+
patterns = self.human_availability_patterns(device)
|
| 905 |
+
# The last row is the all-ones pattern; draw the others uniformly.
|
| 906 |
+
choice = torch.randint(
|
| 907 |
+
0, patterns.shape[0] - 1, (batch,), device=device, generator=generator
|
| 908 |
+
)
|
| 909 |
+
drawn = patterns[choice]
|
| 910 |
+
use_full = torch.rand(batch, device=device, generator=generator) < float(
|
| 911 |
+
config.full_human_context_prob
|
| 912 |
+
)
|
| 913 |
+
drawn = torch.where(use_full[:, None], torch.ones_like(drawn), drawn)
|
| 914 |
+
if config.droppable_human_current:
|
| 915 |
+
return drawn
|
| 916 |
+
current = torch.ones((batch, 1), dtype=torch.bool, device=device)
|
| 917 |
+
return torch.cat((current, drawn), dim=1)
|
| 918 |
+
|
| 919 |
+
def _token_timesteps(
|
| 920 |
+
self, timestep: torch.Tensor, *, num_frames: int, noisy_frames: int
|
| 921 |
+
) -> torch.Tensor:
|
| 922 |
+
"""Clean condition frames get t=0; only the robot future frames carry t=s."""
|
| 923 |
+
|
| 924 |
+
config = self.config
|
| 925 |
+
batch = timestep.shape[0]
|
| 926 |
+
per_frame = torch.zeros((batch, num_frames), dtype=torch.float32, device=timestep.device)
|
| 927 |
+
per_frame[:, num_frames - noisy_frames :] = timestep.float()[:, None]
|
| 928 |
+
return per_frame.repeat_interleave(config.tokens_per_frame, dim=1)
|
| 929 |
+
|
| 930 |
+
def forward_tokens(
|
| 931 |
+
self,
|
| 932 |
+
*,
|
| 933 |
+
robot_current_latent: torch.Tensor,
|
| 934 |
+
human_latents: torch.Tensor,
|
| 935 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 936 |
+
noisy_robot_future_action: torch.Tensor,
|
| 937 |
+
timestep_video: torch.Tensor,
|
| 938 |
+
timestep_action: torch.Tensor,
|
| 939 |
+
human_mask: torch.Tensor | None = None,
|
| 940 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 941 |
+
robot_current_state: torch.Tensor | None = None,
|
| 942 |
+
human_future_action: torch.Tensor | None = None,
|
| 943 |
+
) -> tuple[dict[str, torch.Tensor], torch.Tensor, torch.Tensor]:
|
| 944 |
+
"""Run the MoT and return (tokens_out, video_t, action_t).
|
| 945 |
+
|
| 946 |
+
`tokens_out["video"]` still holds the condition positions, which
|
| 947 |
+
`predict_velocity` drops. Tests use them to prove the attention mask
|
| 948 |
+
really isolates condition tokens from the noisy prediction tokens.
|
| 949 |
+
"""
|
| 950 |
+
|
| 951 |
+
config = self.config
|
| 952 |
+
if robot_current_latent.ndim != 5 or robot_current_latent.shape[1] != 1:
|
| 953 |
+
raise ValueError(
|
| 954 |
+
f"robot_current_latent must be [B, 1, C, h, w], got "
|
| 955 |
+
f"{tuple(robot_current_latent.shape)}"
|
| 956 |
+
)
|
| 957 |
+
if human_latents.shape[1] != config.num_latent_steps:
|
| 958 |
+
raise ValueError(
|
| 959 |
+
f"human_latents must carry {config.num_latent_steps} latent steps, "
|
| 960 |
+
f"got {human_latents.shape[1]}"
|
| 961 |
+
)
|
| 962 |
+
if noisy_robot_future_latents.shape[1] != config.num_horizons:
|
| 963 |
+
raise ValueError(
|
| 964 |
+
f"noisy_robot_future_latents must carry {config.num_horizons} horizons, "
|
| 965 |
+
f"got {noisy_robot_future_latents.shape[1]}"
|
| 966 |
+
)
|
| 967 |
+
|
| 968 |
+
latents = torch.cat(
|
| 969 |
+
(robot_current_latent, human_latents, noisy_robot_future_latents), dim=1
|
| 970 |
+
)
|
| 971 |
+
device = latents.device
|
| 972 |
+
|
| 973 |
+
if human_mask is None:
|
| 974 |
+
human_mask = torch.ones(
|
| 975 |
+
(latents.shape[0], config.num_latent_steps),
|
| 976 |
+
dtype=torch.bool,
|
| 977 |
+
device=device,
|
| 978 |
+
)
|
| 979 |
+
if human_motion_mask is None:
|
| 980 |
+
human_motion_mask = (
|
| 981 |
+
human_mask if config.use_human_motion_context else torch.zeros_like(human_mask)
|
| 982 |
+
)
|
| 983 |
+
video_tokens = self.video_expert.embed(latents, human_mask=human_mask)
|
| 984 |
+
action_tokens = self.action_expert.embed(
|
| 985 |
+
noisy_robot_future_action,
|
| 986 |
+
human_mask=human_motion_mask,
|
| 987 |
+
robot_current_state=robot_current_state,
|
| 988 |
+
human_future_action=human_future_action,
|
| 989 |
+
)
|
| 990 |
+
|
| 991 |
+
video_token_t = self._token_timesteps(
|
| 992 |
+
timestep_video,
|
| 993 |
+
num_frames=config.num_video_frames,
|
| 994 |
+
noisy_frames=config.num_horizons,
|
| 995 |
+
)
|
| 996 |
+
# Condition tokens are clean (t=0); only the predicted states carry t=s.
|
| 997 |
+
action_token_t = torch.zeros(
|
| 998 |
+
(latents.shape[0], config.num_action_sequence),
|
| 999 |
+
dtype=torch.float32,
|
| 1000 |
+
device=device,
|
| 1001 |
+
)
|
| 1002 |
+
action_token_t[:, config.num_action_condition_tokens :] = timestep_action.float()[:, None]
|
| 1003 |
+
|
| 1004 |
+
video_t, video_t_mod = self.video_expert.embed_timesteps(video_token_t)
|
| 1005 |
+
action_t, action_t_mod = self.action_expert.embed_timesteps(action_token_t)
|
| 1006 |
+
|
| 1007 |
+
mask = self.attention_mask(human_mask, human_motion_mask=human_motion_mask, device=device)
|
| 1008 |
+
tokens_out = self.mot(
|
| 1009 |
+
embeds_all={"video": video_tokens, "action": action_tokens},
|
| 1010 |
+
attention_mask=mask,
|
| 1011 |
+
freqs_all={
|
| 1012 |
+
"video": self.video_expert.rope_freqs(device),
|
| 1013 |
+
"action": self.action_expert.rope_freqs(device),
|
| 1014 |
+
},
|
| 1015 |
+
# No cross-attention: human context lives in the self-attention sequence.
|
| 1016 |
+
context_all={"video": None, "action": None},
|
| 1017 |
+
t_mod_all={"video": video_t_mod, "action": action_t_mod},
|
| 1018 |
+
)
|
| 1019 |
+
return tokens_out, video_t, action_t
|
| 1020 |
+
|
| 1021 |
+
def predict_velocity(
|
| 1022 |
+
self,
|
| 1023 |
+
*,
|
| 1024 |
+
robot_current_latent: torch.Tensor,
|
| 1025 |
+
human_latents: torch.Tensor,
|
| 1026 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 1027 |
+
noisy_robot_future_action: torch.Tensor,
|
| 1028 |
+
timestep_video: torch.Tensor,
|
| 1029 |
+
timestep_action: torch.Tensor,
|
| 1030 |
+
human_mask: torch.Tensor | None = None,
|
| 1031 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 1032 |
+
robot_current_state: torch.Tensor | None = None,
|
| 1033 |
+
human_future_action: torch.Tensor | None = None,
|
| 1034 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1035 |
+
"""Return flow velocity for the robot future latents and actions."""
|
| 1036 |
+
|
| 1037 |
+
config = self.config
|
| 1038 |
+
tokens_out, video_t, action_t = self.forward_tokens(
|
| 1039 |
+
robot_current_latent=robot_current_latent,
|
| 1040 |
+
human_latents=human_latents,
|
| 1041 |
+
noisy_robot_future_latents=noisy_robot_future_latents,
|
| 1042 |
+
noisy_robot_future_action=noisy_robot_future_action,
|
| 1043 |
+
timestep_video=timestep_video,
|
| 1044 |
+
timestep_action=timestep_action,
|
| 1045 |
+
human_mask=human_mask,
|
| 1046 |
+
human_motion_mask=human_motion_mask,
|
| 1047 |
+
robot_current_state=robot_current_state,
|
| 1048 |
+
human_future_action=human_future_action,
|
| 1049 |
+
)
|
| 1050 |
+
# Only the robot-future slice is a prediction; drop the condition tokens.
|
| 1051 |
+
start = config.num_condition_tokens
|
| 1052 |
+
pred_video = self.video_expert.unembed(
|
| 1053 |
+
tokens_out["video"][:, start:, :],
|
| 1054 |
+
video_t[:, start:, :],
|
| 1055 |
+
num_frames=config.num_horizons,
|
| 1056 |
+
)
|
| 1057 |
+
start_action = config.num_action_condition_tokens
|
| 1058 |
+
pred_action = self.action_expert.unembed(
|
| 1059 |
+
tokens_out["action"][:, start_action:, :], action_t[:, start_action:, :]
|
| 1060 |
+
)
|
| 1061 |
+
return pred_video, pred_action
|
| 1062 |
+
|
| 1063 |
+
def training_loss(
|
| 1064 |
+
self,
|
| 1065 |
+
*,
|
| 1066 |
+
robot_current_latent: torch.Tensor,
|
| 1067 |
+
human_latents: torch.Tensor,
|
| 1068 |
+
robot_future_latents: torch.Tensor,
|
| 1069 |
+
robot_future_action: torch.Tensor,
|
| 1070 |
+
generator: Optional[torch.Generator] = None,
|
| 1071 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1072 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1073 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1074 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1075 |
+
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 1076 |
+
config = self.config
|
| 1077 |
+
batch = robot_future_latents.shape[0]
|
| 1078 |
+
device = robot_future_latents.device
|
| 1079 |
+
dtype = robot_future_latents.dtype
|
| 1080 |
+
|
| 1081 |
+
timestep_video = self.train_video_scheduler.sample_training_t(batch, device, dtype)
|
| 1082 |
+
timestep_action = self.train_action_scheduler.sample_training_t(batch, device, dtype)
|
| 1083 |
+
|
| 1084 |
+
noise_video = torch.randn(
|
| 1085 |
+
robot_future_latents.shape, device=device, dtype=dtype, generator=generator
|
| 1086 |
+
)
|
| 1087 |
+
noise_action = torch.randn(
|
| 1088 |
+
robot_future_action.shape, device=device, dtype=dtype, generator=generator
|
| 1089 |
+
)
|
| 1090 |
+
noisy_video = self.train_video_scheduler.add_noise(
|
| 1091 |
+
robot_future_latents, noise_video, timestep_video
|
| 1092 |
+
)
|
| 1093 |
+
noisy_action = self.train_action_scheduler.add_noise(
|
| 1094 |
+
robot_future_action, noise_action, timestep_action
|
| 1095 |
+
)
|
| 1096 |
+
target_video = self.train_video_scheduler.training_target(
|
| 1097 |
+
robot_future_latents, noise_video, timestep_video
|
| 1098 |
+
)
|
| 1099 |
+
target_action = self.train_action_scheduler.training_target(
|
| 1100 |
+
robot_future_action, noise_action, timestep_action
|
| 1101 |
+
)
|
| 1102 |
+
|
| 1103 |
+
if human_mask is None:
|
| 1104 |
+
human_mask = self.sample_human_mask(batch, device=device, generator=generator)
|
| 1105 |
+
|
| 1106 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1107 |
+
robot_current_latent=robot_current_latent,
|
| 1108 |
+
human_latents=human_latents,
|
| 1109 |
+
noisy_robot_future_latents=noisy_video,
|
| 1110 |
+
noisy_robot_future_action=noisy_action,
|
| 1111 |
+
timestep_video=timestep_video,
|
| 1112 |
+
timestep_action=timestep_action,
|
| 1113 |
+
human_mask=human_mask,
|
| 1114 |
+
human_motion_mask=human_motion_mask,
|
| 1115 |
+
robot_current_state=robot_current_state,
|
| 1116 |
+
human_future_action=human_future_action,
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
# Per-sample means, then the scheduler's timestep weighting -- matching
|
| 1120 |
+
# FastWAM rather than averaging a single scalar over the whole batch.
|
| 1121 |
+
video_per_sample = (pred_video.float() - target_video.float()).pow(2).flatten(1).mean(dim=1)
|
| 1122 |
+
action_per_sample = (
|
| 1123 |
+
(pred_action.float() - target_action.float()).pow(2).flatten(1).mean(dim=1)
|
| 1124 |
+
)
|
| 1125 |
+
video_weight = self.train_video_scheduler.training_weight(timestep_video).to(
|
| 1126 |
+
video_per_sample.device, video_per_sample.dtype
|
| 1127 |
+
)
|
| 1128 |
+
action_weight = self.train_action_scheduler.training_weight(timestep_action).to(
|
| 1129 |
+
action_per_sample.device, action_per_sample.dtype
|
| 1130 |
+
)
|
| 1131 |
+
loss_video = (video_per_sample * video_weight).mean()
|
| 1132 |
+
loss_action = (action_per_sample * action_weight).mean()
|
| 1133 |
+
total = config.loss_lambda_video * loss_video + config.loss_lambda_action * loss_action
|
| 1134 |
+
return total, {
|
| 1135 |
+
"loss_video": loss_video.detach(),
|
| 1136 |
+
"loss_action": loss_action.detach(),
|
| 1137 |
+
"loss_video_unweighted": video_per_sample.mean().detach(),
|
| 1138 |
+
"loss_action_unweighted": action_per_sample.mean().detach(),
|
| 1139 |
+
"human_frames_kept": human_mask.sum(dim=1).float().mean().detach(),
|
| 1140 |
+
}
|
| 1141 |
+
|
| 1142 |
+
@torch.no_grad()
|
| 1143 |
+
def generate(
|
| 1144 |
+
self,
|
| 1145 |
+
*,
|
| 1146 |
+
robot_current_latent: torch.Tensor,
|
| 1147 |
+
human_latents: torch.Tensor,
|
| 1148 |
+
num_inference_steps: int = 20,
|
| 1149 |
+
sigma_shift: Optional[float] = None,
|
| 1150 |
+
generator: Optional[torch.Generator] = None,
|
| 1151 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1152 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1153 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1154 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1155 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1156 |
+
"""FastWAM-style joint flow integration in latent + action space.
|
| 1157 |
+
|
| 1158 |
+
This is the latent-space core and returns
|
| 1159 |
+
(robot_future_latents, normalized robot_future_state). It does not touch
|
| 1160 |
+
the VAE, which lives outside the model so DDP never syncs its 705M frozen
|
| 1161 |
+
parameters. For RGB frames and un-normalized state use
|
| 1162 |
+
`fasterwam.models.hr_inference.generate_rollout`.
|
| 1163 |
+
|
| 1164 |
+
`human_mask` is [B, 1+K] and controls human video steps.
|
| 1165 |
+
`human_motion_mask` controls the 84-D motion tokens mapped to those
|
| 1166 |
+
steps. It defaults to `human_mask` for the standard model and to an
|
| 1167 |
+
all-False mask for a configured human-video-only model.
|
| 1168 |
+
"""
|
| 1169 |
+
|
| 1170 |
+
config = self.config
|
| 1171 |
+
batch = robot_current_latent.shape[0]
|
| 1172 |
+
device = robot_current_latent.device
|
| 1173 |
+
dtype = robot_current_latent.dtype
|
| 1174 |
+
|
| 1175 |
+
latents_video = torch.randn(
|
| 1176 |
+
(
|
| 1177 |
+
batch,
|
| 1178 |
+
config.num_horizons,
|
| 1179 |
+
config.latent_channels,
|
| 1180 |
+
config.latent_height,
|
| 1181 |
+
config.latent_width,
|
| 1182 |
+
),
|
| 1183 |
+
device=device,
|
| 1184 |
+
dtype=dtype,
|
| 1185 |
+
generator=generator,
|
| 1186 |
+
)
|
| 1187 |
+
latents_action = torch.randn(
|
| 1188 |
+
(batch, config.num_action_tokens, config.action_dim),
|
| 1189 |
+
device=device,
|
| 1190 |
+
dtype=dtype,
|
| 1191 |
+
generator=generator,
|
| 1192 |
+
)
|
| 1193 |
+
|
| 1194 |
+
timesteps_video, deltas_video = self.infer_video_scheduler.build_inference_schedule(
|
| 1195 |
+
num_inference_steps=num_inference_steps,
|
| 1196 |
+
device=device,
|
| 1197 |
+
dtype=dtype,
|
| 1198 |
+
shift_override=sigma_shift,
|
| 1199 |
+
)
|
| 1200 |
+
timesteps_action, deltas_action = self.infer_action_scheduler.build_inference_schedule(
|
| 1201 |
+
num_inference_steps=num_inference_steps,
|
| 1202 |
+
device=device,
|
| 1203 |
+
dtype=dtype,
|
| 1204 |
+
shift_override=sigma_shift,
|
| 1205 |
+
)
|
| 1206 |
+
|
| 1207 |
+
for step in range(num_inference_steps):
|
| 1208 |
+
step_t_video = timesteps_video[step].expand(batch)
|
| 1209 |
+
step_t_action = timesteps_action[step].expand(batch)
|
| 1210 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1211 |
+
robot_current_latent=robot_current_latent,
|
| 1212 |
+
human_latents=human_latents,
|
| 1213 |
+
noisy_robot_future_latents=latents_video,
|
| 1214 |
+
noisy_robot_future_action=latents_action,
|
| 1215 |
+
timestep_video=step_t_video,
|
| 1216 |
+
timestep_action=step_t_action,
|
| 1217 |
+
human_mask=human_mask,
|
| 1218 |
+
human_motion_mask=human_motion_mask,
|
| 1219 |
+
robot_current_state=robot_current_state,
|
| 1220 |
+
human_future_action=human_future_action,
|
| 1221 |
+
)
|
| 1222 |
+
latents_video = self.infer_video_scheduler.step(
|
| 1223 |
+
pred_video, deltas_video[step], latents_video
|
| 1224 |
+
)
|
| 1225 |
+
latents_action = self.infer_action_scheduler.step(
|
| 1226 |
+
pred_action, deltas_action[step], latents_action
|
| 1227 |
+
)
|
| 1228 |
+
return latents_video, latents_action
|
| 1229 |
+
|
| 1230 |
+
def forward(self, *args, **kwargs):
|
| 1231 |
+
return self.training_loss(*args, **kwargs)
|
| 1232 |
+
|
| 1233 |
+
|
| 1234 |
+
def count_parameters(model: nn.Module) -> int:
|
| 1235 |
+
return sum(parameter.numel() for parameter in model.parameters())
|
| 1236 |
+
|
| 1237 |
+
|
| 1238 |
+
def parameter_breakdown(model: HRMoTFlowModel) -> dict[str, int]:
|
| 1239 |
+
return {
|
| 1240 |
+
"total": count_parameters(model),
|
| 1241 |
+
"video_expert": count_parameters(model.video_expert),
|
| 1242 |
+
"action_expert": count_parameters(model.action_expert),
|
| 1243 |
+
"video_blocks": sum(count_parameters(b) for b in model.video_expert.blocks),
|
| 1244 |
+
"action_blocks": sum(count_parameters(b) for b in model.action_expert.blocks),
|
| 1245 |
+
}
|
tools/model_code/recorded/arm/wan22/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/arm/wan22/helpers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/arm/wan22/helpers/gradient.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def create_custom_forward(module):
|
| 5 |
+
def custom_forward(*inputs, **kwargs):
|
| 6 |
+
return module(*inputs, **kwargs)
|
| 7 |
+
|
| 8 |
+
return custom_forward
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def gradient_checkpoint_forward(
|
| 12 |
+
model,
|
| 13 |
+
use_gradient_checkpointing,
|
| 14 |
+
*args,
|
| 15 |
+
**kwargs,
|
| 16 |
+
):
|
| 17 |
+
if use_gradient_checkpointing:
|
| 18 |
+
model_output = torch.utils.checkpoint.checkpoint(
|
| 19 |
+
create_custom_forward(model),
|
| 20 |
+
*args,
|
| 21 |
+
**kwargs,
|
| 22 |
+
use_reentrant=False,
|
| 23 |
+
)
|
| 24 |
+
else:
|
| 25 |
+
model_output = model(*args, **kwargs)
|
| 26 |
+
return model_output
|
tools/model_code/recorded/arm/wan22/mot.py
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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ence
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
from .wan_video_dit import flash_attention, modulate, rope_apply
|
| 9 |
+
from logging import getLogger as get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class MoT(nn.Module):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
mixtures: Dict[str, nn.Module],
|
| 18 |
+
mot_checkpoint_mixed_attn: bool = True,
|
| 19 |
+
):
|
| 20 |
+
super().__init__()
|
| 21 |
+
if not mixtures:
|
| 22 |
+
raise ValueError("`mixtures` cannot be empty.")
|
| 23 |
+
if "video" not in mixtures or "action" not in mixtures:
|
| 24 |
+
raise ValueError("`mixtures` must include both 'video' and 'action' experts.")
|
| 25 |
+
|
| 26 |
+
self.mixtures = nn.ModuleDict(mixtures)
|
| 27 |
+
self.expert_order = list(self.mixtures.keys())
|
| 28 |
+
self.mot_checkpoint_mixed_attn = mot_checkpoint_mixed_attn
|
| 29 |
+
if mot_checkpoint_mixed_attn:
|
| 30 |
+
logger.info(
|
| 31 |
+
"Using gradient checkpointing for mixture attention. This will save memory but use more computation."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
first_expert = self.mixtures[self.expert_order[0]]
|
| 35 |
+
self.num_layers = len(first_expert.blocks)
|
| 36 |
+
self.num_heads = first_expert.num_heads
|
| 37 |
+
self.attn_head_dim = first_expert.attn_head_dim
|
| 38 |
+
|
| 39 |
+
for name in self.expert_order[1:]:
|
| 40 |
+
expert = self.mixtures[name]
|
| 41 |
+
if len(expert.blocks) != self.num_layers:
|
| 42 |
+
raise ValueError(
|
| 43 |
+
f"All experts must have same number of layers; got {self.num_layers} and {len(expert.blocks)}"
|
| 44 |
+
)
|
| 45 |
+
if expert.num_heads != self.num_heads:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"All experts must have same num_heads; got {self.num_heads} and {expert.num_heads}"
|
| 48 |
+
)
|
| 49 |
+
if expert.attn_head_dim != self.attn_head_dim:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
"All experts must have same attn_head_dim; "
|
| 52 |
+
f"got {self.attn_head_dim} and {expert.attn_head_dim}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
logger.info(
|
| 56 |
+
f"Initialized MoT with experts: {self.expert_order}, num_layers={self.num_layers}"
|
| 57 |
+
)
|
| 58 |
+
for name in self.expert_order:
|
| 59 |
+
expert = self.mixtures[name]
|
| 60 |
+
logger.info(
|
| 61 |
+
f" Expert '{name}': num_params={sum(p.numel() for p in expert.parameters()) / 1e9:.2f} B"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _split_modulation(block, t_mod: torch.Tensor):
|
| 66 |
+
has_seq = len(t_mod.shape) == 4
|
| 67 |
+
chunk_dim = 2 if has_seq else 1
|
| 68 |
+
|
| 69 |
+
base_mod = block.modulation.to(dtype=t_mod.dtype, device=t_mod.device)
|
| 70 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (base_mod + t_mod).chunk(
|
| 71 |
+
6, dim=chunk_dim
|
| 72 |
+
)
|
| 73 |
+
if has_seq:
|
| 74 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 75 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 76 |
+
shift_msa.squeeze(2),
|
| 77 |
+
scale_msa.squeeze(2),
|
| 78 |
+
gate_msa.squeeze(2),
|
| 79 |
+
shift_mlp.squeeze(2),
|
| 80 |
+
scale_mlp.squeeze(2),
|
| 81 |
+
gate_mlp.squeeze(2),
|
| 82 |
+
)
|
| 83 |
+
return shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp
|
| 84 |
+
|
| 85 |
+
def _mixed_attention(
|
| 86 |
+
self,
|
| 87 |
+
q_cat: torch.Tensor,
|
| 88 |
+
k_cat: torch.Tensor,
|
| 89 |
+
v_cat: torch.Tensor,
|
| 90 |
+
attention_mask: torch.Tensor,
|
| 91 |
+
) -> torch.Tensor:
|
| 92 |
+
attn_mask = attention_mask.to(device=q_cat.device)
|
| 93 |
+
|
| 94 |
+
def _forward(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
|
| 95 |
+
return flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=attn_mask)
|
| 96 |
+
|
| 97 |
+
if self.mot_checkpoint_mixed_attn and self.training:
|
| 98 |
+
return torch.utils.checkpoint.checkpoint(
|
| 99 |
+
_forward,
|
| 100 |
+
q_cat,
|
| 101 |
+
k_cat,
|
| 102 |
+
v_cat,
|
| 103 |
+
use_reentrant=False,
|
| 104 |
+
)
|
| 105 |
+
return _forward(q_cat, k_cat, v_cat)
|
| 106 |
+
|
| 107 |
+
def _resolve_attention_masks(
|
| 108 |
+
self,
|
| 109 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 110 |
+
expected_seq_len: int,
|
| 111 |
+
) -> list[torch.Tensor]:
|
| 112 |
+
if isinstance(attention_mask, torch.Tensor):
|
| 113 |
+
attention_masks = [attention_mask] * self.num_layers
|
| 114 |
+
else:
|
| 115 |
+
attention_masks = list(attention_mask)
|
| 116 |
+
if len(attention_masks) != self.num_layers:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
f"`attention_mask` must contain {self.num_layers} layers, got {len(attention_masks)}."
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
for layer_idx, layer_mask in enumerate(attention_masks):
|
| 122 |
+
if not isinstance(layer_mask, torch.Tensor):
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"`attention_mask[{layer_idx}]` must be torch.Tensor, got {type(layer_mask)}."
|
| 125 |
+
)
|
| 126 |
+
# [S,S] shares one mask across the batch; [B,S,S] and [B,1,S,S] give a
|
| 127 |
+
# per-sample mask, which is what a per-sample condition-availability
|
| 128 |
+
# pattern needs. All three broadcast correctly in
|
| 129 |
+
# scaled_dot_product_attention against q of shape [B,heads,S,D].
|
| 130 |
+
if layer_mask.ndim not in (2, 3, 4):
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"`attention_mask[{layer_idx}]` must be [S,S], [B,S,S] or [B,1,S,S], "
|
| 133 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 134 |
+
)
|
| 135 |
+
if layer_mask.shape[-1] != layer_mask.shape[-2]:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
f"`attention_mask[{layer_idx}]` must be square in its last two dims, "
|
| 138 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 139 |
+
)
|
| 140 |
+
if layer_mask.shape[-1] != expected_seq_len:
|
| 141 |
+
raise ValueError(
|
| 142 |
+
f"`attention_mask[{layer_idx}]` seq length mismatch: "
|
| 143 |
+
f"mask={layer_mask.shape[-1]} vs expected_total={expected_seq_len}"
|
| 144 |
+
)
|
| 145 |
+
return attention_masks
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def _apply_expert_post_block(
|
| 149 |
+
block,
|
| 150 |
+
residual_x: torch.Tensor,
|
| 151 |
+
mixed_attn_out: torch.Tensor,
|
| 152 |
+
gate_msa: torch.Tensor,
|
| 153 |
+
shift_mlp: torch.Tensor,
|
| 154 |
+
scale_mlp: torch.Tensor,
|
| 155 |
+
gate_mlp: torch.Tensor,
|
| 156 |
+
context_payload: Optional[dict],
|
| 157 |
+
) -> torch.Tensor:
|
| 158 |
+
x = block.gate(residual_x, gate_msa, block.self_attn.o(mixed_attn_out))
|
| 159 |
+
|
| 160 |
+
if context_payload is not None:
|
| 161 |
+
context = context_payload.get("context")
|
| 162 |
+
if context is not None:
|
| 163 |
+
context_mask = context_payload.get("mask")
|
| 164 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 165 |
+
context_mask = context_mask.unsqueeze(1)
|
| 166 |
+
x = x + block.cross_attn(block.norm3(x), context, ctx_mask=context_mask)
|
| 167 |
+
|
| 168 |
+
mlp_input = modulate(block.norm2(x), shift_mlp, scale_mlp)
|
| 169 |
+
x = block.gate(x, gate_mlp, block.ffn(mlp_input))
|
| 170 |
+
return x
|
| 171 |
+
|
| 172 |
+
def _build_expert_attention_io(
|
| 173 |
+
self,
|
| 174 |
+
expert,
|
| 175 |
+
block,
|
| 176 |
+
x: torch.Tensor,
|
| 177 |
+
freqs: torch.Tensor,
|
| 178 |
+
t_mod: torch.Tensor,
|
| 179 |
+
) -> tuple[
|
| 180 |
+
torch.Tensor,
|
| 181 |
+
torch.Tensor,
|
| 182 |
+
torch.Tensor,
|
| 183 |
+
torch.Tensor,
|
| 184 |
+
torch.Tensor,
|
| 185 |
+
torch.Tensor,
|
| 186 |
+
torch.Tensor,
|
| 187 |
+
torch.Tensor,
|
| 188 |
+
bool,
|
| 189 |
+
]:
|
| 190 |
+
"""Build per-expert attention tensors and post-block states.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
expert: Expert module that owns this `block`; only used to read
|
| 194 |
+
`use_gradient_checkpointing`.
|
| 195 |
+
block: Transformer block for current layer (`expert.blocks[layer_idx]`).
|
| 196 |
+
x: Current expert tokens, shape [B, S, D].
|
| 197 |
+
freqs: RoPE frequencies aligned with token sequence, shape [S, 1, rope_dim].
|
| 198 |
+
t_mod: Time modulation tensor for this expert/layer.
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
q: Query after q-proj, RMSNorm, and RoPE, shape [B, S, H*Dh].
|
| 202 |
+
k: Key after k-proj, RMSNorm, and RoPE, shape [B, S, H*Dh].
|
| 203 |
+
v: Value after v-proj, shape [B, S, H*Dh].
|
| 204 |
+
residual_x: Original input `x` for residual path in post block.
|
| 205 |
+
gate_msa: Gating tensor for self-attention residual branch.
|
| 206 |
+
shift_mlp: Shift tensor for MLP modulation.
|
| 207 |
+
scale_mlp: Scale tensor for MLP modulation.
|
| 208 |
+
gate_mlp: Gating tensor for MLP residual branch.
|
| 209 |
+
use_gradient_checkpointing: Whether this expert enables checkpointing.
|
| 210 |
+
"""
|
| 211 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self._split_modulation(
|
| 212 |
+
block, t_mod
|
| 213 |
+
)
|
| 214 |
+
attn_input = modulate(block.norm1(x), shift_msa, scale_msa)
|
| 215 |
+
|
| 216 |
+
q = block.self_attn.norm_q(block.self_attn.q(attn_input))
|
| 217 |
+
k = block.self_attn.norm_k(block.self_attn.k(attn_input))
|
| 218 |
+
v = block.self_attn.v(attn_input)
|
| 219 |
+
|
| 220 |
+
q = rope_apply(q, freqs, block.num_heads)
|
| 221 |
+
k = rope_apply(k, freqs, block.num_heads)
|
| 222 |
+
|
| 223 |
+
use_gradient_checkpointing = bool(getattr(expert, "use_gradient_checkpointing", False))
|
| 224 |
+
return (
|
| 225 |
+
q,
|
| 226 |
+
k,
|
| 227 |
+
v,
|
| 228 |
+
x,
|
| 229 |
+
gate_msa,
|
| 230 |
+
shift_mlp,
|
| 231 |
+
scale_mlp,
|
| 232 |
+
gate_mlp,
|
| 233 |
+
use_gradient_checkpointing,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def _apply_post_with_optional_checkpoint(
|
| 237 |
+
self,
|
| 238 |
+
block,
|
| 239 |
+
residual_x: torch.Tensor,
|
| 240 |
+
gate_msa: torch.Tensor,
|
| 241 |
+
shift_mlp: torch.Tensor,
|
| 242 |
+
scale_mlp: torch.Tensor,
|
| 243 |
+
gate_mlp: torch.Tensor,
|
| 244 |
+
use_gradient_checkpointing: bool,
|
| 245 |
+
mixed_slice: torch.Tensor,
|
| 246 |
+
context_payload: Optional[dict],
|
| 247 |
+
) -> torch.Tensor:
|
| 248 |
+
"""Apply post-attention computations, with optional checkpointing.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
block: Transformer block for current layer.
|
| 252 |
+
residual_x: Residual input tokens before attention update, shape [B, S, D].
|
| 253 |
+
gate_msa: Gating tensor used after mixed self-attention.
|
| 254 |
+
shift_mlp: Shift tensor for MLP input modulation.
|
| 255 |
+
scale_mlp: Scale tensor for MLP input modulation.
|
| 256 |
+
gate_mlp: Gating tensor used after MLP.
|
| 257 |
+
use_gradient_checkpointing: If True and training, checkpoint this post block.
|
| 258 |
+
mixed_slice: Mixed-attention output for this expert, shape [B, S, H*Dh].
|
| 259 |
+
context_payload: Optional dict for cross-attention.
|
| 260 |
+
- `context`: encoder states [B, L, D]
|
| 261 |
+
- `mask`: attention mask [B, S, L] or [B, 1, S, L]
|
| 262 |
+
|
| 263 |
+
Returns:
|
| 264 |
+
Updated expert tokens after self-attn residual, optional cross-attn, and MLP.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
def _post_fn(
|
| 268 |
+
_mixed_slice: torch.Tensor,
|
| 269 |
+
_x: torch.Tensor,
|
| 270 |
+
_gate_msa: torch.Tensor,
|
| 271 |
+
_shift_mlp: torch.Tensor,
|
| 272 |
+
_scale_mlp: torch.Tensor,
|
| 273 |
+
_gate_mlp: torch.Tensor,
|
| 274 |
+
_block=block,
|
| 275 |
+
_context_payload=context_payload,
|
| 276 |
+
) -> torch.Tensor:
|
| 277 |
+
return self._apply_expert_post_block(
|
| 278 |
+
block=_block,
|
| 279 |
+
residual_x=_x,
|
| 280 |
+
mixed_attn_out=_mixed_slice,
|
| 281 |
+
gate_msa=_gate_msa,
|
| 282 |
+
shift_mlp=_shift_mlp,
|
| 283 |
+
scale_mlp=_scale_mlp,
|
| 284 |
+
gate_mlp=_gate_mlp,
|
| 285 |
+
context_payload=_context_payload,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if use_gradient_checkpointing and self.training:
|
| 289 |
+
return torch.utils.checkpoint.checkpoint(
|
| 290 |
+
_post_fn,
|
| 291 |
+
mixed_slice,
|
| 292 |
+
residual_x,
|
| 293 |
+
gate_msa,
|
| 294 |
+
shift_mlp,
|
| 295 |
+
scale_mlp,
|
| 296 |
+
gate_mlp,
|
| 297 |
+
use_reentrant=False,
|
| 298 |
+
)
|
| 299 |
+
return _post_fn(
|
| 300 |
+
mixed_slice,
|
| 301 |
+
residual_x,
|
| 302 |
+
gate_msa,
|
| 303 |
+
shift_mlp,
|
| 304 |
+
scale_mlp,
|
| 305 |
+
gate_mlp,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
def prefill_video_cache(
|
| 309 |
+
self,
|
| 310 |
+
video_tokens: torch.Tensor,
|
| 311 |
+
video_freqs: torch.Tensor,
|
| 312 |
+
video_t_mod: torch.Tensor,
|
| 313 |
+
video_context_payload: Optional[dict],
|
| 314 |
+
video_attention_mask: torch.Tensor,
|
| 315 |
+
) -> list[dict[str, torch.Tensor]]:
|
| 316 |
+
"""Prefill video branch once and cache per-layer K/V for action denoising.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
video_tokens: Video tokens before layer 0, shape [B, Sv, D].
|
| 320 |
+
video_freqs: Video RoPE frequencies, shape [Sv, 1, rope_dim].
|
| 321 |
+
video_t_mod: Video time modulation tensor.
|
| 322 |
+
video_context_payload: Optional dict for video cross-attention.
|
| 323 |
+
- `context`: encoder states [B, L, D]
|
| 324 |
+
- `mask`: attention mask [B, Sv, L] or [B, 1, Sv, L]
|
| 325 |
+
video_attention_mask: Video self-attention mask, shape [Sv, Sv].
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
Layer-wise cache list with length `num_layers`.
|
| 329 |
+
Each entry contains:
|
| 330 |
+
- `k`: video key tensor [B, Sv, H*Dh]
|
| 331 |
+
- `v`: video value tensor [B, Sv, H*Dh]
|
| 332 |
+
"""
|
| 333 |
+
if "video" not in self.mixtures:
|
| 334 |
+
raise ValueError("MoT requires `video` expert for `prefill_video_cache`.")
|
| 335 |
+
if video_attention_mask.ndim != 2:
|
| 336 |
+
raise ValueError(
|
| 337 |
+
f"`video_attention_mask` must be 2D [S,S], got shape {tuple(video_attention_mask.shape)}"
|
| 338 |
+
)
|
| 339 |
+
if video_attention_mask.shape[0] != video_attention_mask.shape[1]:
|
| 340 |
+
raise ValueError(
|
| 341 |
+
f"`video_attention_mask` must be square, got shape {tuple(video_attention_mask.shape)}"
|
| 342 |
+
)
|
| 343 |
+
if video_attention_mask.shape[0] != video_tokens.shape[1]:
|
| 344 |
+
raise ValueError(
|
| 345 |
+
"`video_attention_mask` seq length mismatch: "
|
| 346 |
+
f"mask={video_attention_mask.shape[0]} vs tokens={video_tokens.shape[1]}"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
expert = self.mixtures["video"]
|
| 350 |
+
x = video_tokens
|
| 351 |
+
kv_cache: list[dict[str, torch.Tensor]] = []
|
| 352 |
+
for layer_idx in range(self.num_layers):
|
| 353 |
+
block = expert.blocks[layer_idx]
|
| 354 |
+
# Build video Q/K/V from current layer input tokens.
|
| 355 |
+
(
|
| 356 |
+
q,
|
| 357 |
+
k,
|
| 358 |
+
v,
|
| 359 |
+
residual_x,
|
| 360 |
+
gate_msa,
|
| 361 |
+
shift_mlp,
|
| 362 |
+
scale_mlp,
|
| 363 |
+
gate_mlp,
|
| 364 |
+
use_gradient_checkpointing,
|
| 365 |
+
) = self._build_expert_attention_io(
|
| 366 |
+
expert=expert,
|
| 367 |
+
block=block,
|
| 368 |
+
x=x,
|
| 369 |
+
freqs=video_freqs,
|
| 370 |
+
t_mod=video_t_mod,
|
| 371 |
+
)
|
| 372 |
+
# Video prefill uses only video self-attention mask.
|
| 373 |
+
mixed = self._mixed_attention(
|
| 374 |
+
q_cat=q,
|
| 375 |
+
k_cat=k,
|
| 376 |
+
v_cat=v,
|
| 377 |
+
attention_mask=video_attention_mask,
|
| 378 |
+
)
|
| 379 |
+
# Update video tokens for the next layer and persist current layer K/V.
|
| 380 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 381 |
+
block=block,
|
| 382 |
+
residual_x=residual_x,
|
| 383 |
+
gate_msa=gate_msa,
|
| 384 |
+
shift_mlp=shift_mlp,
|
| 385 |
+
scale_mlp=scale_mlp,
|
| 386 |
+
gate_mlp=gate_mlp,
|
| 387 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 388 |
+
mixed_slice=mixed,
|
| 389 |
+
context_payload=video_context_payload,
|
| 390 |
+
)
|
| 391 |
+
kv_cache.append({"k": k, "v": v})
|
| 392 |
+
return kv_cache
|
| 393 |
+
|
| 394 |
+
def forward_action_with_video_cache(
|
| 395 |
+
self,
|
| 396 |
+
action_tokens: torch.Tensor,
|
| 397 |
+
action_freqs: torch.Tensor,
|
| 398 |
+
action_t_mod: torch.Tensor,
|
| 399 |
+
action_context_payload: Optional[dict],
|
| 400 |
+
video_kv_cache: list[dict[str, torch.Tensor]],
|
| 401 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 402 |
+
video_seq_len: int,
|
| 403 |
+
) -> torch.Tensor:
|
| 404 |
+
"""Run action branch with cached video K/V instead of recomputing video tokens.
|
| 405 |
+
|
| 406 |
+
Args:
|
| 407 |
+
action_tokens: Action tokens before layer 0, shape [B, Sa, D].
|
| 408 |
+
action_freqs: Action RoPE frequencies, shape [Sa, 1, rope_dim].
|
| 409 |
+
action_t_mod: Action time modulation tensor.
|
| 410 |
+
action_context_payload: Optional dict for action cross-attention.
|
| 411 |
+
- `context`: encoder states [B, L, D]
|
| 412 |
+
- `mask`: attention mask [B, Sa, L] or [B, 1, Sa, L]
|
| 413 |
+
video_kv_cache: Layer-wise cached video K/V from `prefill_video_cache`.
|
| 414 |
+
attention_mask: Joint [video+action] mask, shape [Sv+Sa, Sv+Sa].
|
| 415 |
+
video_seq_len: Video token count `Sv` in the joint sequence prefix.
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
Updated action tokens after all layers, shape [B, Sa, D].
|
| 419 |
+
"""
|
| 420 |
+
if "action" not in self.mixtures:
|
| 421 |
+
raise ValueError("MoT requires `action` expert for `forward_action_with_video_cache`.")
|
| 422 |
+
if len(video_kv_cache) != self.num_layers:
|
| 423 |
+
raise ValueError(
|
| 424 |
+
f"`video_kv_cache` must contain {self.num_layers} layers, got {len(video_kv_cache)}."
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
action_seq_len = int(action_tokens.shape[1])
|
| 428 |
+
total_seq_len = int(video_seq_len) + action_seq_len
|
| 429 |
+
attention_masks = self._resolve_attention_masks(
|
| 430 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
expert = self.mixtures["action"]
|
| 434 |
+
x = action_tokens
|
| 435 |
+
for layer_idx in range(self.num_layers):
|
| 436 |
+
block = expert.blocks[layer_idx]
|
| 437 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 438 |
+
action_attention_mask = layer_attention_mask[
|
| 439 |
+
video_seq_len:total_seq_len, :total_seq_len
|
| 440 |
+
]
|
| 441 |
+
# Action query/key/value are still step-dependent and must be recomputed each step.
|
| 442 |
+
(
|
| 443 |
+
q_action,
|
| 444 |
+
k_action,
|
| 445 |
+
v_action,
|
| 446 |
+
residual_x,
|
| 447 |
+
gate_msa,
|
| 448 |
+
shift_mlp,
|
| 449 |
+
scale_mlp,
|
| 450 |
+
gate_mlp,
|
| 451 |
+
use_gradient_checkpointing,
|
| 452 |
+
) = self._build_expert_attention_io(
|
| 453 |
+
expert=expert,
|
| 454 |
+
block=block,
|
| 455 |
+
x=x,
|
| 456 |
+
freqs=action_freqs,
|
| 457 |
+
t_mod=action_t_mod,
|
| 458 |
+
)
|
| 459 |
+
layer_cache = video_kv_cache[layer_idx]
|
| 460 |
+
if "k" not in layer_cache or "v" not in layer_cache:
|
| 461 |
+
raise ValueError(f"`video_kv_cache[{layer_idx}]` must contain `k` and `v`.")
|
| 462 |
+
|
| 463 |
+
k_video = layer_cache["k"]
|
| 464 |
+
v_video = layer_cache["v"]
|
| 465 |
+
if k_video.shape[1] != video_seq_len or v_video.shape[1] != video_seq_len:
|
| 466 |
+
raise ValueError(
|
| 467 |
+
f"`video_kv_cache[{layer_idx}]` seq len mismatch, expected {video_seq_len}."
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# Mixed attention: action queries attend to cached video K/V plus current action K/V.
|
| 471 |
+
k_cat = torch.cat([k_video, k_action], dim=1)
|
| 472 |
+
v_cat = torch.cat([v_video, v_action], dim=1)
|
| 473 |
+
mixed = self._mixed_attention(
|
| 474 |
+
q_cat=q_action,
|
| 475 |
+
k_cat=k_cat,
|
| 476 |
+
v_cat=v_cat,
|
| 477 |
+
attention_mask=action_attention_mask,
|
| 478 |
+
)
|
| 479 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 480 |
+
block=block,
|
| 481 |
+
residual_x=residual_x,
|
| 482 |
+
gate_msa=gate_msa,
|
| 483 |
+
shift_mlp=shift_mlp,
|
| 484 |
+
scale_mlp=scale_mlp,
|
| 485 |
+
gate_mlp=gate_mlp,
|
| 486 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 487 |
+
mixed_slice=mixed,
|
| 488 |
+
context_payload=action_context_payload,
|
| 489 |
+
)
|
| 490 |
+
return x
|
| 491 |
+
|
| 492 |
+
def forward(
|
| 493 |
+
self,
|
| 494 |
+
embeds_all: Dict[str, torch.Tensor],
|
| 495 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 496 |
+
freqs_all: Dict[str, torch.Tensor],
|
| 497 |
+
context_all: Dict[str, Optional[dict]],
|
| 498 |
+
t_mod_all: Dict[str, torch.Tensor],
|
| 499 |
+
):
|
| 500 |
+
missing = [k for k in self.expert_order if k not in embeds_all]
|
| 501 |
+
if missing:
|
| 502 |
+
raise ValueError(f"Missing expert tokens for {missing}")
|
| 503 |
+
missing = [k for k in self.expert_order if k not in freqs_all]
|
| 504 |
+
if missing:
|
| 505 |
+
raise ValueError(f"Missing expert freqs for {missing}")
|
| 506 |
+
missing = [k for k in self.expert_order if k not in t_mod_all]
|
| 507 |
+
if missing:
|
| 508 |
+
raise ValueError(f"Missing expert t_mod for {missing}")
|
| 509 |
+
|
| 510 |
+
tokens_all = {k: v for k, v in embeds_all.items()}
|
| 511 |
+
total_seq_len = sum(int(tokens_all[name].shape[1]) for name in self.expert_order)
|
| 512 |
+
attention_masks = self._resolve_attention_masks(
|
| 513 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
for layer_idx in range(self.num_layers):
|
| 517 |
+
q_chunks = []
|
| 518 |
+
k_chunks = []
|
| 519 |
+
v_chunks = []
|
| 520 |
+
cached = {}
|
| 521 |
+
seq_lens = []
|
| 522 |
+
|
| 523 |
+
for name in self.expert_order:
|
| 524 |
+
expert = self.mixtures[name]
|
| 525 |
+
block = expert.blocks[layer_idx]
|
| 526 |
+
x = tokens_all[name]
|
| 527 |
+
freqs = freqs_all[name]
|
| 528 |
+
t_mod = t_mod_all[name]
|
| 529 |
+
|
| 530 |
+
(
|
| 531 |
+
q,
|
| 532 |
+
k,
|
| 533 |
+
v,
|
| 534 |
+
residual_x,
|
| 535 |
+
gate_msa,
|
| 536 |
+
shift_mlp,
|
| 537 |
+
scale_mlp,
|
| 538 |
+
gate_mlp,
|
| 539 |
+
use_gradient_checkpointing,
|
| 540 |
+
) = self._build_expert_attention_io(
|
| 541 |
+
expert=expert,
|
| 542 |
+
block=block,
|
| 543 |
+
x=x,
|
| 544 |
+
freqs=freqs,
|
| 545 |
+
t_mod=t_mod,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
q_chunks.append(q)
|
| 549 |
+
k_chunks.append(k)
|
| 550 |
+
v_chunks.append(v)
|
| 551 |
+
seq_lens.append(x.shape[1])
|
| 552 |
+
cached[name] = {
|
| 553 |
+
"block": block,
|
| 554 |
+
"residual_x": residual_x,
|
| 555 |
+
"gate_msa": gate_msa,
|
| 556 |
+
"shift_mlp": shift_mlp,
|
| 557 |
+
"scale_mlp": scale_mlp,
|
| 558 |
+
"gate_mlp": gate_mlp,
|
| 559 |
+
"use_gradient_checkpointing": use_gradient_checkpointing,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
# 3. concat all tokens for mixed attention
|
| 563 |
+
q_cat = torch.cat(q_chunks, dim=1)
|
| 564 |
+
k_cat = torch.cat(k_chunks, dim=1)
|
| 565 |
+
v_cat = torch.cat(v_chunks, dim=1)
|
| 566 |
+
|
| 567 |
+
total_seq = q_cat.shape[1]
|
| 568 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 569 |
+
if layer_attention_mask.shape[-1] != total_seq:
|
| 570 |
+
raise ValueError(
|
| 571 |
+
"Attention mask seq length mismatch: "
|
| 572 |
+
f"mask={layer_attention_mask.shape[-1]} vs tokens={total_seq}"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
mixed = self._mixed_attention(
|
| 576 |
+
q_cat=q_cat,
|
| 577 |
+
k_cat=k_cat,
|
| 578 |
+
v_cat=v_cat,
|
| 579 |
+
attention_mask=layer_attention_mask,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
start = 0
|
| 583 |
+
for name, seq_len in zip(self.expert_order, seq_lens):
|
| 584 |
+
# 4. split mixed attention output and apply post-attention blocks for each expert
|
| 585 |
+
end = start + seq_len
|
| 586 |
+
mixed_slice = mixed[:, start:end, :]
|
| 587 |
+
cached_expert = cached[name]
|
| 588 |
+
block = cached_expert["block"]
|
| 589 |
+
context_payload = context_all.get(name)
|
| 590 |
+
|
| 591 |
+
updated_tokens = self._apply_post_with_optional_checkpoint(
|
| 592 |
+
block=block,
|
| 593 |
+
residual_x=cached_expert["residual_x"],
|
| 594 |
+
gate_msa=cached_expert["gate_msa"],
|
| 595 |
+
shift_mlp=cached_expert["shift_mlp"],
|
| 596 |
+
scale_mlp=cached_expert["scale_mlp"],
|
| 597 |
+
gate_mlp=cached_expert["gate_mlp"],
|
| 598 |
+
use_gradient_checkpointing=cached_expert["use_gradient_checkpointing"],
|
| 599 |
+
mixed_slice=mixed_slice,
|
| 600 |
+
context_payload=context_payload,
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
tokens_all[name] = updated_tokens
|
| 604 |
+
start = end
|
| 605 |
+
|
| 606 |
+
return tokens_all
|
tools/model_code/recorded/arm/wan22/schedulers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/arm/wan22/schedulers/scheduler_continuous.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class WanContinuousFlowMatchScheduler:
|
| 5 |
+
"""Continuous-time Flow-Matching scheduler with shift-based sampling."""
|
| 6 |
+
|
| 7 |
+
def __init__(self, num_train_timesteps: int = 1000, shift: float = 5.0, eps: float = 1e-10):
|
| 8 |
+
if num_train_timesteps <= 0:
|
| 9 |
+
raise ValueError(f"`num_train_timesteps` must be positive, got {num_train_timesteps}")
|
| 10 |
+
if shift <= 0:
|
| 11 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 12 |
+
self.num_train_timesteps = int(num_train_timesteps)
|
| 13 |
+
self.shift = float(shift)
|
| 14 |
+
self.eps = float(eps)
|
| 15 |
+
self._y_min, self._weight_norm_const = self._precompute_training_weight_stats()
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def _phi(u: torch.Tensor, shift: float) -> torch.Tensor:
|
| 19 |
+
return shift * u / (1.0 + (shift - 1.0) * u)
|
| 20 |
+
|
| 21 |
+
def _precompute_training_weight_stats(self) -> tuple[float, float]:
|
| 22 |
+
steps = self.num_train_timesteps
|
| 23 |
+
u_grid = torch.linspace(1.0, 0.0, steps + 1, dtype=torch.float64)[:-1]
|
| 24 |
+
t_grid = self._phi(u_grid, self.shift) * float(steps)
|
| 25 |
+
y_grid = torch.exp(-2.0 * ((t_grid - (steps / 2.0)) / steps) ** 2)
|
| 26 |
+
y_min = float(y_grid.min().item())
|
| 27 |
+
y_shifted_grid = y_grid - y_min
|
| 28 |
+
norm_const = float(y_shifted_grid.mean().item())
|
| 29 |
+
return y_min, norm_const
|
| 30 |
+
|
| 31 |
+
def sample_training_t(
|
| 32 |
+
self, batch_size: int, device: torch.device, dtype: torch.dtype
|
| 33 |
+
) -> torch.Tensor:
|
| 34 |
+
if batch_size <= 0:
|
| 35 |
+
raise ValueError(f"`batch_size` must be positive, got {batch_size}")
|
| 36 |
+
u = torch.rand((batch_size,), device=device, dtype=torch.float32)
|
| 37 |
+
sigma = self._phi(u, self.shift)
|
| 38 |
+
timestep = sigma * float(self.num_train_timesteps)
|
| 39 |
+
return timestep.to(dtype=dtype)
|
| 40 |
+
|
| 41 |
+
def training_weight(self, timestep: torch.Tensor) -> torch.Tensor:
|
| 42 |
+
t = timestep.to(dtype=torch.float32)
|
| 43 |
+
steps = float(self.num_train_timesteps)
|
| 44 |
+
y = torch.exp(-2.0 * ((t - (steps / 2.0)) / steps) ** 2)
|
| 45 |
+
y_shifted = y - self._y_min
|
| 46 |
+
weight = y_shifted / (self._weight_norm_const + self.eps)
|
| 47 |
+
if weight.numel() == 1:
|
| 48 |
+
return weight.reshape(())
|
| 49 |
+
return weight
|
| 50 |
+
|
| 51 |
+
def add_noise(
|
| 52 |
+
self, original_samples: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 53 |
+
) -> torch.Tensor:
|
| 54 |
+
sigma = (timestep / float(self.num_train_timesteps)).to(
|
| 55 |
+
original_samples.device, dtype=original_samples.dtype
|
| 56 |
+
)
|
| 57 |
+
if sigma.ndim == 0:
|
| 58 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 59 |
+
sigma = sigma.view(-1, *([1] * (original_samples.ndim - 1)))
|
| 60 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def training_target(
|
| 64 |
+
sample: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 65 |
+
) -> torch.Tensor:
|
| 66 |
+
del timestep
|
| 67 |
+
return noise - sample
|
| 68 |
+
|
| 69 |
+
def build_inference_schedule(
|
| 70 |
+
self,
|
| 71 |
+
num_inference_steps: int,
|
| 72 |
+
device: torch.device,
|
| 73 |
+
dtype: torch.dtype,
|
| 74 |
+
shift_override: float | None = None,
|
| 75 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 76 |
+
if num_inference_steps <= 0:
|
| 77 |
+
raise ValueError(f"`num_inference_steps` must be positive, got {num_inference_steps}")
|
| 78 |
+
shift = self.shift if shift_override is None else float(shift_override)
|
| 79 |
+
if shift <= 0:
|
| 80 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 81 |
+
|
| 82 |
+
u_steps = torch.linspace(
|
| 83 |
+
1.0, 0.0, num_inference_steps + 1, device=device, dtype=torch.float32
|
| 84 |
+
)
|
| 85 |
+
sigma_steps = self._phi(u_steps, shift)
|
| 86 |
+
timesteps = sigma_steps[:-1] * float(self.num_train_timesteps)
|
| 87 |
+
deltas = sigma_steps[1:] - sigma_steps[:-1]
|
| 88 |
+
return timesteps.to(dtype=dtype), deltas.to(dtype=dtype)
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def step(model_output: torch.Tensor, delta: torch.Tensor, sample: torch.Tensor) -> torch.Tensor:
|
| 92 |
+
delta = delta.to(sample.device, dtype=sample.dtype)
|
| 93 |
+
if delta.ndim == 0:
|
| 94 |
+
return sample + model_output * delta
|
| 95 |
+
delta = delta.view(-1, *([1] * (sample.ndim - 1)))
|
| 96 |
+
return sample + model_output * delta
|
tools/model_code/recorded/arm/wan22/wan_video_dit.py
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import math
|
| 5 |
+
from typing import Any, Dict, Tuple, Optional
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from .helpers.gradient import gradient_checkpoint_forward
|
| 8 |
+
|
| 9 |
+
from logging import getLogger as get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def flash_attention(
|
| 15 |
+
q: torch.Tensor,
|
| 16 |
+
k: torch.Tensor,
|
| 17 |
+
v: torch.Tensor,
|
| 18 |
+
num_heads: int,
|
| 19 |
+
ctx_mask: Optional[torch.Tensor] = None,
|
| 20 |
+
compatibility_mode=True,
|
| 21 |
+
):
|
| 22 |
+
if compatibility_mode:
|
| 23 |
+
q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
|
| 24 |
+
k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
|
| 25 |
+
v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
|
| 26 |
+
x = F.scaled_dot_product_attention(q, k, v, attn_mask=ctx_mask)
|
| 27 |
+
x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
|
| 28 |
+
return x
|
| 29 |
+
else:
|
| 30 |
+
raise NotImplementedError(
|
| 31 |
+
"Only compatibility mode is implemented for flash attention. Please set compatibility_mode=True."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor):
|
| 36 |
+
return x * (1 + scale) + shift
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def sinusoidal_embedding_1d(dim, position):
|
| 40 |
+
sinusoid = torch.outer(
|
| 41 |
+
position.type(torch.float64),
|
| 42 |
+
torch.pow(
|
| 43 |
+
10000,
|
| 44 |
+
-torch.arange(dim // 2, dtype=torch.float64, device=position.device).div(dim // 2),
|
| 45 |
+
),
|
| 46 |
+
)
|
| 47 |
+
x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
|
| 48 |
+
return x.to(position.dtype)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def precompute_freqs_cis_3d(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 52 |
+
# 3d rope precompute
|
| 53 |
+
f_freqs_cis = precompute_freqs_cis(dim - 2 * (dim // 3), end, theta)
|
| 54 |
+
h_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 55 |
+
w_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 56 |
+
return f_freqs_cis, h_freqs_cis, w_freqs_cis
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def precompute_freqs_cis(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 60 |
+
# 1d rope precompute
|
| 61 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].double() / dim))
|
| 62 |
+
freqs = torch.outer(torch.arange(end, device=freqs.device), freqs)
|
| 63 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
|
| 64 |
+
return freqs_cis
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def rope_apply(x, freqs, num_heads):
|
| 68 |
+
x = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
|
| 69 |
+
x_out = torch.view_as_complex(
|
| 70 |
+
x.to(torch.float64).reshape(x.shape[0], x.shape[1], x.shape[2], -1, 2)
|
| 71 |
+
)
|
| 72 |
+
freqs = freqs.to(torch.complex64) if freqs.device.type == "npu" else freqs
|
| 73 |
+
x_out = torch.view_as_real(x_out * freqs).flatten(2)
|
| 74 |
+
return x_out.to(x.dtype)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def create_group_causal_attn_mask(
|
| 78 |
+
num_temporal_groups: int, num_query_per_group: int, num_key_per_group: int, mode: str = "causal"
|
| 79 |
+
) -> torch.Tensor:
|
| 80 |
+
"""
|
| 81 |
+
Creates a group-based attention mask for scaled dot-product attention with two modes:
|
| 82 |
+
'causal' and 'group_diagonal'.
|
| 83 |
+
|
| 84 |
+
Parameters:
|
| 85 |
+
- num_temporal_groups (int): The number of temporal groups (e.g., frames in a video sequence).
|
| 86 |
+
- num_query_per_group (int): The number of query tokens per temporal group. (e.g., latent tokens in a frame, H x W).
|
| 87 |
+
- num_key_per_group (int): The number of key tokens per temporal group. (e.g., action tokens per frame).
|
| 88 |
+
- mode (str): The mode of the attention mask. Options are:
|
| 89 |
+
- 'causal': Query tokens can attend to key tokens from the same or previous temporal groups.
|
| 90 |
+
- 'group_diagonal': Query tokens can attend only to key tokens from the same temporal group.
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
- attn_mask (torch.Tensor): A boolean tensor of shape (L, S), where:
|
| 94 |
+
- L = num_temporal_groups * num_query_per_group (total number of query tokens)
|
| 95 |
+
- S = num_temporal_groups * num_key_per_group (total number of key tokens)
|
| 96 |
+
The mask indicates where attention is allowed (True) and disallowed (False).
|
| 97 |
+
|
| 98 |
+
Example:
|
| 99 |
+
Input:
|
| 100 |
+
num_temporal_groups = 3
|
| 101 |
+
num_query_per_group = 4
|
| 102 |
+
num_key_per_group = 2
|
| 103 |
+
Output:
|
| 104 |
+
Causal Mask Shape: torch.Size([12, 6])
|
| 105 |
+
Group Diagonal Mask Shape: torch.Size([12, 6])
|
| 106 |
+
if mode='causal':
|
| 107 |
+
tensor([[ True, True, False, False, False, False],
|
| 108 |
+
[ True, True, False, False, False, False],
|
| 109 |
+
[ True, True, False, False, False, False],
|
| 110 |
+
[ True, True, False, False, False, False],
|
| 111 |
+
[ True, True, True, True, False, False],
|
| 112 |
+
[ True, True, True, True, False, False],
|
| 113 |
+
[ True, True, True, True, False, False],
|
| 114 |
+
[ True, True, True, True, False, False],
|
| 115 |
+
[ True, True, True, True, True, True],
|
| 116 |
+
[ True, True, True, True, True, True],
|
| 117 |
+
[ True, True, True, True, True, True],
|
| 118 |
+
[ True, True, True, True, True, True]])
|
| 119 |
+
|
| 120 |
+
if mode='group_diagonal':
|
| 121 |
+
tensor([[ True, True, False, False, False, False],
|
| 122 |
+
[ True, True, False, False, False, False],
|
| 123 |
+
[ True, True, False, False, False, False],
|
| 124 |
+
[ True, True, False, False, False, False],
|
| 125 |
+
[False, False, True, True, False, False],
|
| 126 |
+
[False, False, True, True, False, False],
|
| 127 |
+
[False, False, True, True, False, False],
|
| 128 |
+
[False, False, True, True, False, False],
|
| 129 |
+
[False, False, False, False, True, True],
|
| 130 |
+
[False, False, False, False, True, True],
|
| 131 |
+
[False, False, False, False, True, True],
|
| 132 |
+
[False, False, False, False, True, True]])
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
assert mode in ["causal", "group_diagonal"], f"Mode {mode} must be 'causal' or 'group_diagonal'"
|
| 136 |
+
|
| 137 |
+
# Total number of query and key tokens
|
| 138 |
+
total_num_query_tokens = (
|
| 139 |
+
num_temporal_groups * num_query_per_group
|
| 140 |
+
) # Total number of query tokens (L)
|
| 141 |
+
total_num_key_tokens = num_temporal_groups * num_key_per_group # Total number of key tokens (S)
|
| 142 |
+
|
| 143 |
+
# Generate time indices for query and key tokens (shape: [L] and [S])
|
| 144 |
+
query_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 145 |
+
num_query_per_group
|
| 146 |
+
) # Shape: [L]
|
| 147 |
+
key_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 148 |
+
num_key_per_group
|
| 149 |
+
) # Shape: [S]
|
| 150 |
+
|
| 151 |
+
# Expand dimensions to compute outer comparison
|
| 152 |
+
query_time_indices = query_time_indices.unsqueeze(1) # Shape: [L, 1]
|
| 153 |
+
key_time_indices = key_time_indices.unsqueeze(0) # Shape: [1, S]
|
| 154 |
+
|
| 155 |
+
if mode == "causal":
|
| 156 |
+
# Causal Mode: Query can attend to keys where key_time <= query_time
|
| 157 |
+
attn_mask = query_time_indices >= key_time_indices # Shape: [L, S]
|
| 158 |
+
elif mode == "group_diagonal":
|
| 159 |
+
# Group Diagonal Mode: Query can attend only to keys where key_time == query_time
|
| 160 |
+
attn_mask = query_time_indices == key_time_indices # Shape: [L, S]
|
| 161 |
+
|
| 162 |
+
assert attn_mask.shape == (
|
| 163 |
+
total_num_query_tokens,
|
| 164 |
+
total_num_key_tokens,
|
| 165 |
+
), "Attention mask shape mismatch"
|
| 166 |
+
return attn_mask
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class RMSNorm(nn.Module):
|
| 170 |
+
def __init__(self, dim, eps=1e-5):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.eps = eps
|
| 173 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 174 |
+
|
| 175 |
+
def norm(self, x):
|
| 176 |
+
return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
|
| 177 |
+
|
| 178 |
+
def forward(self, x):
|
| 179 |
+
dtype = x.dtype
|
| 180 |
+
return self.norm(x.float()).to(dtype) * self.weight
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class AttentionModule(nn.Module):
|
| 184 |
+
def __init__(self, num_heads):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.num_heads = num_heads
|
| 187 |
+
|
| 188 |
+
def forward(self, q, k, v, ctx_mask=None):
|
| 189 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 190 |
+
return x
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SelfAttention(nn.Module):
|
| 194 |
+
def __init__(self, hidden_dim: int, attn_head_dim: int, num_heads: int, eps: float = 1e-6):
|
| 195 |
+
super().__init__()
|
| 196 |
+
self.hidden_dim = hidden_dim
|
| 197 |
+
self.num_heads = num_heads
|
| 198 |
+
self.attn_head_dim = attn_head_dim
|
| 199 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 200 |
+
|
| 201 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 202 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 203 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 204 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 205 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 206 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 207 |
+
|
| 208 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 209 |
+
|
| 210 |
+
def forward(self, x, freqs, self_attn_mask: Optional[torch.Tensor] = None):
|
| 211 |
+
q = self.norm_q(self.q(x))
|
| 212 |
+
k = self.norm_k(self.k(x))
|
| 213 |
+
v = self.v(x)
|
| 214 |
+
q = rope_apply(q, freqs, self.num_heads)
|
| 215 |
+
k = rope_apply(k, freqs, self.num_heads)
|
| 216 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=self_attn_mask)
|
| 217 |
+
return self.o(x)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class CrossAttention(nn.Module):
|
| 221 |
+
def __init__(
|
| 222 |
+
self,
|
| 223 |
+
hidden_dim: int,
|
| 224 |
+
attn_head_dim: int,
|
| 225 |
+
num_heads: int,
|
| 226 |
+
eps: float = 1e-6,
|
| 227 |
+
):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.hidden_dim = hidden_dim
|
| 230 |
+
self.num_heads = num_heads
|
| 231 |
+
self.attn_head_dim = attn_head_dim
|
| 232 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 233 |
+
|
| 234 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 235 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 236 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 237 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 238 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 239 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 240 |
+
|
| 241 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 242 |
+
|
| 243 |
+
def forward(self, x: torch.Tensor, ctx: torch.Tensor, ctx_mask: Optional[torch.Tensor] = None):
|
| 244 |
+
q = self.norm_q(self.q(x))
|
| 245 |
+
k = self.norm_k(self.k(ctx))
|
| 246 |
+
v = self.v(ctx)
|
| 247 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 248 |
+
return self.o(x)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class GateModule(nn.Module):
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
def forward(self, x, gate, residual):
|
| 258 |
+
return x + gate * residual
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class DiTBlock(nn.Module):
|
| 262 |
+
def __init__(
|
| 263 |
+
self, hidden_dim: int, attn_head_dim: int, num_heads: int, ffn_dim: int, eps: float = 1e-6
|
| 264 |
+
):
|
| 265 |
+
super().__init__()
|
| 266 |
+
self.hidden_dim = hidden_dim
|
| 267 |
+
self.attn_head_dim = attn_head_dim
|
| 268 |
+
self.num_heads = num_heads
|
| 269 |
+
self.ffn_dim = ffn_dim
|
| 270 |
+
|
| 271 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 272 |
+
self.cross_attn = CrossAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 273 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 274 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 275 |
+
self.norm3 = nn.LayerNorm(hidden_dim, eps=eps)
|
| 276 |
+
self.ffn = nn.Sequential(
|
| 277 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 278 |
+
nn.GELU(approximate="tanh"),
|
| 279 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 280 |
+
)
|
| 281 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 282 |
+
self.gate = GateModule()
|
| 283 |
+
|
| 284 |
+
def forward(
|
| 285 |
+
self,
|
| 286 |
+
x,
|
| 287 |
+
context,
|
| 288 |
+
t_mod,
|
| 289 |
+
freqs,
|
| 290 |
+
context_mask=None,
|
| 291 |
+
self_attn_mask: Optional[torch.Tensor] = None,
|
| 292 |
+
):
|
| 293 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 294 |
+
context_mask = context_mask.unsqueeze(1) # (B, 1, seq_len, context_len), 1 for heads
|
| 295 |
+
has_seq = len(t_mod.shape) == 4
|
| 296 |
+
chunk_dim = 2 if has_seq else 1
|
| 297 |
+
# msa: multi-head self-attention mlp: multi-layer perceptron
|
| 298 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 299 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 300 |
+
).chunk(6, dim=chunk_dim)
|
| 301 |
+
if has_seq:
|
| 302 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 303 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 304 |
+
shift_msa.squeeze(2),
|
| 305 |
+
scale_msa.squeeze(2),
|
| 306 |
+
gate_msa.squeeze(2),
|
| 307 |
+
shift_mlp.squeeze(2),
|
| 308 |
+
scale_mlp.squeeze(2),
|
| 309 |
+
gate_mlp.squeeze(2),
|
| 310 |
+
)
|
| 311 |
+
input_x = modulate(self.norm1(x), shift_msa, scale_msa)
|
| 312 |
+
x = self.gate(x, gate_msa, self.self_attn(input_x, freqs, self_attn_mask=self_attn_mask))
|
| 313 |
+
x = x + self.cross_attn(self.norm3(x), context, ctx_mask=context_mask)
|
| 314 |
+
input_x = modulate(self.norm2(x), shift_mlp, scale_mlp)
|
| 315 |
+
x = self.gate(x, gate_mlp, self.ffn(input_x))
|
| 316 |
+
return x
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class MLP(torch.nn.Module):
|
| 320 |
+
def __init__(self, in_dim, out_dim, has_pos_emb=False):
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.proj = torch.nn.Sequential(
|
| 323 |
+
nn.LayerNorm(in_dim),
|
| 324 |
+
nn.Linear(in_dim, in_dim),
|
| 325 |
+
nn.GELU(),
|
| 326 |
+
nn.Linear(in_dim, out_dim),
|
| 327 |
+
nn.LayerNorm(out_dim),
|
| 328 |
+
)
|
| 329 |
+
self.has_pos_emb = has_pos_emb
|
| 330 |
+
if has_pos_emb:
|
| 331 |
+
self.emb_pos = torch.nn.Parameter(torch.zeros((1, 514, 1280)))
|
| 332 |
+
|
| 333 |
+
def forward(self, x):
|
| 334 |
+
if self.has_pos_emb:
|
| 335 |
+
x = x + self.emb_pos.to(dtype=x.dtype, device=x.device)
|
| 336 |
+
return self.proj(x)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class Head(nn.Module):
|
| 340 |
+
def __init__(self, dim: int, out_dim: int, patch_size: Tuple[int, int, int], eps: float):
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.dim = dim
|
| 343 |
+
self.patch_size = patch_size
|
| 344 |
+
self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
|
| 345 |
+
self.head = nn.Linear(dim, out_dim * math.prod(patch_size))
|
| 346 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
|
| 347 |
+
|
| 348 |
+
def forward(self, x, t_mod):
|
| 349 |
+
if len(t_mod.shape) == 3:
|
| 350 |
+
shift, scale = (
|
| 351 |
+
self.modulation.unsqueeze(0).to(dtype=t_mod.dtype, device=t_mod.device)
|
| 352 |
+
+ t_mod.unsqueeze(2)
|
| 353 |
+
).chunk(2, dim=2)
|
| 354 |
+
x = self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 355 |
+
else:
|
| 356 |
+
shift, scale = (
|
| 357 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 358 |
+
).chunk(2, dim=1)
|
| 359 |
+
x = self.head(self.norm(x) * (1 + scale) + shift)
|
| 360 |
+
return x
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class WanVideoDiT(torch.nn.Module):
|
| 364 |
+
def __init__(
|
| 365 |
+
self,
|
| 366 |
+
hidden_dim: int,
|
| 367 |
+
in_dim: int,
|
| 368 |
+
ffn_dim: int,
|
| 369 |
+
out_dim: int,
|
| 370 |
+
text_dim: int,
|
| 371 |
+
freq_dim: int,
|
| 372 |
+
eps: float,
|
| 373 |
+
patch_size: Tuple[int, int, int],
|
| 374 |
+
num_heads: int,
|
| 375 |
+
attn_head_dim: int,
|
| 376 |
+
num_layers: int,
|
| 377 |
+
has_image_input: bool,
|
| 378 |
+
has_image_pos_emb: bool = False,
|
| 379 |
+
has_ref_conv: bool = False,
|
| 380 |
+
add_control_adapter: bool = False,
|
| 381 |
+
in_dim_control_adapter: int = 24,
|
| 382 |
+
seperated_timestep: bool = False,
|
| 383 |
+
require_vae_embedding: bool = False,
|
| 384 |
+
require_clip_embedding: bool = False,
|
| 385 |
+
fuse_vae_embedding_in_latents: bool = True,
|
| 386 |
+
action_conditioned: bool = False,
|
| 387 |
+
action_dim: int = 7,
|
| 388 |
+
action_group_causal_mask_mode="causal",
|
| 389 |
+
video_attention_mask_mode: str = "bidirectional",
|
| 390 |
+
use_gradient_checkpointing: bool = False,
|
| 391 |
+
):
|
| 392 |
+
super().__init__()
|
| 393 |
+
self.hidden_dim = hidden_dim
|
| 394 |
+
self.in_dim = in_dim
|
| 395 |
+
self.freq_dim = freq_dim
|
| 396 |
+
self.patch_size = patch_size
|
| 397 |
+
self.num_heads = num_heads
|
| 398 |
+
self.attn_head_dim = attn_head_dim
|
| 399 |
+
self.seperated_timestep = seperated_timestep
|
| 400 |
+
self.require_vae_embedding = require_vae_embedding
|
| 401 |
+
self.require_clip_embedding = require_clip_embedding
|
| 402 |
+
self.fuse_vae_embedding_in_latents = fuse_vae_embedding_in_latents
|
| 403 |
+
self.video_attention_mask_mode = str(video_attention_mask_mode)
|
| 404 |
+
|
| 405 |
+
if num_heads <= 0:
|
| 406 |
+
raise ValueError(f"`num_heads` must be > 0, got {num_heads}")
|
| 407 |
+
if attn_head_dim <= 0:
|
| 408 |
+
raise ValueError(f"`attn_head_dim` must be > 0, got {attn_head_dim}")
|
| 409 |
+
if attn_head_dim % 2 != 0:
|
| 410 |
+
raise ValueError(f"`attn_head_dim` must be even for RoPE, got {attn_head_dim}")
|
| 411 |
+
|
| 412 |
+
self.action_conditioned = action_conditioned
|
| 413 |
+
self.action_dim = action_dim
|
| 414 |
+
assert has_image_input == False
|
| 415 |
+
assert require_clip_embedding == False
|
| 416 |
+
assert (
|
| 417 |
+
require_vae_embedding == False and fuse_vae_embedding_in_latents == True
|
| 418 |
+
), "Only support fusing vae embedding in latents"
|
| 419 |
+
|
| 420 |
+
self.patch_embedding = nn.Conv3d(
|
| 421 |
+
in_dim, hidden_dim, kernel_size=patch_size, stride=patch_size
|
| 422 |
+
)
|
| 423 |
+
self.text_embedding = nn.Sequential(
|
| 424 |
+
nn.Linear(text_dim, hidden_dim),
|
| 425 |
+
nn.GELU(approximate="tanh"),
|
| 426 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 427 |
+
)
|
| 428 |
+
self.time_embedding = nn.Sequential(
|
| 429 |
+
nn.Linear(freq_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim)
|
| 430 |
+
)
|
| 431 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 432 |
+
self.blocks = nn.ModuleList(
|
| 433 |
+
[
|
| 434 |
+
DiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 435 |
+
for _ in range(num_layers)
|
| 436 |
+
]
|
| 437 |
+
)
|
| 438 |
+
self.head = Head(hidden_dim, out_dim, patch_size, eps)
|
| 439 |
+
self.freqs = precompute_freqs_cis_3d(attn_head_dim)
|
| 440 |
+
if has_ref_conv:
|
| 441 |
+
self.ref_conv = nn.Conv2d(16, hidden_dim, kernel_size=(2, 2), stride=(2, 2))
|
| 442 |
+
self.has_image_pos_emb = has_image_pos_emb
|
| 443 |
+
self.has_ref_conv = has_ref_conv
|
| 444 |
+
self.control_adapter = None
|
| 445 |
+
|
| 446 |
+
if self.action_conditioned:
|
| 447 |
+
self.action_embedding = nn.Linear(action_dim, hidden_dim)
|
| 448 |
+
self.action_group_causal_mask_mode = action_group_causal_mask_mode
|
| 449 |
+
|
| 450 |
+
self.use_gradient_checkpointing = use_gradient_checkpointing
|
| 451 |
+
if self.use_gradient_checkpointing:
|
| 452 |
+
logger.info(
|
| 453 |
+
"Using gradient checkpointing for DiT blocks. This will save memory but use more computation."
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
def patchify(
|
| 457 |
+
self, x: torch.Tensor, control_camera_latents_input: Optional[torch.Tensor] = None
|
| 458 |
+
):
|
| 459 |
+
x = self.patch_embedding(x)
|
| 460 |
+
if self.control_adapter is not None and control_camera_latents_input is not None:
|
| 461 |
+
y_camera = self.control_adapter(control_camera_latents_input)
|
| 462 |
+
x = [u + v for u, v in zip(x, y_camera)]
|
| 463 |
+
x = x[0].unsqueeze(0)
|
| 464 |
+
return x
|
| 465 |
+
|
| 466 |
+
def unpatchify(self, x: torch.Tensor, grid_size: torch.Tensor):
|
| 467 |
+
return rearrange(
|
| 468 |
+
x,
|
| 469 |
+
"b (f h w) (x y z c) -> b c (f x) (h y) (w z)",
|
| 470 |
+
f=grid_size[0],
|
| 471 |
+
h=grid_size[1],
|
| 472 |
+
w=grid_size[2],
|
| 473 |
+
x=self.patch_size[0],
|
| 474 |
+
y=self.patch_size[1],
|
| 475 |
+
z=self.patch_size[2],
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
def _validate_forward_inputs(
|
| 479 |
+
self,
|
| 480 |
+
x: torch.Tensor,
|
| 481 |
+
timestep: torch.Tensor,
|
| 482 |
+
context: torch.Tensor,
|
| 483 |
+
context_mask: Optional[torch.Tensor],
|
| 484 |
+
action: Optional[torch.Tensor],
|
| 485 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 486 |
+
if x.ndim != 5:
|
| 487 |
+
raise ValueError(f"`latents` must be 5D [B, C, T, H, W], got shape {tuple(x.shape)}")
|
| 488 |
+
num_latent_frames = x.shape[2]
|
| 489 |
+
if context.ndim != 3:
|
| 490 |
+
raise ValueError(f"`context` must be 3D [B, L, D], got shape {tuple(context.shape)}")
|
| 491 |
+
if timestep.ndim != 1:
|
| 492 |
+
raise ValueError(f"`timestep` must be 1D [B] or [1], got shape {tuple(timestep.shape)}")
|
| 493 |
+
if self.action_conditioned:
|
| 494 |
+
allow_text_only_single_frame = num_latent_frames == 1 and action is None
|
| 495 |
+
if not allow_text_only_single_frame:
|
| 496 |
+
assert action is not None, "Action input is required for action-conditioned model."
|
| 497 |
+
if action.ndim != 3:
|
| 498 |
+
raise ValueError(
|
| 499 |
+
f"`action` must be 3D [B, action_horizon, action_dim], got shape {tuple(action.shape)}"
|
| 500 |
+
)
|
| 501 |
+
if action.shape[2] != self.action_dim:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
f"`action` last dimension must be {self.action_dim}, got {action.shape[2]}"
|
| 504 |
+
)
|
| 505 |
+
if num_latent_frames <= 1:
|
| 506 |
+
raise ValueError(
|
| 507 |
+
f"video length must be > 1 for action-conditioned model, got {num_latent_frames}"
|
| 508 |
+
)
|
| 509 |
+
if action.shape[1] % (num_latent_frames - 1) != 0:
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"action horizon must be divisible by (num_latent_frames - 1), got action_horizon={action.shape[1]}"
|
| 512 |
+
)
|
| 513 |
+
if context_mask is None:
|
| 514 |
+
context_mask = torch.ones(
|
| 515 |
+
(context.shape[0], context.shape[1]), dtype=torch.bool, device=context.device
|
| 516 |
+
)
|
| 517 |
+
else:
|
| 518 |
+
if context_mask.ndim != 2:
|
| 519 |
+
raise ValueError(
|
| 520 |
+
f"`context_mask` must be 2D [B, L], got shape {tuple(context_mask.shape)}"
|
| 521 |
+
)
|
| 522 |
+
if (
|
| 523 |
+
context_mask.shape[0] != context.shape[0]
|
| 524 |
+
or context_mask.shape[1] != context.shape[1]
|
| 525 |
+
):
|
| 526 |
+
raise ValueError(
|
| 527 |
+
f"`context_mask` shape must match `context` shape [B, L], got {tuple(context_mask.shape)} vs {tuple(context.shape)}"
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
batch_size = x.shape[0]
|
| 531 |
+
if batch_size != context.shape[0]:
|
| 532 |
+
if not self.training and batch_size == 1:
|
| 533 |
+
x = x.expand(context.shape[0], -1, -1, -1, -1)
|
| 534 |
+
batch_size = context.shape[0]
|
| 535 |
+
else:
|
| 536 |
+
raise ValueError(
|
| 537 |
+
f"Batch mismatch between latents and context: {batch_size} vs {context.shape[0]}."
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
if timestep.shape[0] not in (1, batch_size):
|
| 541 |
+
raise ValueError(
|
| 542 |
+
f"`timestep` length must be 1 or batch_size({batch_size}), got {timestep.shape[0]}"
|
| 543 |
+
)
|
| 544 |
+
if timestep.shape[0] == 1 and batch_size > 1:
|
| 545 |
+
assert not self.training, "During training, timestep length must match batch_size."
|
| 546 |
+
timestep = timestep.expand(batch_size)
|
| 547 |
+
return x, timestep, context_mask
|
| 548 |
+
|
| 549 |
+
def build_video_to_video_mask(
|
| 550 |
+
self,
|
| 551 |
+
video_seq_len: int,
|
| 552 |
+
video_tokens_per_frame: int,
|
| 553 |
+
device: torch.device,
|
| 554 |
+
) -> torch.Tensor:
|
| 555 |
+
if video_seq_len <= 0:
|
| 556 |
+
raise ValueError(f"`video_seq_len` must be positive, got {video_seq_len}")
|
| 557 |
+
if video_tokens_per_frame <= 0:
|
| 558 |
+
raise ValueError(
|
| 559 |
+
f"`video_tokens_per_frame` must be positive, got {video_tokens_per_frame}"
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if self.video_attention_mask_mode == "bidirectional":
|
| 563 |
+
return torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 564 |
+
|
| 565 |
+
if self.video_attention_mask_mode == "per_frame_causal":
|
| 566 |
+
if video_seq_len % video_tokens_per_frame != 0:
|
| 567 |
+
raise ValueError(
|
| 568 |
+
"`video_seq_len` must be divisible by `video_tokens_per_frame` in `per_frame_causal` mode, "
|
| 569 |
+
f"got {video_seq_len} and {video_tokens_per_frame}"
|
| 570 |
+
)
|
| 571 |
+
num_video_frames = video_seq_len // video_tokens_per_frame
|
| 572 |
+
frame_causal = torch.tril(
|
| 573 |
+
torch.ones((num_video_frames, num_video_frames), dtype=torch.bool, device=device)
|
| 574 |
+
)
|
| 575 |
+
return frame_causal.repeat_interleave(video_tokens_per_frame, dim=0).repeat_interleave(
|
| 576 |
+
video_tokens_per_frame, dim=1
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
if self.video_attention_mask_mode == "first_frame_causal":
|
| 580 |
+
video_mask = torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 581 |
+
first_frame_tokens = min(video_tokens_per_frame, video_seq_len)
|
| 582 |
+
video_mask[:first_frame_tokens, first_frame_tokens:] = False
|
| 583 |
+
return video_mask
|
| 584 |
+
|
| 585 |
+
raise ValueError(f"Unsupported video attention mask mode: {self.video_attention_mask_mode}")
|
| 586 |
+
|
| 587 |
+
def pre_dit(
|
| 588 |
+
self,
|
| 589 |
+
x: torch.Tensor,
|
| 590 |
+
timestep: torch.Tensor,
|
| 591 |
+
context: torch.Tensor,
|
| 592 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 593 |
+
action: Optional[torch.Tensor] = None,
|
| 594 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 595 |
+
control_camera_latents_input: Optional[torch.Tensor] = None,
|
| 596 |
+
) -> Dict[str, Any]:
|
| 597 |
+
x, timestep, context_mask = self._validate_forward_inputs(
|
| 598 |
+
x=x,
|
| 599 |
+
timestep=timestep,
|
| 600 |
+
context=context,
|
| 601 |
+
context_mask=context_mask,
|
| 602 |
+
action=action,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
batch_size = x.shape[0]
|
| 606 |
+
patch_h = int(self.patch_size[1])
|
| 607 |
+
patch_w = int(self.patch_size[2])
|
| 608 |
+
if x.shape[3] % patch_h != 0 or x.shape[4] % patch_w != 0:
|
| 609 |
+
raise ValueError(
|
| 610 |
+
"Latent spatial shape must be divisible by DiT patch size, "
|
| 611 |
+
f"got HxW=({x.shape[3]}, {x.shape[4]}), patch=({patch_h}, {patch_w})"
|
| 612 |
+
)
|
| 613 |
+
tokens_per_frame = (x.shape[3] // patch_h) * (x.shape[4] // patch_w)
|
| 614 |
+
|
| 615 |
+
if self.seperated_timestep and fuse_vae_embedding_in_latents:
|
| 616 |
+
if not hasattr(self, "patch_size") or len(self.patch_size) < 3:
|
| 617 |
+
raise ValueError(f"Invalid dit.patch_size: {getattr(self, 'patch_size', None)}")
|
| 618 |
+
|
| 619 |
+
token_timesteps = torch.ones(
|
| 620 |
+
(batch_size, x.shape[2], tokens_per_frame),
|
| 621 |
+
dtype=timestep.dtype,
|
| 622 |
+
device=timestep.device,
|
| 623 |
+
) * timestep.view(batch_size, 1, 1)
|
| 624 |
+
token_timesteps[:, 0, :] = 0
|
| 625 |
+
token_timesteps = token_timesteps.reshape(batch_size, -1)
|
| 626 |
+
token_t_emb = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1))
|
| 627 |
+
t = self.time_embedding(token_t_emb).reshape(batch_size, -1, self.hidden_dim)
|
| 628 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 629 |
+
else:
|
| 630 |
+
raise NotImplementedError(
|
| 631 |
+
"Only support seperated_timestep with fuse_vae_embedding_in_latents for now."
|
| 632 |
+
)
|
| 633 |
+
t = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, timestep))
|
| 634 |
+
t_mod = self.time_projection(t).unflatten(1, (6, self.hidden_dim))
|
| 635 |
+
x = self.patchify(x, control_camera_latents_input=control_camera_latents_input)
|
| 636 |
+
f, h, w = x.shape[2:]
|
| 637 |
+
|
| 638 |
+
context = self.text_embedding(context) # (B, L, dim)
|
| 639 |
+
context_len = context.shape[1]
|
| 640 |
+
if self.action_conditioned and action is not None:
|
| 641 |
+
action_len = action.shape[1]
|
| 642 |
+
action_emb = self.action_embedding(action) # (B, action_len, dim)
|
| 643 |
+
action_pos_embed = sinusoidal_embedding_1d(
|
| 644 |
+
self.hidden_dim, torch.arange(action_len, device=action_emb.device)
|
| 645 |
+
) # (action_len, dim)
|
| 646 |
+
action_emb = action_emb + action_pos_embed.unsqueeze(0) # (B, action_len, dim)
|
| 647 |
+
context = torch.cat([context, action_emb], dim=1) # (B, context_len + action_len, dim)
|
| 648 |
+
|
| 649 |
+
# new mask
|
| 650 |
+
num_temporal_groups = f - 1 # first latent frame do not attend to actions
|
| 651 |
+
if num_temporal_groups <= 0:
|
| 652 |
+
raise ValueError(
|
| 653 |
+
"Action-conditioned context mask requires at least 2 latent frames when `action` is provided."
|
| 654 |
+
)
|
| 655 |
+
assert (
|
| 656 |
+
action_emb.shape[1] % num_temporal_groups == 0
|
| 657 |
+
), f"Action embedding length {action_emb.shape[1]} must be divisible by number of temporal groups {num_temporal_groups}"
|
| 658 |
+
# Each latent frame (from the 2nd one) attends to the corresponding group of action tokens
|
| 659 |
+
action_group_mask = create_group_causal_attn_mask(
|
| 660 |
+
num_temporal_groups=num_temporal_groups,
|
| 661 |
+
num_query_per_group=tokens_per_frame,
|
| 662 |
+
num_key_per_group=action_len // num_temporal_groups,
|
| 663 |
+
mode=self.action_group_causal_mask_mode,
|
| 664 |
+
).to(
|
| 665 |
+
context.device
|
| 666 |
+
) # ((f-1)*tokens_per_frame, action_len)
|
| 667 |
+
|
| 668 |
+
seq_len = f * h * w # query length
|
| 669 |
+
final_context_mask = torch.zeros(
|
| 670 |
+
(batch_size, seq_len, context.shape[1]), dtype=torch.bool, device=context.device
|
| 671 |
+
) # (B, seq_len, L + action_len)
|
| 672 |
+
# all latent frames attend to text tokens
|
| 673 |
+
final_context_mask[:, :, :context_len] = context_mask.unsqueeze(1).expand(
|
| 674 |
+
-1, seq_len, -1
|
| 675 |
+
) # (B, seq_len, L)
|
| 676 |
+
# latent frames from the 2nd one attend to action tokens
|
| 677 |
+
final_context_mask[:, tokens_per_frame:, context_len:] = action_group_mask.unsqueeze(
|
| 678 |
+
0
|
| 679 |
+
).expand(
|
| 680 |
+
batch_size, -1, -1
|
| 681 |
+
) # (B, seq_len, action_len)
|
| 682 |
+
context_mask = final_context_mask
|
| 683 |
+
elif self.action_conditioned and action is None:
|
| 684 |
+
if f != 1:
|
| 685 |
+
raise ValueError(
|
| 686 |
+
"Action-conditioned model requires `action` unless running single-frame text-only mode with num_latent_frames=1."
|
| 687 |
+
)
|
| 688 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 689 |
+
else:
|
| 690 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 691 |
+
|
| 692 |
+
x_tokens = rearrange(x, "b c f h w -> b (f h w) c").contiguous()
|
| 693 |
+
|
| 694 |
+
freqs = (
|
| 695 |
+
torch.cat(
|
| 696 |
+
[
|
| 697 |
+
self.freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
|
| 698 |
+
self.freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
|
| 699 |
+
self.freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1),
|
| 700 |
+
],
|
| 701 |
+
dim=-1,
|
| 702 |
+
)
|
| 703 |
+
.reshape(f * h * w, 1, -1)
|
| 704 |
+
.to(x_tokens.device)
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
return {
|
| 708 |
+
"tokens": x_tokens,
|
| 709 |
+
"freqs": freqs,
|
| 710 |
+
"t": t,
|
| 711 |
+
"t_mod": t_mod,
|
| 712 |
+
"context": context,
|
| 713 |
+
"context_mask": context_mask,
|
| 714 |
+
"meta": {
|
| 715 |
+
"grid_size": (f, h, w),
|
| 716 |
+
"tokens_per_frame": tokens_per_frame,
|
| 717 |
+
"batch_size": batch_size,
|
| 718 |
+
},
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
def post_dit(self, x_tokens: torch.Tensor, pre_state: Dict[str, Any]) -> torch.Tensor:
|
| 722 |
+
f, h, w = pre_state["meta"]["grid_size"]
|
| 723 |
+
x = self.head(x_tokens, pre_state["t"])
|
| 724 |
+
x = self.unpatchify(x, (f, h, w))
|
| 725 |
+
return x
|
| 726 |
+
|
| 727 |
+
def forward(
|
| 728 |
+
self,
|
| 729 |
+
x: torch.Tensor,
|
| 730 |
+
timestep: torch.Tensor,
|
| 731 |
+
context: torch.Tensor,
|
| 732 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 733 |
+
action: Optional[torch.Tensor] = None,
|
| 734 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 735 |
+
):
|
| 736 |
+
pre_state = self.pre_dit(
|
| 737 |
+
x=x,
|
| 738 |
+
timestep=timestep,
|
| 739 |
+
context=context,
|
| 740 |
+
context_mask=context_mask,
|
| 741 |
+
action=action,
|
| 742 |
+
fuse_vae_embedding_in_latents=fuse_vae_embedding_in_latents,
|
| 743 |
+
)
|
| 744 |
+
x_tokens = pre_state["tokens"]
|
| 745 |
+
context_emb = pre_state["context"]
|
| 746 |
+
t_mod = pre_state["t_mod"]
|
| 747 |
+
freqs = pre_state["freqs"]
|
| 748 |
+
context_attn_mask = pre_state["context_mask"]
|
| 749 |
+
self_attn_mask = (
|
| 750 |
+
self.build_video_to_video_mask(
|
| 751 |
+
video_seq_len=x_tokens.shape[1],
|
| 752 |
+
video_tokens_per_frame=int(pre_state["meta"]["tokens_per_frame"]),
|
| 753 |
+
device=x_tokens.device,
|
| 754 |
+
)
|
| 755 |
+
if self.video_attention_mask_mode != "bidirectional"
|
| 756 |
+
else None
|
| 757 |
+
) # special rule for faster speed
|
| 758 |
+
|
| 759 |
+
for block in self.blocks:
|
| 760 |
+
if self.use_gradient_checkpointing:
|
| 761 |
+
x_tokens = gradient_checkpoint_forward(
|
| 762 |
+
block,
|
| 763 |
+
self.use_gradient_checkpointing,
|
| 764 |
+
x_tokens,
|
| 765 |
+
context_emb,
|
| 766 |
+
t_mod,
|
| 767 |
+
freqs,
|
| 768 |
+
context_mask=context_attn_mask,
|
| 769 |
+
self_attn_mask=self_attn_mask,
|
| 770 |
+
)
|
| 771 |
+
else:
|
| 772 |
+
x_tokens = block(
|
| 773 |
+
x_tokens,
|
| 774 |
+
context_emb,
|
| 775 |
+
t_mod,
|
| 776 |
+
freqs,
|
| 777 |
+
context_mask=context_attn_mask,
|
| 778 |
+
self_attn_mask=self_attn_mask,
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
return self.post_dit(x_tokens, pre_state)
|
tools/model_code/recorded/carrier/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/carrier/hr_mot.py
ADDED
|
@@ -0,0 +1,1293 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""H&R Mixture-of-Transformers flow model: ~0.6B, FastWAM-style, trained from scratch.
|
| 2 |
+
|
| 3 |
+
Architecture follows FastWAM and departs from it in exactly one place.
|
| 4 |
+
|
| 5 |
+
Same as FastWAM:
|
| 6 |
+
* The whole ordered segment goes through the frozen Wan2.2 48-channel VAE in
|
| 7 |
+
one pass, so its causal 3D convolutions apply both compressions: 16x spatial
|
| 8 |
+
and 4:1 temporal. [B,3,T,H,W] -> [B,48,1+(T-1)/4,h,w], with z0<-f0,
|
| 9 |
+
z1<-f1..4, z2<-f5..8. The DiT never sees RGB.
|
| 10 |
+
* Latents are patchified (1, 2, 2) into spatial tokens that survive all the way
|
| 11 |
+
through the transformer -- there is no per-frame bottleneck.
|
| 12 |
+
* Video and action are two separate experts (Mixture of Transformers): each owns
|
| 13 |
+
its own weights, and they are joined by one mixed self-attention per layer.
|
| 14 |
+
* Per-block AdaLN-Zero style modulation from a per-token timestep, plus RoPE
|
| 15 |
+
(3D over frame/height/width for video, 1D over horizon for action).
|
| 16 |
+
* Rectified-flow / flow-matching objective with the shift-based continuous
|
| 17 |
+
scheduler: x_t = (1-s) x_0 + s eps, target eps - x_0.
|
| 18 |
+
* Generation is the same joint iterative flow integration in latent + action
|
| 19 |
+
space. `HRMoTFlowModel.generate` is the latent-space core; the VAE decode and
|
| 20 |
+
state un-normalization live in `hr_inference.generate_rollout`, because the
|
| 21 |
+
VAE is deliberately kept outside this module.
|
| 22 |
+
|
| 23 |
+
Different from FastWAM:
|
| 24 |
+
* FastWAM passes human context through cross-attention. Here the ground-truth
|
| 25 |
+
human frames are VAE-encoded and placed *in the self-attention sequence* as
|
| 26 |
+
clean condition tokens, so the robot-future video and action tokens attend to
|
| 27 |
+
them directly. There is no text encoder and no cross-attention at all.
|
| 28 |
+
|
| 29 |
+
Token layout for T=9 RGB frames per stream (3 latent steps, 2 predicted):
|
| 30 |
+
|
| 31 |
+
video expert covers RGB
|
| 32 |
+
[0] robot z0 clean, t=0 condition f0
|
| 33 |
+
[1..3] human z0.. clean, t=0 condition f0 / f1-4 / f5-8
|
| 34 |
+
[4..5] robot z1.. NOISY, t=s prediction f1-4 / f5-8
|
| 35 |
+
action expert
|
| 36 |
+
[0] robot state t0 clean condition
|
| 37 |
+
[1..32] human hand motion t1..t32 clean condition
|
| 38 |
+
[33..64] robot states t1..t32 NOISY prediction
|
| 39 |
+
|
| 40 |
+
Only the robot's future latent steps and states are denoised; the robot z0 latent
|
| 41 |
+
step is restored as clean condition, exactly as FastWAM does.
|
| 42 |
+
|
| 43 |
+
Attention visibility: condition tokens see condition tokens only; prediction
|
| 44 |
+
tokens (robot-future video and robot-future action) see everything.
|
| 45 |
+
|
| 46 |
+
Human-condition availability is an extra mask layer on top of that structure,
|
| 47 |
+
not a change to it. Robot z0 is always present; by default all three human
|
| 48 |
+
latent steps, including human z0, are maskable, giving 2^Tz patterns (8 for
|
| 49 |
+
Tz=3). Masking is whole-step: all `tokens_per_frame` tokens of a human latent
|
| 50 |
+
step are dropped together,
|
| 51 |
+
never a scattered subset of patches. A missing frame is excluded as a key/value
|
| 52 |
+
so nothing reads it, its own query row is diagonal-only and discarded, and its
|
| 53 |
+
RoPE position is *not* renumbered -- the step covering f5-8 stays at position 32
|
| 54 |
+
even when the f1-4 step is absent. Supplied frames additionally carry a 0/1 availability embedding.
|
| 55 |
+
Training and inference build the mask through the same function, so at inference
|
| 56 |
+
any number of human frames can be supplied.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
from __future__ import annotations
|
| 60 |
+
|
| 61 |
+
from dataclasses import asdict, dataclass, field
|
| 62 |
+
import math
|
| 63 |
+
from typing import Optional, Sequence
|
| 64 |
+
|
| 65 |
+
import torch
|
| 66 |
+
from einops import rearrange
|
| 67 |
+
from torch import nn
|
| 68 |
+
from torch.nn import functional as F
|
| 69 |
+
|
| 70 |
+
from .wan22.mot import MoT
|
| 71 |
+
from .wan22.schedulers.scheduler_continuous import WanContinuousFlowMatchScheduler
|
| 72 |
+
from .wan22.wan_video_dit import (
|
| 73 |
+
GateModule,
|
| 74 |
+
SelfAttention,
|
| 75 |
+
precompute_freqs_cis,
|
| 76 |
+
precompute_freqs_cis_3d,
|
| 77 |
+
sinusoidal_embedding_1d,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
ROLE_ROBOT_CURRENT = 0
|
| 81 |
+
ROLE_HUMAN_CONTEXT = 1
|
| 82 |
+
ROLE_ROBOT_FUTURE = 2
|
| 83 |
+
NUM_ROLES = 3
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass(frozen=True)
|
| 87 |
+
class HRMoTConfig:
|
| 88 |
+
"""Shapes for the ~0.6B H&R MoT. Only trainable modules are counted."""
|
| 89 |
+
|
| 90 |
+
# Latent geometry, fixed by the frozen Wan2.2 VAE and the chosen image size.
|
| 91 |
+
latent_channels: int = 48
|
| 92 |
+
latent_height: int = 14
|
| 93 |
+
latent_width: int = 24
|
| 94 |
+
patch_height: int = 2
|
| 95 |
+
patch_width: int = 2
|
| 96 |
+
|
| 97 |
+
# Ordered RGB segment length handed to the VAE, per stream. The Wan2.2 VAE
|
| 98 |
+
# folds each run of 4 frames into one latent step, so T=9 -> 3 latent steps:
|
| 99 |
+
# z0 <- f0, z1 <- f1..4, z2 <- f5..8. The robot's z0 is the clean current
|
| 100 |
+
# condition; z1.. are what gets denoised.
|
| 101 |
+
num_rgb_frames: int = 9
|
| 102 |
+
vae_temporal_factor: int = 4
|
| 103 |
+
|
| 104 |
+
# Control steps between consecutive video frames. FastWAM keeps every 4th of
|
| 105 |
+
# 33 control steps as a video frame, so 9 frames span 32 steps (1.09 s at the
|
| 106 |
+
# data's 29.4 fps). Reading 9 contiguous frames instead spans 8 steps = 0.27 s,
|
| 107 |
+
# in which almost nothing happens: the gripper changes in 6.4% of 8-step
|
| 108 |
+
# windows versus 25.4% of 32-step ones.
|
| 109 |
+
frame_stride: int = 4
|
| 110 |
+
|
| 111 |
+
# Contiguous robot action steps predicted per sample, covering the video span.
|
| 112 |
+
action_horizon: int = 32
|
| 113 |
+
|
| 114 |
+
action_dim: int = 7
|
| 115 |
+
|
| 116 |
+
# Clean anchors for the action expert. Without them it predicts an absolute
|
| 117 |
+
# end-effector pose (x spans 103..346 mm) with no idea where the arm is now
|
| 118 |
+
# and no aligned human counterpart, having to infer both from pixels through
|
| 119 |
+
# the shared attention. Measured on the anchorless baseline, removing the
|
| 120 |
+
# human cost the action branch +362% -- far more than it cost video, the
|
| 121 |
+
# signature of an unanchored pathway.
|
| 122 |
+
# robot_state_f0 [7] where the arm is at t0
|
| 123 |
+
# human_action t1..tH [action_horizon, 84] raw wrist frame + hand coords
|
| 124 |
+
# False reproduces the anchorless baseline.
|
| 125 |
+
use_state_context: bool = True
|
| 126 |
+
# These two switches preserve the action-condition slots and every module,
|
| 127 |
+
# but hard-mask the corresponding sources. They are therefore suitable for
|
| 128 |
+
# same-size carrier ablations, unlike `use_state_context=False`.
|
| 129 |
+
use_robot_state_context: bool = True
|
| 130 |
+
# Keep the action-side robot-current anchor while hard-masking every mapped
|
| 131 |
+
# human-motion token. This defines the same-size human-video-only control:
|
| 132 |
+
# all modules and parameters remain present, but no 84-D human signal is a
|
| 133 |
+
# readable key/value for any prediction query.
|
| 134 |
+
use_human_motion_context: bool = True
|
| 135 |
+
# Hard-mask every human video latent while retaining the slots, projections,
|
| 136 |
+
# role parameters and sequence length for a strict robot-video-only control.
|
| 137 |
+
use_human_video_context: bool = True
|
| 138 |
+
human_action_dim: int = 84
|
| 139 |
+
|
| 140 |
+
# Whether the human z0 latent step may also be dropped. With it pinned on, the
|
| 141 |
+
# "no human context at all" path is never trained, its availability embedding
|
| 142 |
+
# row never receives gradient, and any measurement of that condition is out of
|
| 143 |
+
# distribution. Pinning it also lets the model lean entirely on the
|
| 144 |
+
# same-moment cross-embodiment correspondence instead of reading the
|
| 145 |
+
# demonstration. Droppable by default, as part of the same 10% regularizer.
|
| 146 |
+
droppable_human_current: bool = True
|
| 147 |
+
|
| 148 |
+
# Shared across experts -- MoT mixes attention, so head geometry must match.
|
| 149 |
+
num_layers: int = 22
|
| 150 |
+
num_heads: int = 10
|
| 151 |
+
attn_head_dim: int = 128
|
| 152 |
+
|
| 153 |
+
video_hidden_dim: int = 1280
|
| 154 |
+
video_ffn_dim: int = 5120
|
| 155 |
+
action_hidden_dim: int = 640
|
| 156 |
+
action_ffn_dim: int = 2560
|
| 157 |
+
|
| 158 |
+
freq_dim: int = 256
|
| 159 |
+
max_rope_position: int = 1024
|
| 160 |
+
eps: float = 1e-6
|
| 161 |
+
|
| 162 |
+
gradient_checkpointing: bool = True
|
| 163 |
+
|
| 164 |
+
# Human-condition availability. Robot z0 is never masked. Human z0 is
|
| 165 |
+
# droppable by default together with both human-future latent steps, yielding
|
| 166 |
+
# 2^3 = 8 patterns; --pin-human-current restores the legacy 4-pattern contract.
|
| 167 |
+
#
|
| 168 |
+
# This is a *regularizer*, not a curriculum: the point is that the model can
|
| 169 |
+
# still be asked for fewer human steps at inference, not that it should train
|
| 170 |
+
# mostly on degraded context. Dropping context on half the samples actively
|
| 171 |
+
# weakens the human pathway, which is the pathway under study. Default is 0.9
|
| 172 |
+
# full context, i.e. a 10% dropout rate.
|
| 173 |
+
full_human_context_prob: float = 0.9
|
| 174 |
+
|
| 175 |
+
# Flow-matching schedule (FastWAM defaults).
|
| 176 |
+
video_train_shift: float = 5.0
|
| 177 |
+
video_infer_shift: float = 5.0
|
| 178 |
+
action_train_shift: float = 5.0
|
| 179 |
+
action_infer_shift: float = 5.0
|
| 180 |
+
num_train_timesteps: int = 1000
|
| 181 |
+
|
| 182 |
+
# The video loss averages over ~250k scalars per sample and the action loss
|
| 183 |
+
# over ~21. Summing the two raw means gives the video term a far smaller and
|
| 184 |
+
# noisier per-element gradient, which is one of the failures the previous run
|
| 185 |
+
# hit. These weights are the knob for that balance.
|
| 186 |
+
loss_lambda_video: float = 1.0
|
| 187 |
+
loss_lambda_action: float = 1.0
|
| 188 |
+
|
| 189 |
+
def validate(self) -> None:
|
| 190 |
+
if self.use_state_context and self.human_action_dim != 84:
|
| 191 |
+
raise ValueError(
|
| 192 |
+
"raw H&R human motion must be 84-D "
|
| 193 |
+
"(transformed_hand_frames + transformed_hand_coords); "
|
| 194 |
+
f"got human_action_dim={self.human_action_dim}"
|
| 195 |
+
)
|
| 196 |
+
if self.frame_stride < 1:
|
| 197 |
+
raise ValueError(f"frame_stride must be >= 1, got {self.frame_stride}")
|
| 198 |
+
if self.action_horizon != self.video_span:
|
| 199 |
+
raise ValueError(
|
| 200 |
+
"action_horizon must equal the video span "
|
| 201 |
+
f"(num_rgb_frames-1)*frame_stride = {self.video_span}, "
|
| 202 |
+
f"got {self.action_horizon}"
|
| 203 |
+
)
|
| 204 |
+
if self.latent_height % self.patch_height or self.latent_width % self.patch_width:
|
| 205 |
+
raise ValueError(
|
| 206 |
+
f"latent size ({self.latent_height}, {self.latent_width}) must be divisible "
|
| 207 |
+
f"by DiT patch ({self.patch_height}, {self.patch_width})"
|
| 208 |
+
)
|
| 209 |
+
if self.num_rgb_frames < 5 or (self.num_rgb_frames - 1) % self.vae_temporal_factor:
|
| 210 |
+
raise ValueError(
|
| 211 |
+
"num_rgb_frames must be >=5 with (T-1) % "
|
| 212 |
+
f"{self.vae_temporal_factor} == 0, got {self.num_rgb_frames}"
|
| 213 |
+
)
|
| 214 |
+
# Guard the indices actually used, not the frame count: the video stream
|
| 215 |
+
# indexes `frame_rope_positions` and the action stream indexes up to
|
| 216 |
+
# num_action_tokens, either of which can exceed num_rgb_frames.
|
| 217 |
+
highest = max((*self.frame_rope_positions, self.num_action_tokens))
|
| 218 |
+
if highest >= self.max_rope_position:
|
| 219 |
+
raise ValueError(
|
| 220 |
+
f"RoPE position {highest} exceeds the precomputed table "
|
| 221 |
+
f"({self.max_rope_position})"
|
| 222 |
+
)
|
| 223 |
+
# rope_apply consumes head_dim/2 complex frequencies; the 3D split must
|
| 224 |
+
# add back up to exactly that or the rotation silently misaligns.
|
| 225 |
+
head_dim = self.attn_head_dim
|
| 226 |
+
f_dim = head_dim - 2 * (head_dim // 3)
|
| 227 |
+
complex_total = (f_dim // 2) + 2 * ((head_dim // 3) // 2)
|
| 228 |
+
if complex_total != head_dim // 2:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
f"attn_head_dim={head_dim} does not split evenly into 3D RoPE "
|
| 231 |
+
f"({complex_total} complex frequencies, need {head_dim // 2}); "
|
| 232 |
+
"use a value such as 96 or 128"
|
| 233 |
+
)
|
| 234 |
+
for name, dim in (
|
| 235 |
+
("video_hidden_dim", self.video_hidden_dim),
|
| 236 |
+
("action_hidden_dim", self.action_hidden_dim),
|
| 237 |
+
):
|
| 238 |
+
if dim <= 0:
|
| 239 |
+
raise ValueError(f"{name} must be positive")
|
| 240 |
+
if self.num_layers <= 0 or self.num_heads <= 0:
|
| 241 |
+
raise ValueError("num_layers and num_heads must be positive")
|
| 242 |
+
|
| 243 |
+
@property
|
| 244 |
+
def num_latent_steps(self) -> int:
|
| 245 |
+
"""1 + (T-1)/4 per stream."""
|
| 246 |
+
return 1 + (self.num_rgb_frames - 1) // self.vae_temporal_factor
|
| 247 |
+
|
| 248 |
+
@property
|
| 249 |
+
def num_horizons(self) -> int:
|
| 250 |
+
"""Predicted robot latent steps: everything after the clean z0."""
|
| 251 |
+
return self.num_latent_steps - 1
|
| 252 |
+
|
| 253 |
+
@property
|
| 254 |
+
def video_span(self) -> int:
|
| 255 |
+
"""Control steps covered by the video window."""
|
| 256 |
+
return (self.num_rgb_frames - 1) * self.frame_stride
|
| 257 |
+
|
| 258 |
+
@property
|
| 259 |
+
def num_action_tokens(self) -> int:
|
| 260 |
+
"""One robot state per predicted control step."""
|
| 261 |
+
return self.action_horizon
|
| 262 |
+
|
| 263 |
+
@property
|
| 264 |
+
def latent_step_frames(self) -> tuple[int, ...]:
|
| 265 |
+
"""Last CONTROL STEP each latent step covers.
|
| 266 |
+
|
| 267 |
+
The VAE folds 4 video frames into one latent step and each video frame is
|
| 268 |
+
`frame_stride` control steps apart, so a latent step spans
|
| 269 |
+
`4 * frame_stride` control steps: with stride 4 that is 0 / 16 / 32.
|
| 270 |
+
Expressing this in control steps rather than video-frame index is what
|
| 271 |
+
lets a predicted robot latent step share a RoPE position with the human
|
| 272 |
+
latent step covering the same real time.
|
| 273 |
+
"""
|
| 274 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 275 |
+
return (0, *((index + 1) * span for index in range(self.num_latent_steps - 1)))
|
| 276 |
+
|
| 277 |
+
@property
|
| 278 |
+
def tokens_per_frame(self) -> int:
|
| 279 |
+
return (self.latent_height // self.patch_height) * (self.latent_width // self.patch_width)
|
| 280 |
+
|
| 281 |
+
@property
|
| 282 |
+
def num_action_condition_tokens(self) -> int:
|
| 283 |
+
"""Robot state at t0 plus one human-motion token per control step."""
|
| 284 |
+
return (1 + self.num_action_tokens) if self.use_state_context else 0
|
| 285 |
+
|
| 286 |
+
@property
|
| 287 |
+
def num_action_sequence(self) -> int:
|
| 288 |
+
return self.num_action_condition_tokens + self.num_action_tokens
|
| 289 |
+
|
| 290 |
+
@property
|
| 291 |
+
def action_rope_positions(self) -> tuple[int, ...]:
|
| 292 |
+
"""Control-step index per action token, condition block first.
|
| 293 |
+
|
| 294 |
+
A predicted state at step i shares its RoPE position with the human motion
|
| 295 |
+
at step i, mirroring how a predicted robot latent step shares a position
|
| 296 |
+
with the human latent step covering the same real time.
|
| 297 |
+
"""
|
| 298 |
+
future = tuple(range(1, self.num_action_tokens + 1))
|
| 299 |
+
if not self.use_state_context:
|
| 300 |
+
return future
|
| 301 |
+
return (0, *future, *future)
|
| 302 |
+
|
| 303 |
+
def human_action_latent_step(self) -> tuple[int, ...]:
|
| 304 |
+
"""Which human latent step each human-motion token follows for availability.
|
| 305 |
+
|
| 306 |
+
Control steps 1..16 fall inside latent step 1, 17..32 inside step 2, so a
|
| 307 |
+
masked human latent step masks the action tokens covering the same real
|
| 308 |
+
time. Clamped in case the horizon ever overruns the video span.
|
| 309 |
+
"""
|
| 310 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 311 |
+
last = self.num_latent_steps - 1
|
| 312 |
+
return tuple(min(1 + (index // span), last) for index in range(self.num_action_tokens))
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def num_condition_frames(self) -> int:
|
| 316 |
+
"""robot z0 + every human latent step."""
|
| 317 |
+
return 1 + self.num_latent_steps
|
| 318 |
+
|
| 319 |
+
@property
|
| 320 |
+
def num_video_frames(self) -> int:
|
| 321 |
+
"""condition slots + predicted robot latent steps."""
|
| 322 |
+
return self.num_condition_frames + self.num_horizons
|
| 323 |
+
|
| 324 |
+
@property
|
| 325 |
+
def num_condition_tokens(self) -> int:
|
| 326 |
+
return self.num_condition_frames * self.tokens_per_frame
|
| 327 |
+
|
| 328 |
+
@property
|
| 329 |
+
def num_video_tokens(self) -> int:
|
| 330 |
+
return self.num_video_frames * self.tokens_per_frame
|
| 331 |
+
|
| 332 |
+
@property
|
| 333 |
+
def frame_rope_positions(self) -> tuple[int, ...]:
|
| 334 |
+
"""Temporal RoPE index per latent-step slot, in RGB-frame units.
|
| 335 |
+
|
| 336 |
+
A predicted robot latent step shares its temporal position with the human
|
| 337 |
+
latent step covering the same frames; the role embedding is what separates
|
| 338 |
+
them. That alignment is the point.
|
| 339 |
+
"""
|
| 340 |
+
steps = self.latent_step_frames
|
| 341 |
+
return (steps[0], *steps, *steps[1:])
|
| 342 |
+
|
| 343 |
+
@property
|
| 344 |
+
def frame_roles(self) -> tuple[int, ...]:
|
| 345 |
+
return (
|
| 346 |
+
ROLE_ROBOT_CURRENT,
|
| 347 |
+
*([ROLE_HUMAN_CONTEXT] * self.num_latent_steps),
|
| 348 |
+
*([ROLE_ROBOT_FUTURE] * self.num_horizons),
|
| 349 |
+
)
|
| 350 |
+
|
| 351 |
+
def to_dict(self) -> dict[str, object]:
|
| 352 |
+
return asdict(self)
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
def build_condition_prediction_mask(
|
| 356 |
+
*,
|
| 357 |
+
num_condition_tokens: int,
|
| 358 |
+
num_video_tokens: int,
|
| 359 |
+
num_action_tokens: int,
|
| 360 |
+
device: torch.device | None = None,
|
| 361 |
+
) -> torch.Tensor:
|
| 362 |
+
"""Visibility over the concatenated [video, action] MoT sequence.
|
| 363 |
+
|
| 364 |
+
Condition queries (robot current + human ground truth) see condition keys
|
| 365 |
+
only, so the clean context never leaks information from the noisy targets.
|
| 366 |
+
Prediction queries (robot future video + robot future action) see everything.
|
| 367 |
+
"""
|
| 368 |
+
|
| 369 |
+
if not 0 < num_condition_tokens <= num_video_tokens:
|
| 370 |
+
raise ValueError(
|
| 371 |
+
f"num_condition_tokens={num_condition_tokens} must be in (0, {num_video_tokens}]"
|
| 372 |
+
)
|
| 373 |
+
if num_action_tokens <= 0:
|
| 374 |
+
raise ValueError("num_action_tokens must be positive")
|
| 375 |
+
total = num_video_tokens + num_action_tokens
|
| 376 |
+
mask = torch.zeros((total, total), dtype=torch.bool, device=device)
|
| 377 |
+
mask[:num_condition_tokens, :num_condition_tokens] = True
|
| 378 |
+
mask[num_condition_tokens:, :] = True
|
| 379 |
+
return mask
|
| 380 |
+
|
| 381 |
+
|
| 382 |
+
def build_availability_attention_mask(
|
| 383 |
+
config: "HRMoTConfig",
|
| 384 |
+
human_mask: torch.Tensor,
|
| 385 |
+
*,
|
| 386 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 387 |
+
device: torch.device | None = None,
|
| 388 |
+
) -> torch.Tensor:
|
| 389 |
+
"""Per-sample [B, 1, S, S] visibility over the concatenated [video, action] sequence.
|
| 390 |
+
|
| 391 |
+
`human_mask` is [B, 1+K] with True = that human video step was
|
| 392 |
+
supplied. `human_motion_mask` has the same shape and controls the mapped
|
| 393 |
+
84-D motion tokens. It defaults to `human_mask`, preserving the joint-mask
|
| 394 |
+
training contract and every existing caller.
|
| 395 |
+
|
| 396 |
+
Rows follow the group-level contract:
|
| 397 |
+
|
| 398 |
+
valid condition (R0, H0, available H*) -> valid condition only
|
| 399 |
+
missing condition (masked-out H*) -> itself only, output discarded
|
| 400 |
+
prediction (robot future + state) -> valid condition + prediction
|
| 401 |
+
|
| 402 |
+
Missing frames are excluded as keys entirely, so no query ever reads them.
|
| 403 |
+
Their own rows are diagonal-only purely to keep the softmax well defined; a
|
| 404 |
+
fully-False row would produce NaN.
|
| 405 |
+
"""
|
| 406 |
+
|
| 407 |
+
tokens_per_frame = config.tokens_per_frame
|
| 408 |
+
human_slots = config.num_latent_steps
|
| 409 |
+
batch = human_mask.shape[0]
|
| 410 |
+
if human_mask.shape != (batch, human_slots):
|
| 411 |
+
raise ValueError(f"human_mask must be [B, {human_slots}], got {tuple(human_mask.shape)}")
|
| 412 |
+
device = device if device is not None else human_mask.device
|
| 413 |
+
human_mask = human_mask.to(device=device, dtype=torch.bool)
|
| 414 |
+
if human_motion_mask is None:
|
| 415 |
+
human_motion_mask = human_mask
|
| 416 |
+
if human_motion_mask.shape != (batch, human_slots):
|
| 417 |
+
raise ValueError(
|
| 418 |
+
f"human_motion_mask must be [B, {human_slots}], got "
|
| 419 |
+
f"{tuple(human_motion_mask.shape)}"
|
| 420 |
+
)
|
| 421 |
+
human_motion_mask = human_motion_mask.to(device=device, dtype=torch.bool)
|
| 422 |
+
if not config.use_human_video_context:
|
| 423 |
+
human_mask = torch.zeros_like(human_mask)
|
| 424 |
+
if not config.use_human_motion_context:
|
| 425 |
+
human_motion_mask = torch.zeros_like(human_motion_mask)
|
| 426 |
+
|
| 427 |
+
# --- video side: robot z0, human z0.., then the predicted robot steps ------
|
| 428 |
+
frame_available = torch.ones((batch, config.num_video_frames), dtype=torch.bool, device=device)
|
| 429 |
+
frame_available[:, 1 : 1 + human_slots] = human_mask
|
| 430 |
+
is_condition_frame = torch.zeros(config.num_video_frames, dtype=torch.bool, device=device)
|
| 431 |
+
is_condition_frame[: config.num_condition_frames] = True
|
| 432 |
+
|
| 433 |
+
valid = (frame_available & is_condition_frame[None, :]).repeat_interleave(
|
| 434 |
+
tokens_per_frame, dim=1
|
| 435 |
+
)
|
| 436 |
+
missing = ((~frame_available) & is_condition_frame[None, :]).repeat_interleave(
|
| 437 |
+
tokens_per_frame, dim=1
|
| 438 |
+
)
|
| 439 |
+
prediction = (
|
| 440 |
+
(~is_condition_frame)[None, :].expand(batch, -1).repeat_interleave(tokens_per_frame, dim=1)
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
# --- action side: optional clean anchors, then the predicted states --------
|
| 444 |
+
if config.use_state_context:
|
| 445 |
+
# The robot anchor slot is retained in same-size ablations, but can be
|
| 446 |
+
# made a missing (diagonal-only) key/value.
|
| 447 |
+
robot_now = torch.full(
|
| 448 |
+
(batch, 1),
|
| 449 |
+
bool(config.use_robot_state_context),
|
| 450 |
+
dtype=torch.bool,
|
| 451 |
+
device=device,
|
| 452 |
+
)
|
| 453 |
+
# A human-motion token inherits the availability of the latent step whose
|
| 454 |
+
# control steps it covers, so masking a human step masks its motion too.
|
| 455 |
+
steps = torch.tensor(config.human_action_latent_step(), dtype=torch.long, device=device)
|
| 456 |
+
human_now = human_motion_mask[:, steps]
|
| 457 |
+
action_valid = torch.cat((robot_now, human_now), dim=1)
|
| 458 |
+
action_missing = torch.cat((~robot_now, ~human_now), dim=1)
|
| 459 |
+
else:
|
| 460 |
+
action_valid = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 461 |
+
action_missing = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 462 |
+
action_prediction = torch.ones(
|
| 463 |
+
(batch, config.num_action_tokens), dtype=torch.bool, device=device
|
| 464 |
+
)
|
| 465 |
+
zeros_pred = torch.zeros_like(action_prediction)
|
| 466 |
+
|
| 467 |
+
valid = torch.cat((valid, action_valid, zeros_pred), dim=1)
|
| 468 |
+
missing = torch.cat((missing, action_missing, zeros_pred), dim=1)
|
| 469 |
+
prediction = torch.cat((prediction, torch.zeros_like(action_valid), action_prediction), dim=1)
|
| 470 |
+
|
| 471 |
+
total = valid.shape[1]
|
| 472 |
+
mask = valid[:, :, None] & valid[:, None, :]
|
| 473 |
+
mask |= prediction[:, :, None] & (valid | prediction)[:, None, :]
|
| 474 |
+
mask |= missing[:, :, None] & torch.eye(total, dtype=torch.bool, device=device)[None]
|
| 475 |
+
return mask.unsqueeze(1)
|
| 476 |
+
|
| 477 |
+
|
| 478 |
+
class HRDiTBlock(nn.Module):
|
| 479 |
+
"""FastWAM's DiT block minus cross-attention: all conditioning is in-sequence."""
|
| 480 |
+
|
| 481 |
+
def __init__(
|
| 482 |
+
self,
|
| 483 |
+
hidden_dim: int,
|
| 484 |
+
attn_head_dim: int,
|
| 485 |
+
num_heads: int,
|
| 486 |
+
ffn_dim: int,
|
| 487 |
+
eps: float = 1e-6,
|
| 488 |
+
) -> None:
|
| 489 |
+
super().__init__()
|
| 490 |
+
self.hidden_dim = hidden_dim
|
| 491 |
+
self.attn_head_dim = attn_head_dim
|
| 492 |
+
self.num_heads = num_heads
|
| 493 |
+
self.ffn_dim = ffn_dim
|
| 494 |
+
|
| 495 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 496 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 497 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 498 |
+
self.ffn = nn.Sequential(
|
| 499 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 500 |
+
nn.GELU(approximate="tanh"),
|
| 501 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 502 |
+
)
|
| 503 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 504 |
+
self.gate = GateModule()
|
| 505 |
+
|
| 506 |
+
|
| 507 |
+
class HRHead(nn.Module):
|
| 508 |
+
"""Final AdaLN-modulated projection, driven by the same per-token timestep."""
|
| 509 |
+
|
| 510 |
+
def __init__(self, hidden_dim: int, out_dim: int, eps: float = 1e-6) -> None:
|
| 511 |
+
super().__init__()
|
| 512 |
+
self.norm = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 513 |
+
self.head = nn.Linear(hidden_dim, out_dim)
|
| 514 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, hidden_dim) / hidden_dim**0.5)
|
| 515 |
+
|
| 516 |
+
def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 517 |
+
# x, t: [B, S, hidden]
|
| 518 |
+
modulation = self.modulation.unsqueeze(0).to(dtype=t.dtype, device=t.device)
|
| 519 |
+
shift, scale = (modulation + t.unsqueeze(2)).chunk(2, dim=2)
|
| 520 |
+
return self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 521 |
+
|
| 522 |
+
|
| 523 |
+
class _ExpertBase(nn.Module):
|
| 524 |
+
"""Shared timestep-modulation plumbing and the MoT-required attributes."""
|
| 525 |
+
|
| 526 |
+
def __init__(
|
| 527 |
+
self,
|
| 528 |
+
*,
|
| 529 |
+
hidden_dim: int,
|
| 530 |
+
ffn_dim: int,
|
| 531 |
+
num_layers: int,
|
| 532 |
+
num_heads: int,
|
| 533 |
+
attn_head_dim: int,
|
| 534 |
+
freq_dim: int,
|
| 535 |
+
eps: float,
|
| 536 |
+
gradient_checkpointing: bool,
|
| 537 |
+
) -> None:
|
| 538 |
+
super().__init__()
|
| 539 |
+
self.hidden_dim = hidden_dim
|
| 540 |
+
self.num_heads = num_heads
|
| 541 |
+
self.attn_head_dim = attn_head_dim
|
| 542 |
+
self.freq_dim = freq_dim
|
| 543 |
+
self.use_gradient_checkpointing = bool(gradient_checkpointing)
|
| 544 |
+
|
| 545 |
+
self.blocks = nn.ModuleList(
|
| 546 |
+
HRDiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 547 |
+
for _ in range(num_layers)
|
| 548 |
+
)
|
| 549 |
+
self.time_embedding = nn.Sequential(
|
| 550 |
+
nn.Linear(freq_dim, hidden_dim),
|
| 551 |
+
nn.SiLU(),
|
| 552 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 553 |
+
)
|
| 554 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 555 |
+
self._rope_cache: dict[tuple[torch.device, int], torch.Tensor] = {}
|
| 556 |
+
|
| 557 |
+
def embed_timesteps(self, token_timesteps: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 558 |
+
"""[B, S] per-token flow time -> (t [B, S, D], t_mod [B, S, 6, D])."""
|
| 559 |
+
|
| 560 |
+
batch, seq_len = token_timesteps.shape
|
| 561 |
+
embedded = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1).float())
|
| 562 |
+
t = self.time_embedding(embedded).reshape(batch, seq_len, self.hidden_dim)
|
| 563 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 564 |
+
return t, t_mod
|
| 565 |
+
|
| 566 |
+
|
| 567 |
+
class HRVideoExpert(_ExpertBase):
|
| 568 |
+
"""Video expert over per-frame Wan2.2 latents with 3D RoPE and role embeddings."""
|
| 569 |
+
|
| 570 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 571 |
+
super().__init__(
|
| 572 |
+
hidden_dim=config.video_hidden_dim,
|
| 573 |
+
ffn_dim=config.video_ffn_dim,
|
| 574 |
+
num_layers=config.num_layers,
|
| 575 |
+
num_heads=config.num_heads,
|
| 576 |
+
attn_head_dim=config.attn_head_dim,
|
| 577 |
+
freq_dim=config.freq_dim,
|
| 578 |
+
eps=config.eps,
|
| 579 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 580 |
+
)
|
| 581 |
+
self.config = config
|
| 582 |
+
patch = (1, config.patch_height, config.patch_width)
|
| 583 |
+
self.patch_size = patch
|
| 584 |
+
self.patch_embedding = nn.Conv3d(
|
| 585 |
+
config.latent_channels, config.video_hidden_dim, kernel_size=patch, stride=patch
|
| 586 |
+
)
|
| 587 |
+
self.role_embedding = nn.Parameter(torch.zeros(NUM_ROLES, config.video_hidden_dim))
|
| 588 |
+
# Availability code read by the *prediction* tokens. It has to live here,
|
| 589 |
+
# not on the human slots: under the hard mask nothing can read a missing
|
| 590 |
+
# frame, so a marker placed on it would be permanently unreachable and
|
| 591 |
+
# carry zero gradient. One embedding per (human slot, available?) pair,
|
| 592 |
+
# summed, tells the predictor exactly which human frames were supplied.
|
| 593 |
+
self.availability_embedding = nn.Parameter(
|
| 594 |
+
torch.zeros(config.num_latent_steps, 2, config.video_hidden_dim)
|
| 595 |
+
)
|
| 596 |
+
self.head = HRHead(
|
| 597 |
+
config.video_hidden_dim,
|
| 598 |
+
config.latent_channels * config.patch_height * config.patch_width,
|
| 599 |
+
config.eps,
|
| 600 |
+
)
|
| 601 |
+
# Kept off the module buffer registry: complex tensors do not survive DDP
|
| 602 |
+
# buffer broadcast cleanly, and these are deterministic constants anyway.
|
| 603 |
+
self._freqs_3d = precompute_freqs_cis_3d(config.attn_head_dim, end=config.max_rope_position)
|
| 604 |
+
|
| 605 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 606 |
+
"""[num_video_tokens, 1, head_dim/2] complex, in frame-major token order."""
|
| 607 |
+
|
| 608 |
+
key = (device, 0)
|
| 609 |
+
cached = self._rope_cache.get(key)
|
| 610 |
+
if cached is not None:
|
| 611 |
+
return cached
|
| 612 |
+
config = self.config
|
| 613 |
+
grid_h = config.latent_height // config.patch_height
|
| 614 |
+
grid_w = config.latent_width // config.patch_width
|
| 615 |
+
f_freqs, h_freqs, w_freqs = (x.to(device) for x in self._freqs_3d)
|
| 616 |
+
positions = torch.tensor(config.frame_rope_positions, dtype=torch.long, device=device)
|
| 617 |
+
num_frames = positions.numel()
|
| 618 |
+
freqs = torch.cat(
|
| 619 |
+
(
|
| 620 |
+
f_freqs[positions]
|
| 621 |
+
.view(num_frames, 1, 1, -1)
|
| 622 |
+
.expand(num_frames, grid_h, grid_w, -1),
|
| 623 |
+
h_freqs[:grid_h].view(1, grid_h, 1, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 624 |
+
w_freqs[:grid_w].view(1, 1, grid_w, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 625 |
+
),
|
| 626 |
+
dim=-1,
|
| 627 |
+
).reshape(num_frames * grid_h * grid_w, 1, -1)
|
| 628 |
+
self._rope_cache[key] = freqs
|
| 629 |
+
return freqs
|
| 630 |
+
|
| 631 |
+
def embed(self, latents: torch.Tensor, human_mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 632 |
+
"""[B, N, C, h, w] latents -> [B, N*tokens_per_frame, D] tokens.
|
| 633 |
+
|
| 634 |
+
`human_mask` is [B, 1+K] with True = this human frame is provided. Frames
|
| 635 |
+
marked False are replaced by `absent_human_embedding`, so they keep their
|
| 636 |
+
slot, role and RoPE position but carry no information from any episode.
|
| 637 |
+
"""
|
| 638 |
+
|
| 639 |
+
config = self.config
|
| 640 |
+
if latents.ndim != 5:
|
| 641 |
+
raise ValueError(f"latents must be [B, N, C, h, w], got {tuple(latents.shape)}")
|
| 642 |
+
if latents.shape[1] != config.num_video_frames:
|
| 643 |
+
raise ValueError(
|
| 644 |
+
f"expected {config.num_video_frames} video frames, got {latents.shape[1]}"
|
| 645 |
+
)
|
| 646 |
+
if latents.shape[2:] != (
|
| 647 |
+
config.latent_channels,
|
| 648 |
+
config.latent_height,
|
| 649 |
+
config.latent_width,
|
| 650 |
+
):
|
| 651 |
+
raise ValueError(
|
| 652 |
+
f"latent shape {tuple(latents.shape[2:])} does not match config "
|
| 653 |
+
f"({config.latent_channels}, {config.latent_height}, {config.latent_width})"
|
| 654 |
+
)
|
| 655 |
+
# patch_size[0] == 1, so the conv never mixes two frames together.
|
| 656 |
+
x = self.patch_embedding(latents.permute(0, 2, 1, 3, 4))
|
| 657 |
+
tokens = rearrange(x, "b d n h w -> b n (h w) d")
|
| 658 |
+
if human_mask is not None:
|
| 659 |
+
start = 1 # human latent steps occupy [1, 1 + num_latent_steps)
|
| 660 |
+
end = 1 + config.num_latent_steps
|
| 661 |
+
if human_mask.shape != (tokens.shape[0], end - start):
|
| 662 |
+
raise ValueError(
|
| 663 |
+
f"human_mask must be [B, {end - start}], got {tuple(human_mask.shape)}"
|
| 664 |
+
)
|
| 665 |
+
keep = human_mask[:, :, None, None].to(torch.bool).to(tokens.device)
|
| 666 |
+
# Whole-frame masking: every token of a human frame is dropped
|
| 667 |
+
# together, never a scattered subset of patches. The hard attention
|
| 668 |
+
# mask already makes these unreadable; zeroing also removes the data.
|
| 669 |
+
human = tokens[:, start:end] * keep.to(tokens.dtype)
|
| 670 |
+
# Availability code onto the robot-future (prediction) frames.
|
| 671 |
+
slots = torch.arange(end - start, device=tokens.device)
|
| 672 |
+
if config.use_human_video_context:
|
| 673 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 674 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 675 |
+
].sum(dim=1)[:, None, None, :]
|
| 676 |
+
else:
|
| 677 |
+
# A fixed "all absent" code would not carry episode data, but it
|
| 678 |
+
# would create a side channel absent from the robot-z0-only claim.
|
| 679 |
+
# Keep a zero-valued autograd edge so DDP still reduces this
|
| 680 |
+
# retained same-size parameter instead of flagging it unused.
|
| 681 |
+
code = self.availability_embedding.sum().to(tokens.dtype) * 0.0
|
| 682 |
+
future = tokens[:, end:] + code
|
| 683 |
+
tokens = torch.cat((tokens[:, :start], human, future), dim=1)
|
| 684 |
+
roles = torch.tensor(config.frame_roles, dtype=torch.long, device=latents.device)
|
| 685 |
+
tokens = tokens + self.role_embedding[roles][None, :, None, :].to(tokens.dtype)
|
| 686 |
+
if not config.use_human_video_context:
|
| 687 |
+
tokens[:, 1 : 1 + config.num_latent_steps] = 0
|
| 688 |
+
return rearrange(tokens, "b n s d -> b (n s) d")
|
| 689 |
+
|
| 690 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor, num_frames: int) -> torch.Tensor:
|
| 691 |
+
"""[B, N*tokens_per_frame, D] -> [B, N, C, h, w] velocity in latent space."""
|
| 692 |
+
|
| 693 |
+
config = self.config
|
| 694 |
+
grid_h = config.latent_height // config.patch_height
|
| 695 |
+
grid_w = config.latent_width // config.patch_width
|
| 696 |
+
x = self.head(tokens, t)
|
| 697 |
+
return rearrange(
|
| 698 |
+
x,
|
| 699 |
+
"b (n h w) (c ph pw) -> b n c (h ph) (w pw)",
|
| 700 |
+
n=num_frames,
|
| 701 |
+
h=grid_h,
|
| 702 |
+
w=grid_w,
|
| 703 |
+
ph=config.patch_height,
|
| 704 |
+
pw=config.patch_width,
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
|
| 708 |
+
class HRActionExpert(_ExpertBase):
|
| 709 |
+
"""Action expert over one token per future horizon, with 1D RoPE on the horizon."""
|
| 710 |
+
|
| 711 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 712 |
+
super().__init__(
|
| 713 |
+
hidden_dim=config.action_hidden_dim,
|
| 714 |
+
ffn_dim=config.action_ffn_dim,
|
| 715 |
+
num_layers=config.num_layers,
|
| 716 |
+
num_heads=config.num_heads,
|
| 717 |
+
attn_head_dim=config.attn_head_dim,
|
| 718 |
+
freq_dim=config.freq_dim,
|
| 719 |
+
eps=config.eps,
|
| 720 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 721 |
+
)
|
| 722 |
+
self.config = config
|
| 723 |
+
self.action_embedding = nn.Linear(config.action_dim, config.action_hidden_dim)
|
| 724 |
+
self.availability_embedding = nn.Parameter(
|
| 725 |
+
torch.zeros(config.num_latent_steps, 2, config.action_hidden_dim)
|
| 726 |
+
)
|
| 727 |
+
if config.use_state_context:
|
| 728 |
+
# The robot anchor reuses action_embedding: it is the same 7-D
|
| 729 |
+
# quantity, so the same projection is the right one. Human hand
|
| 730 |
+
# motion is a different 84-D modality and gets its own projection.
|
| 731 |
+
self.human_action_embedding = nn.Linear(
|
| 732 |
+
config.human_action_dim, config.action_hidden_dim
|
| 733 |
+
)
|
| 734 |
+
self.action_role_embedding = nn.Parameter(
|
| 735 |
+
torch.zeros(NUM_ROLES, config.action_hidden_dim)
|
| 736 |
+
)
|
| 737 |
+
self.head = HRHead(config.action_hidden_dim, config.action_dim, config.eps)
|
| 738 |
+
self._freqs_1d = precompute_freqs_cis(config.attn_head_dim, end=config.max_rope_position)
|
| 739 |
+
|
| 740 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 741 |
+
key = (device, 0)
|
| 742 |
+
cached = self._rope_cache.get(key)
|
| 743 |
+
if cached is not None:
|
| 744 |
+
return cached
|
| 745 |
+
positions = torch.tensor(self.config.action_rope_positions, dtype=torch.long, device=device)
|
| 746 |
+
freqs = self._freqs_1d.to(device)[positions].view(positions.numel(), 1, -1)
|
| 747 |
+
self._rope_cache[key] = freqs
|
| 748 |
+
return freqs
|
| 749 |
+
|
| 750 |
+
def embed(
|
| 751 |
+
self,
|
| 752 |
+
actions: torch.Tensor,
|
| 753 |
+
human_mask: torch.Tensor | None = None,
|
| 754 |
+
robot_current_state: torch.Tensor | None = None,
|
| 755 |
+
human_future_action: torch.Tensor | None = None,
|
| 756 |
+
) -> torch.Tensor:
|
| 757 |
+
"""-> [B, num_action_sequence, D], condition block first when enabled."""
|
| 758 |
+
|
| 759 |
+
config = self.config
|
| 760 |
+
if actions.ndim != 3 or actions.shape[1:] != (
|
| 761 |
+
config.num_action_tokens,
|
| 762 |
+
config.action_dim,
|
| 763 |
+
):
|
| 764 |
+
raise ValueError(
|
| 765 |
+
f"actions must be [B, {config.num_action_tokens}, {config.action_dim}], "
|
| 766 |
+
f"got {tuple(actions.shape)}"
|
| 767 |
+
)
|
| 768 |
+
predicted = self.action_embedding(actions)
|
| 769 |
+
if config.use_state_context:
|
| 770 |
+
if robot_current_state is None or human_future_action is None:
|
| 771 |
+
raise ValueError(
|
| 772 |
+
"use_state_context requires robot_current_state and 84-D human_future_action"
|
| 773 |
+
)
|
| 774 |
+
if robot_current_state.shape[1:] != (config.action_dim,):
|
| 775 |
+
raise ValueError(
|
| 776 |
+
f"robot_current_state must be [B, {config.action_dim}], "
|
| 777 |
+
f"got {tuple(robot_current_state.shape)}"
|
| 778 |
+
)
|
| 779 |
+
if human_future_action.shape[1:] != (
|
| 780 |
+
config.num_action_tokens,
|
| 781 |
+
config.human_action_dim,
|
| 782 |
+
):
|
| 783 |
+
raise ValueError(
|
| 784 |
+
f"human_future_action must be [B, {config.num_action_tokens}, "
|
| 785 |
+
f"{config.human_action_dim}], got {tuple(human_future_action.shape)}"
|
| 786 |
+
)
|
| 787 |
+
role = self.action_role_embedding.to(predicted.dtype)
|
| 788 |
+
anchor = self.action_embedding(robot_current_state)[:, None, :]
|
| 789 |
+
anchor = anchor + role[ROLE_ROBOT_CURRENT]
|
| 790 |
+
if not config.use_robot_state_context:
|
| 791 |
+
anchor = torch.zeros_like(anchor)
|
| 792 |
+
human = self.human_action_embedding(human_future_action) + role[ROLE_HUMAN_CONTEXT]
|
| 793 |
+
if human_mask is not None:
|
| 794 |
+
# Zero a masked step's human-motion tokens as well; the hard attention
|
| 795 |
+
# mask already makes them unreadable, this also drops the data.
|
| 796 |
+
steps = torch.tensor(config.human_action_latent_step(), device=human.device)
|
| 797 |
+
keep = human_mask.to(human.device)[:, steps][:, :, None]
|
| 798 |
+
human = human * keep.to(human.dtype)
|
| 799 |
+
predicted = predicted + role[ROLE_ROBOT_FUTURE]
|
| 800 |
+
tokens = torch.cat((anchor, human, predicted), dim=1)
|
| 801 |
+
else:
|
| 802 |
+
tokens = predicted
|
| 803 |
+
if human_mask is not None:
|
| 804 |
+
if config.use_human_motion_context:
|
| 805 |
+
slots = torch.arange(human_mask.shape[1], device=tokens.device)
|
| 806 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 807 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 808 |
+
].sum(dim=1)[:, None, :]
|
| 809 |
+
else:
|
| 810 |
+
# Same zero-edge contract as the video expert: no information or
|
| 811 |
+
# numerical effect, while every retained parameter participates.
|
| 812 |
+
code = self.availability_embedding.sum().to(tokens.dtype) * 0.0
|
| 813 |
+
tokens = tokens + code
|
| 814 |
+
return tokens
|
| 815 |
+
|
| 816 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 817 |
+
return self.head(tokens, t)
|
| 818 |
+
|
| 819 |
+
|
| 820 |
+
class HRMoTFlowModel(nn.Module):
|
| 821 |
+
"""The trainable ~0.6B model. VAE encoding happens outside, in the trainer."""
|
| 822 |
+
|
| 823 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 824 |
+
super().__init__()
|
| 825 |
+
config.validate()
|
| 826 |
+
self.config = config
|
| 827 |
+
# MoT owns the experts. Registering them a second time on this module
|
| 828 |
+
# would duplicate every tensor in state_dict, so they are reached through
|
| 829 |
+
# properties instead of attributes.
|
| 830 |
+
self.mot = MoT(
|
| 831 |
+
mixtures={"video": HRVideoExpert(config), "action": HRActionExpert(config)},
|
| 832 |
+
mot_checkpoint_mixed_attn=config.gradient_checkpointing,
|
| 833 |
+
)
|
| 834 |
+
self.train_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 835 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_train_shift
|
| 836 |
+
)
|
| 837 |
+
self.infer_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 838 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_infer_shift
|
| 839 |
+
)
|
| 840 |
+
self.train_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 841 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_train_shift
|
| 842 |
+
)
|
| 843 |
+
self.infer_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 844 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_infer_shift
|
| 845 |
+
)
|
| 846 |
+
self.reset_parameters()
|
| 847 |
+
|
| 848 |
+
@property
|
| 849 |
+
def video_expert(self) -> HRVideoExpert:
|
| 850 |
+
return self.mot.mixtures["video"]
|
| 851 |
+
|
| 852 |
+
@property
|
| 853 |
+
def action_expert(self) -> HRActionExpert:
|
| 854 |
+
return self.mot.mixtures["action"]
|
| 855 |
+
|
| 856 |
+
def reset_parameters(self) -> None:
|
| 857 |
+
"""Random init only. No pretrained weights enter the trainable model."""
|
| 858 |
+
|
| 859 |
+
def init_linear(module: nn.Module) -> None:
|
| 860 |
+
if isinstance(module, (nn.Linear, nn.Conv3d)):
|
| 861 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 862 |
+
if module.bias is not None:
|
| 863 |
+
nn.init.zeros_(module.bias)
|
| 864 |
+
|
| 865 |
+
self.apply(init_linear)
|
| 866 |
+
nn.init.normal_(self.video_expert.role_embedding, mean=0.0, std=0.02)
|
| 867 |
+
for expert in (self.video_expert, self.action_expert):
|
| 868 |
+
nn.init.normal_(expert.availability_embedding, mean=0.0, std=0.02)
|
| 869 |
+
if self.config.use_state_context:
|
| 870 |
+
nn.init.normal_(self.action_expert.action_role_embedding, mean=0.0, std=0.02)
|
| 871 |
+
# Wan/DiT init: `modulation` keeps its randn/sqrt(dim) scale (set in the
|
| 872 |
+
# block) and residual output projections are down-scaled by depth so a
|
| 873 |
+
# 22-layer stack does not blow up at step 0.
|
| 874 |
+
residual_std = 0.02 / math.sqrt(2.0 * self.config.num_layers)
|
| 875 |
+
# The final head is initialized *near* zero rather than at zero. Exactly
|
| 876 |
+
# zero makes the model emit zero velocity, which is stable, but it also
|
| 877 |
+
# makes d(loss)/d(head input) identically zero: on the first step only the
|
| 878 |
+
# two head tensors per expert receive gradient and the other 679 do not.
|
| 879 |
+
# A tiny nonzero scale keeps the near-zero start and lets gradient reach
|
| 880 |
+
# every parameter from step 1.
|
| 881 |
+
head_std = 1e-4
|
| 882 |
+
for expert in (self.video_expert, self.action_expert):
|
| 883 |
+
for block in expert.blocks:
|
| 884 |
+
nn.init.normal_(block.self_attn.o.weight, mean=0.0, std=residual_std)
|
| 885 |
+
nn.init.normal_(block.ffn[-1].weight, mean=0.0, std=residual_std)
|
| 886 |
+
nn.init.normal_(expert.head.head.weight, mean=0.0, std=head_std)
|
| 887 |
+
nn.init.zeros_(expert.head.head.bias)
|
| 888 |
+
|
| 889 |
+
def attention_mask(
|
| 890 |
+
self,
|
| 891 |
+
human_mask: torch.Tensor,
|
| 892 |
+
*,
|
| 893 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 894 |
+
device: torch.device,
|
| 895 |
+
) -> torch.Tensor:
|
| 896 |
+
return build_availability_attention_mask(
|
| 897 |
+
self.config,
|
| 898 |
+
human_mask,
|
| 899 |
+
human_motion_mask=human_motion_mask,
|
| 900 |
+
device=device,
|
| 901 |
+
)
|
| 902 |
+
|
| 903 |
+
def human_availability_patterns(self, device: torch.device) -> torch.Tensor:
|
| 904 |
+
"""Every availability pattern over the maskable human latent steps.
|
| 905 |
+
|
| 906 |
+
All 2^Tz patterns when the human current step is droppable, otherwise the
|
| 907 |
+
2^(Tz-1) patterns that keep it.
|
| 908 |
+
"""
|
| 909 |
+
|
| 910 |
+
slots = self.config.num_latent_steps
|
| 911 |
+
if not self.config.droppable_human_current:
|
| 912 |
+
slots -= 1
|
| 913 |
+
codes = torch.arange(2**slots, device=device)
|
| 914 |
+
bits = torch.arange(slots, device=device)
|
| 915 |
+
return ((codes[:, None] >> bits[None, :]) & 1).bool()
|
| 916 |
+
|
| 917 |
+
def sample_human_mask(
|
| 918 |
+
self,
|
| 919 |
+
batch: int,
|
| 920 |
+
*,
|
| 921 |
+
device: torch.device,
|
| 922 |
+
generator: Optional[torch.Generator] = None,
|
| 923 |
+
) -> torch.Tensor:
|
| 924 |
+
"""[B, Tz] bool. True = that human latent step is supplied.
|
| 925 |
+
|
| 926 |
+
`full_human_context_prob` of the batch gets the complete context so
|
| 927 |
+
full-context quality does not regress; the rest are drawn *uniformly* over
|
| 928 |
+
every other pattern. This is a regularizer, not a curriculum.
|
| 929 |
+
|
| 930 |
+
When `droppable_human_current` is set, the human z0 step is included in
|
| 931 |
+
the draw, so "no human context at all" is a trained condition rather than
|
| 932 |
+
an out-of-distribution query, and the model cannot lean entirely on the
|
| 933 |
+
same-moment cross-embodiment correspondence.
|
| 934 |
+
"""
|
| 935 |
+
|
| 936 |
+
config = self.config
|
| 937 |
+
patterns = self.human_availability_patterns(device)
|
| 938 |
+
# The last row is the all-ones pattern; draw the others uniformly.
|
| 939 |
+
choice = torch.randint(
|
| 940 |
+
0, patterns.shape[0] - 1, (batch,), device=device, generator=generator
|
| 941 |
+
)
|
| 942 |
+
drawn = patterns[choice]
|
| 943 |
+
use_full = torch.rand(batch, device=device, generator=generator) < float(
|
| 944 |
+
config.full_human_context_prob
|
| 945 |
+
)
|
| 946 |
+
drawn = torch.where(use_full[:, None], torch.ones_like(drawn), drawn)
|
| 947 |
+
if config.droppable_human_current:
|
| 948 |
+
return drawn
|
| 949 |
+
current = torch.ones((batch, 1), dtype=torch.bool, device=device)
|
| 950 |
+
return torch.cat((current, drawn), dim=1)
|
| 951 |
+
|
| 952 |
+
def _token_timesteps(
|
| 953 |
+
self, timestep: torch.Tensor, *, num_frames: int, noisy_frames: int
|
| 954 |
+
) -> torch.Tensor:
|
| 955 |
+
"""Clean condition frames get t=0; only the robot future frames carry t=s."""
|
| 956 |
+
|
| 957 |
+
config = self.config
|
| 958 |
+
batch = timestep.shape[0]
|
| 959 |
+
per_frame = torch.zeros((batch, num_frames), dtype=torch.float32, device=timestep.device)
|
| 960 |
+
per_frame[:, num_frames - noisy_frames :] = timestep.float()[:, None]
|
| 961 |
+
return per_frame.repeat_interleave(config.tokens_per_frame, dim=1)
|
| 962 |
+
|
| 963 |
+
def forward_tokens(
|
| 964 |
+
self,
|
| 965 |
+
*,
|
| 966 |
+
robot_current_latent: torch.Tensor,
|
| 967 |
+
human_latents: torch.Tensor,
|
| 968 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 969 |
+
noisy_robot_future_action: torch.Tensor,
|
| 970 |
+
timestep_video: torch.Tensor,
|
| 971 |
+
timestep_action: torch.Tensor,
|
| 972 |
+
human_mask: torch.Tensor | None = None,
|
| 973 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 974 |
+
robot_current_state: torch.Tensor | None = None,
|
| 975 |
+
human_future_action: torch.Tensor | None = None,
|
| 976 |
+
) -> tuple[dict[str, torch.Tensor], torch.Tensor, torch.Tensor]:
|
| 977 |
+
"""Run the MoT and return (tokens_out, video_t, action_t).
|
| 978 |
+
|
| 979 |
+
`tokens_out["video"]` still holds the condition positions, which
|
| 980 |
+
`predict_velocity` drops. Tests use them to prove the attention mask
|
| 981 |
+
really isolates condition tokens from the noisy prediction tokens.
|
| 982 |
+
"""
|
| 983 |
+
|
| 984 |
+
config = self.config
|
| 985 |
+
if robot_current_latent.ndim != 5 or robot_current_latent.shape[1] != 1:
|
| 986 |
+
raise ValueError(
|
| 987 |
+
f"robot_current_latent must be [B, 1, C, h, w], got "
|
| 988 |
+
f"{tuple(robot_current_latent.shape)}"
|
| 989 |
+
)
|
| 990 |
+
if human_latents.shape[1] != config.num_latent_steps:
|
| 991 |
+
raise ValueError(
|
| 992 |
+
f"human_latents must carry {config.num_latent_steps} latent steps, "
|
| 993 |
+
f"got {human_latents.shape[1]}"
|
| 994 |
+
)
|
| 995 |
+
if noisy_robot_future_latents.shape[1] != config.num_horizons:
|
| 996 |
+
raise ValueError(
|
| 997 |
+
f"noisy_robot_future_latents must carry {config.num_horizons} horizons, "
|
| 998 |
+
f"got {noisy_robot_future_latents.shape[1]}"
|
| 999 |
+
)
|
| 1000 |
+
|
| 1001 |
+
latents = torch.cat(
|
| 1002 |
+
(robot_current_latent, human_latents, noisy_robot_future_latents), dim=1
|
| 1003 |
+
)
|
| 1004 |
+
device = latents.device
|
| 1005 |
+
|
| 1006 |
+
if human_mask is None:
|
| 1007 |
+
supplied_human_mask = torch.ones(
|
| 1008 |
+
(latents.shape[0], config.num_latent_steps),
|
| 1009 |
+
dtype=torch.bool,
|
| 1010 |
+
device=device,
|
| 1011 |
+
)
|
| 1012 |
+
else:
|
| 1013 |
+
supplied_human_mask = human_mask.to(device=device, dtype=torch.bool)
|
| 1014 |
+
if human_motion_mask is None:
|
| 1015 |
+
human_motion_mask = supplied_human_mask
|
| 1016 |
+
else:
|
| 1017 |
+
human_motion_mask = human_motion_mask.to(device=device, dtype=torch.bool)
|
| 1018 |
+
# Configuration-level ablations fail closed: callers cannot accidentally
|
| 1019 |
+
# re-enable a source by passing an all-True runtime mask.
|
| 1020 |
+
human_mask = (
|
| 1021 |
+
supplied_human_mask
|
| 1022 |
+
if config.use_human_video_context
|
| 1023 |
+
else torch.zeros_like(supplied_human_mask)
|
| 1024 |
+
)
|
| 1025 |
+
if not config.use_human_motion_context:
|
| 1026 |
+
human_motion_mask = torch.zeros_like(human_motion_mask)
|
| 1027 |
+
video_tokens = self.video_expert.embed(latents, human_mask=human_mask)
|
| 1028 |
+
action_tokens = self.action_expert.embed(
|
| 1029 |
+
noisy_robot_future_action,
|
| 1030 |
+
human_mask=human_motion_mask,
|
| 1031 |
+
robot_current_state=robot_current_state,
|
| 1032 |
+
human_future_action=human_future_action,
|
| 1033 |
+
)
|
| 1034 |
+
|
| 1035 |
+
video_token_t = self._token_timesteps(
|
| 1036 |
+
timestep_video,
|
| 1037 |
+
num_frames=config.num_video_frames,
|
| 1038 |
+
noisy_frames=config.num_horizons,
|
| 1039 |
+
)
|
| 1040 |
+
# Condition tokens are clean (t=0); only the predicted states carry t=s.
|
| 1041 |
+
action_token_t = torch.zeros(
|
| 1042 |
+
(latents.shape[0], config.num_action_sequence),
|
| 1043 |
+
dtype=torch.float32,
|
| 1044 |
+
device=device,
|
| 1045 |
+
)
|
| 1046 |
+
action_token_t[:, config.num_action_condition_tokens :] = timestep_action.float()[:, None]
|
| 1047 |
+
|
| 1048 |
+
video_t, video_t_mod = self.video_expert.embed_timesteps(video_token_t)
|
| 1049 |
+
action_t, action_t_mod = self.action_expert.embed_timesteps(action_token_t)
|
| 1050 |
+
|
| 1051 |
+
mask = self.attention_mask(human_mask, human_motion_mask=human_motion_mask, device=device)
|
| 1052 |
+
tokens_out = self.mot(
|
| 1053 |
+
embeds_all={"video": video_tokens, "action": action_tokens},
|
| 1054 |
+
attention_mask=mask,
|
| 1055 |
+
freqs_all={
|
| 1056 |
+
"video": self.video_expert.rope_freqs(device),
|
| 1057 |
+
"action": self.action_expert.rope_freqs(device),
|
| 1058 |
+
},
|
| 1059 |
+
# No cross-attention: human context lives in the self-attention sequence.
|
| 1060 |
+
context_all={"video": None, "action": None},
|
| 1061 |
+
t_mod_all={"video": video_t_mod, "action": action_t_mod},
|
| 1062 |
+
)
|
| 1063 |
+
return tokens_out, video_t, action_t
|
| 1064 |
+
|
| 1065 |
+
def predict_velocity(
|
| 1066 |
+
self,
|
| 1067 |
+
*,
|
| 1068 |
+
robot_current_latent: torch.Tensor,
|
| 1069 |
+
human_latents: torch.Tensor,
|
| 1070 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 1071 |
+
noisy_robot_future_action: torch.Tensor,
|
| 1072 |
+
timestep_video: torch.Tensor,
|
| 1073 |
+
timestep_action: torch.Tensor,
|
| 1074 |
+
human_mask: torch.Tensor | None = None,
|
| 1075 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 1076 |
+
robot_current_state: torch.Tensor | None = None,
|
| 1077 |
+
human_future_action: torch.Tensor | None = None,
|
| 1078 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1079 |
+
"""Return flow velocity for the robot future latents and actions."""
|
| 1080 |
+
|
| 1081 |
+
config = self.config
|
| 1082 |
+
tokens_out, video_t, action_t = self.forward_tokens(
|
| 1083 |
+
robot_current_latent=robot_current_latent,
|
| 1084 |
+
human_latents=human_latents,
|
| 1085 |
+
noisy_robot_future_latents=noisy_robot_future_latents,
|
| 1086 |
+
noisy_robot_future_action=noisy_robot_future_action,
|
| 1087 |
+
timestep_video=timestep_video,
|
| 1088 |
+
timestep_action=timestep_action,
|
| 1089 |
+
human_mask=human_mask,
|
| 1090 |
+
human_motion_mask=human_motion_mask,
|
| 1091 |
+
robot_current_state=robot_current_state,
|
| 1092 |
+
human_future_action=human_future_action,
|
| 1093 |
+
)
|
| 1094 |
+
# Only the robot-future slice is a prediction; drop the condition tokens.
|
| 1095 |
+
start = config.num_condition_tokens
|
| 1096 |
+
pred_video = self.video_expert.unembed(
|
| 1097 |
+
tokens_out["video"][:, start:, :],
|
| 1098 |
+
video_t[:, start:, :],
|
| 1099 |
+
num_frames=config.num_horizons,
|
| 1100 |
+
)
|
| 1101 |
+
start_action = config.num_action_condition_tokens
|
| 1102 |
+
pred_action = self.action_expert.unembed(
|
| 1103 |
+
tokens_out["action"][:, start_action:, :], action_t[:, start_action:, :]
|
| 1104 |
+
)
|
| 1105 |
+
return pred_video, pred_action
|
| 1106 |
+
|
| 1107 |
+
def training_loss(
|
| 1108 |
+
self,
|
| 1109 |
+
*,
|
| 1110 |
+
robot_current_latent: torch.Tensor,
|
| 1111 |
+
human_latents: torch.Tensor,
|
| 1112 |
+
robot_future_latents: torch.Tensor,
|
| 1113 |
+
robot_future_action: torch.Tensor,
|
| 1114 |
+
generator: Optional[torch.Generator] = None,
|
| 1115 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1116 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1117 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1118 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1119 |
+
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 1120 |
+
config = self.config
|
| 1121 |
+
batch = robot_future_latents.shape[0]
|
| 1122 |
+
device = robot_future_latents.device
|
| 1123 |
+
dtype = robot_future_latents.dtype
|
| 1124 |
+
|
| 1125 |
+
timestep_video = self.train_video_scheduler.sample_training_t(batch, device, dtype)
|
| 1126 |
+
timestep_action = self.train_action_scheduler.sample_training_t(batch, device, dtype)
|
| 1127 |
+
|
| 1128 |
+
noise_video = torch.randn(
|
| 1129 |
+
robot_future_latents.shape, device=device, dtype=dtype, generator=generator
|
| 1130 |
+
)
|
| 1131 |
+
noise_action = torch.randn(
|
| 1132 |
+
robot_future_action.shape, device=device, dtype=dtype, generator=generator
|
| 1133 |
+
)
|
| 1134 |
+
noisy_video = self.train_video_scheduler.add_noise(
|
| 1135 |
+
robot_future_latents, noise_video, timestep_video
|
| 1136 |
+
)
|
| 1137 |
+
noisy_action = self.train_action_scheduler.add_noise(
|
| 1138 |
+
robot_future_action, noise_action, timestep_action
|
| 1139 |
+
)
|
| 1140 |
+
target_video = self.train_video_scheduler.training_target(
|
| 1141 |
+
robot_future_latents, noise_video, timestep_video
|
| 1142 |
+
)
|
| 1143 |
+
target_action = self.train_action_scheduler.training_target(
|
| 1144 |
+
robot_future_action, noise_action, timestep_action
|
| 1145 |
+
)
|
| 1146 |
+
|
| 1147 |
+
if human_mask is None:
|
| 1148 |
+
human_mask = self.sample_human_mask(batch, device=device, generator=generator)
|
| 1149 |
+
|
| 1150 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1151 |
+
robot_current_latent=robot_current_latent,
|
| 1152 |
+
human_latents=human_latents,
|
| 1153 |
+
noisy_robot_future_latents=noisy_video,
|
| 1154 |
+
noisy_robot_future_action=noisy_action,
|
| 1155 |
+
timestep_video=timestep_video,
|
| 1156 |
+
timestep_action=timestep_action,
|
| 1157 |
+
human_mask=human_mask,
|
| 1158 |
+
human_motion_mask=human_motion_mask,
|
| 1159 |
+
robot_current_state=robot_current_state,
|
| 1160 |
+
human_future_action=human_future_action,
|
| 1161 |
+
)
|
| 1162 |
+
|
| 1163 |
+
# Per-sample means, then the scheduler's timestep weighting -- matching
|
| 1164 |
+
# FastWAM rather than averaging a single scalar over the whole batch.
|
| 1165 |
+
video_per_sample = (pred_video.float() - target_video.float()).pow(2).flatten(1).mean(dim=1)
|
| 1166 |
+
action_per_sample = (
|
| 1167 |
+
(pred_action.float() - target_action.float()).pow(2).flatten(1).mean(dim=1)
|
| 1168 |
+
)
|
| 1169 |
+
video_weight = self.train_video_scheduler.training_weight(timestep_video).to(
|
| 1170 |
+
video_per_sample.device, video_per_sample.dtype
|
| 1171 |
+
)
|
| 1172 |
+
action_weight = self.train_action_scheduler.training_weight(timestep_action).to(
|
| 1173 |
+
action_per_sample.device, action_per_sample.dtype
|
| 1174 |
+
)
|
| 1175 |
+
loss_video = (video_per_sample * video_weight).mean()
|
| 1176 |
+
loss_action = (action_per_sample * action_weight).mean()
|
| 1177 |
+
total = config.loss_lambda_video * loss_video + config.loss_lambda_action * loss_action
|
| 1178 |
+
return total, {
|
| 1179 |
+
"loss_video": loss_video.detach(),
|
| 1180 |
+
"loss_action": loss_action.detach(),
|
| 1181 |
+
"loss_video_unweighted": video_per_sample.mean().detach(),
|
| 1182 |
+
"loss_action_unweighted": action_per_sample.mean().detach(),
|
| 1183 |
+
"human_frames_kept": (
|
| 1184 |
+
human_mask.sum(dim=1).float().mean().detach()
|
| 1185 |
+
if config.use_human_video_context
|
| 1186 |
+
else torch.zeros((), device=device)
|
| 1187 |
+
),
|
| 1188 |
+
}
|
| 1189 |
+
|
| 1190 |
+
@torch.no_grad()
|
| 1191 |
+
def generate(
|
| 1192 |
+
self,
|
| 1193 |
+
*,
|
| 1194 |
+
robot_current_latent: torch.Tensor,
|
| 1195 |
+
human_latents: torch.Tensor,
|
| 1196 |
+
num_inference_steps: int = 20,
|
| 1197 |
+
sigma_shift: Optional[float] = None,
|
| 1198 |
+
generator: Optional[torch.Generator] = None,
|
| 1199 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1200 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1201 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1202 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1203 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1204 |
+
"""FastWAM-style joint flow integration in latent + action space.
|
| 1205 |
+
|
| 1206 |
+
This is the latent-space core and returns
|
| 1207 |
+
(robot_future_latents, normalized robot_future_state). It does not touch
|
| 1208 |
+
the VAE, which lives outside the model so DDP never syncs its 705M frozen
|
| 1209 |
+
parameters. For RGB frames and un-normalized state use
|
| 1210 |
+
`fasterwam.models.hr_inference.generate_rollout`.
|
| 1211 |
+
|
| 1212 |
+
`human_mask` is [B, 1+K] and controls human video steps.
|
| 1213 |
+
`human_motion_mask` controls the 84-D motion tokens mapped to those
|
| 1214 |
+
steps. It defaults to `human_mask` for the standard model and to an
|
| 1215 |
+
all-False mask for a configured human-video-only model.
|
| 1216 |
+
"""
|
| 1217 |
+
|
| 1218 |
+
config = self.config
|
| 1219 |
+
batch = robot_current_latent.shape[0]
|
| 1220 |
+
device = robot_current_latent.device
|
| 1221 |
+
dtype = robot_current_latent.dtype
|
| 1222 |
+
|
| 1223 |
+
latents_video = torch.randn(
|
| 1224 |
+
(
|
| 1225 |
+
batch,
|
| 1226 |
+
config.num_horizons,
|
| 1227 |
+
config.latent_channels,
|
| 1228 |
+
config.latent_height,
|
| 1229 |
+
config.latent_width,
|
| 1230 |
+
),
|
| 1231 |
+
device=device,
|
| 1232 |
+
dtype=dtype,
|
| 1233 |
+
generator=generator,
|
| 1234 |
+
)
|
| 1235 |
+
latents_action = torch.randn(
|
| 1236 |
+
(batch, config.num_action_tokens, config.action_dim),
|
| 1237 |
+
device=device,
|
| 1238 |
+
dtype=dtype,
|
| 1239 |
+
generator=generator,
|
| 1240 |
+
)
|
| 1241 |
+
|
| 1242 |
+
timesteps_video, deltas_video = self.infer_video_scheduler.build_inference_schedule(
|
| 1243 |
+
num_inference_steps=num_inference_steps,
|
| 1244 |
+
device=device,
|
| 1245 |
+
dtype=dtype,
|
| 1246 |
+
shift_override=sigma_shift,
|
| 1247 |
+
)
|
| 1248 |
+
timesteps_action, deltas_action = self.infer_action_scheduler.build_inference_schedule(
|
| 1249 |
+
num_inference_steps=num_inference_steps,
|
| 1250 |
+
device=device,
|
| 1251 |
+
dtype=dtype,
|
| 1252 |
+
shift_override=sigma_shift,
|
| 1253 |
+
)
|
| 1254 |
+
|
| 1255 |
+
for step in range(num_inference_steps):
|
| 1256 |
+
step_t_video = timesteps_video[step].expand(batch)
|
| 1257 |
+
step_t_action = timesteps_action[step].expand(batch)
|
| 1258 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1259 |
+
robot_current_latent=robot_current_latent,
|
| 1260 |
+
human_latents=human_latents,
|
| 1261 |
+
noisy_robot_future_latents=latents_video,
|
| 1262 |
+
noisy_robot_future_action=latents_action,
|
| 1263 |
+
timestep_video=step_t_video,
|
| 1264 |
+
timestep_action=step_t_action,
|
| 1265 |
+
human_mask=human_mask,
|
| 1266 |
+
human_motion_mask=human_motion_mask,
|
| 1267 |
+
robot_current_state=robot_current_state,
|
| 1268 |
+
human_future_action=human_future_action,
|
| 1269 |
+
)
|
| 1270 |
+
latents_video = self.infer_video_scheduler.step(
|
| 1271 |
+
pred_video, deltas_video[step], latents_video
|
| 1272 |
+
)
|
| 1273 |
+
latents_action = self.infer_action_scheduler.step(
|
| 1274 |
+
pred_action, deltas_action[step], latents_action
|
| 1275 |
+
)
|
| 1276 |
+
return latents_video, latents_action
|
| 1277 |
+
|
| 1278 |
+
def forward(self, *args, **kwargs):
|
| 1279 |
+
return self.training_loss(*args, **kwargs)
|
| 1280 |
+
|
| 1281 |
+
|
| 1282 |
+
def count_parameters(model: nn.Module) -> int:
|
| 1283 |
+
return sum(parameter.numel() for parameter in model.parameters())
|
| 1284 |
+
|
| 1285 |
+
|
| 1286 |
+
def parameter_breakdown(model: HRMoTFlowModel) -> dict[str, int]:
|
| 1287 |
+
return {
|
| 1288 |
+
"total": count_parameters(model),
|
| 1289 |
+
"video_expert": count_parameters(model.video_expert),
|
| 1290 |
+
"action_expert": count_parameters(model.action_expert),
|
| 1291 |
+
"video_blocks": sum(count_parameters(b) for b in model.video_expert.blocks),
|
| 1292 |
+
"action_blocks": sum(count_parameters(b) for b in model.action_expert.blocks),
|
| 1293 |
+
}
|
tools/model_code/recorded/carrier/wan22/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/carrier/wan22/helpers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/carrier/wan22/helpers/gradient.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def create_custom_forward(module):
|
| 5 |
+
def custom_forward(*inputs, **kwargs):
|
| 6 |
+
return module(*inputs, **kwargs)
|
| 7 |
+
|
| 8 |
+
return custom_forward
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def gradient_checkpoint_forward(
|
| 12 |
+
model,
|
| 13 |
+
use_gradient_checkpointing,
|
| 14 |
+
*args,
|
| 15 |
+
**kwargs,
|
| 16 |
+
):
|
| 17 |
+
if use_gradient_checkpointing:
|
| 18 |
+
model_output = torch.utils.checkpoint.checkpoint(
|
| 19 |
+
create_custom_forward(model),
|
| 20 |
+
*args,
|
| 21 |
+
**kwargs,
|
| 22 |
+
use_reentrant=False,
|
| 23 |
+
)
|
| 24 |
+
else:
|
| 25 |
+
model_output = model(*args, **kwargs)
|
| 26 |
+
return model_output
|
tools/model_code/recorded/carrier/wan22/mot.py
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Dict, Optional, Sequence
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
from .wan_video_dit import flash_attention, modulate, rope_apply
|
| 9 |
+
from logging import getLogger as get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class MoT(nn.Module):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
mixtures: Dict[str, nn.Module],
|
| 18 |
+
mot_checkpoint_mixed_attn: bool = True,
|
| 19 |
+
):
|
| 20 |
+
super().__init__()
|
| 21 |
+
if not mixtures:
|
| 22 |
+
raise ValueError("`mixtures` cannot be empty.")
|
| 23 |
+
if "video" not in mixtures or "action" not in mixtures:
|
| 24 |
+
raise ValueError("`mixtures` must include both 'video' and 'action' experts.")
|
| 25 |
+
|
| 26 |
+
self.mixtures = nn.ModuleDict(mixtures)
|
| 27 |
+
self.expert_order = list(self.mixtures.keys())
|
| 28 |
+
self.mot_checkpoint_mixed_attn = mot_checkpoint_mixed_attn
|
| 29 |
+
if mot_checkpoint_mixed_attn:
|
| 30 |
+
logger.info(
|
| 31 |
+
"Using gradient checkpointing for mixture attention. This will save memory but use more computation."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
first_expert = self.mixtures[self.expert_order[0]]
|
| 35 |
+
self.num_layers = len(first_expert.blocks)
|
| 36 |
+
self.num_heads = first_expert.num_heads
|
| 37 |
+
self.attn_head_dim = first_expert.attn_head_dim
|
| 38 |
+
|
| 39 |
+
for name in self.expert_order[1:]:
|
| 40 |
+
expert = self.mixtures[name]
|
| 41 |
+
if len(expert.blocks) != self.num_layers:
|
| 42 |
+
raise ValueError(
|
| 43 |
+
f"All experts must have same number of layers; got {self.num_layers} and {len(expert.blocks)}"
|
| 44 |
+
)
|
| 45 |
+
if expert.num_heads != self.num_heads:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"All experts must have same num_heads; got {self.num_heads} and {expert.num_heads}"
|
| 48 |
+
)
|
| 49 |
+
if expert.attn_head_dim != self.attn_head_dim:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
"All experts must have same attn_head_dim; "
|
| 52 |
+
f"got {self.attn_head_dim} and {expert.attn_head_dim}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
logger.info(
|
| 56 |
+
f"Initialized MoT with experts: {self.expert_order}, num_layers={self.num_layers}"
|
| 57 |
+
)
|
| 58 |
+
for name in self.expert_order:
|
| 59 |
+
expert = self.mixtures[name]
|
| 60 |
+
logger.info(
|
| 61 |
+
f" Expert '{name}': num_params={sum(p.numel() for p in expert.parameters()) / 1e9:.2f} B"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _split_modulation(block, t_mod: torch.Tensor):
|
| 66 |
+
has_seq = len(t_mod.shape) == 4
|
| 67 |
+
chunk_dim = 2 if has_seq else 1
|
| 68 |
+
|
| 69 |
+
base_mod = block.modulation.to(dtype=t_mod.dtype, device=t_mod.device)
|
| 70 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (base_mod + t_mod).chunk(
|
| 71 |
+
6, dim=chunk_dim
|
| 72 |
+
)
|
| 73 |
+
if has_seq:
|
| 74 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 75 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 76 |
+
shift_msa.squeeze(2),
|
| 77 |
+
scale_msa.squeeze(2),
|
| 78 |
+
gate_msa.squeeze(2),
|
| 79 |
+
shift_mlp.squeeze(2),
|
| 80 |
+
scale_mlp.squeeze(2),
|
| 81 |
+
gate_mlp.squeeze(2),
|
| 82 |
+
)
|
| 83 |
+
return shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp
|
| 84 |
+
|
| 85 |
+
def _mixed_attention(
|
| 86 |
+
self,
|
| 87 |
+
q_cat: torch.Tensor,
|
| 88 |
+
k_cat: torch.Tensor,
|
| 89 |
+
v_cat: torch.Tensor,
|
| 90 |
+
attention_mask: torch.Tensor,
|
| 91 |
+
) -> torch.Tensor:
|
| 92 |
+
attn_mask = attention_mask.to(device=q_cat.device)
|
| 93 |
+
|
| 94 |
+
def _forward(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
|
| 95 |
+
return flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=attn_mask)
|
| 96 |
+
|
| 97 |
+
if self.mot_checkpoint_mixed_attn and self.training:
|
| 98 |
+
return torch.utils.checkpoint.checkpoint(
|
| 99 |
+
_forward,
|
| 100 |
+
q_cat,
|
| 101 |
+
k_cat,
|
| 102 |
+
v_cat,
|
| 103 |
+
use_reentrant=False,
|
| 104 |
+
)
|
| 105 |
+
return _forward(q_cat, k_cat, v_cat)
|
| 106 |
+
|
| 107 |
+
def _resolve_attention_masks(
|
| 108 |
+
self,
|
| 109 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 110 |
+
expected_seq_len: int,
|
| 111 |
+
) -> list[torch.Tensor]:
|
| 112 |
+
if isinstance(attention_mask, torch.Tensor):
|
| 113 |
+
attention_masks = [attention_mask] * self.num_layers
|
| 114 |
+
else:
|
| 115 |
+
attention_masks = list(attention_mask)
|
| 116 |
+
if len(attention_masks) != self.num_layers:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
f"`attention_mask` must contain {self.num_layers} layers, got {len(attention_masks)}."
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
for layer_idx, layer_mask in enumerate(attention_masks):
|
| 122 |
+
if not isinstance(layer_mask, torch.Tensor):
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"`attention_mask[{layer_idx}]` must be torch.Tensor, got {type(layer_mask)}."
|
| 125 |
+
)
|
| 126 |
+
# [S,S] shares one mask across the batch; [B,S,S] and [B,1,S,S] give a
|
| 127 |
+
# per-sample mask, which is what a per-sample condition-availability
|
| 128 |
+
# pattern needs. All three broadcast correctly in
|
| 129 |
+
# scaled_dot_product_attention against q of shape [B,heads,S,D].
|
| 130 |
+
if layer_mask.ndim not in (2, 3, 4):
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"`attention_mask[{layer_idx}]` must be [S,S], [B,S,S] or [B,1,S,S], "
|
| 133 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 134 |
+
)
|
| 135 |
+
if layer_mask.shape[-1] != layer_mask.shape[-2]:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
f"`attention_mask[{layer_idx}]` must be square in its last two dims, "
|
| 138 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 139 |
+
)
|
| 140 |
+
if layer_mask.shape[-1] != expected_seq_len:
|
| 141 |
+
raise ValueError(
|
| 142 |
+
f"`attention_mask[{layer_idx}]` seq length mismatch: "
|
| 143 |
+
f"mask={layer_mask.shape[-1]} vs expected_total={expected_seq_len}"
|
| 144 |
+
)
|
| 145 |
+
return attention_masks
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def _apply_expert_post_block(
|
| 149 |
+
block,
|
| 150 |
+
residual_x: torch.Tensor,
|
| 151 |
+
mixed_attn_out: torch.Tensor,
|
| 152 |
+
gate_msa: torch.Tensor,
|
| 153 |
+
shift_mlp: torch.Tensor,
|
| 154 |
+
scale_mlp: torch.Tensor,
|
| 155 |
+
gate_mlp: torch.Tensor,
|
| 156 |
+
context_payload: Optional[dict],
|
| 157 |
+
) -> torch.Tensor:
|
| 158 |
+
x = block.gate(residual_x, gate_msa, block.self_attn.o(mixed_attn_out))
|
| 159 |
+
|
| 160 |
+
if context_payload is not None:
|
| 161 |
+
context = context_payload.get("context")
|
| 162 |
+
if context is not None:
|
| 163 |
+
context_mask = context_payload.get("mask")
|
| 164 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 165 |
+
context_mask = context_mask.unsqueeze(1)
|
| 166 |
+
x = x + block.cross_attn(block.norm3(x), context, ctx_mask=context_mask)
|
| 167 |
+
|
| 168 |
+
mlp_input = modulate(block.norm2(x), shift_mlp, scale_mlp)
|
| 169 |
+
x = block.gate(x, gate_mlp, block.ffn(mlp_input))
|
| 170 |
+
return x
|
| 171 |
+
|
| 172 |
+
def _build_expert_attention_io(
|
| 173 |
+
self,
|
| 174 |
+
expert,
|
| 175 |
+
block,
|
| 176 |
+
x: torch.Tensor,
|
| 177 |
+
freqs: torch.Tensor,
|
| 178 |
+
t_mod: torch.Tensor,
|
| 179 |
+
) -> tuple[
|
| 180 |
+
torch.Tensor,
|
| 181 |
+
torch.Tensor,
|
| 182 |
+
torch.Tensor,
|
| 183 |
+
torch.Tensor,
|
| 184 |
+
torch.Tensor,
|
| 185 |
+
torch.Tensor,
|
| 186 |
+
torch.Tensor,
|
| 187 |
+
torch.Tensor,
|
| 188 |
+
bool,
|
| 189 |
+
]:
|
| 190 |
+
"""Build per-expert attention tensors and post-block states.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
expert: Expert module that owns this `block`; only used to read
|
| 194 |
+
`use_gradient_checkpointing`.
|
| 195 |
+
block: Transformer block for current layer (`expert.blocks[layer_idx]`).
|
| 196 |
+
x: Current expert tokens, shape [B, S, D].
|
| 197 |
+
freqs: RoPE frequencies aligned with token sequence, shape [S, 1, rope_dim].
|
| 198 |
+
t_mod: Time modulation tensor for this expert/layer.
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
q: Query after q-proj, RMSNorm, and RoPE, shape [B, S, H*Dh].
|
| 202 |
+
k: Key after k-proj, RMSNorm, and RoPE, shape [B, S, H*Dh].
|
| 203 |
+
v: Value after v-proj, shape [B, S, H*Dh].
|
| 204 |
+
residual_x: Original input `x` for residual path in post block.
|
| 205 |
+
gate_msa: Gating tensor for self-attention residual branch.
|
| 206 |
+
shift_mlp: Shift tensor for MLP modulation.
|
| 207 |
+
scale_mlp: Scale tensor for MLP modulation.
|
| 208 |
+
gate_mlp: Gating tensor for MLP residual branch.
|
| 209 |
+
use_gradient_checkpointing: Whether this expert enables checkpointing.
|
| 210 |
+
"""
|
| 211 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self._split_modulation(
|
| 212 |
+
block, t_mod
|
| 213 |
+
)
|
| 214 |
+
attn_input = modulate(block.norm1(x), shift_msa, scale_msa)
|
| 215 |
+
|
| 216 |
+
q = block.self_attn.norm_q(block.self_attn.q(attn_input))
|
| 217 |
+
k = block.self_attn.norm_k(block.self_attn.k(attn_input))
|
| 218 |
+
v = block.self_attn.v(attn_input)
|
| 219 |
+
|
| 220 |
+
q = rope_apply(q, freqs, block.num_heads)
|
| 221 |
+
k = rope_apply(k, freqs, block.num_heads)
|
| 222 |
+
|
| 223 |
+
use_gradient_checkpointing = bool(getattr(expert, "use_gradient_checkpointing", False))
|
| 224 |
+
return (
|
| 225 |
+
q,
|
| 226 |
+
k,
|
| 227 |
+
v,
|
| 228 |
+
x,
|
| 229 |
+
gate_msa,
|
| 230 |
+
shift_mlp,
|
| 231 |
+
scale_mlp,
|
| 232 |
+
gate_mlp,
|
| 233 |
+
use_gradient_checkpointing,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def _apply_post_with_optional_checkpoint(
|
| 237 |
+
self,
|
| 238 |
+
block,
|
| 239 |
+
residual_x: torch.Tensor,
|
| 240 |
+
gate_msa: torch.Tensor,
|
| 241 |
+
shift_mlp: torch.Tensor,
|
| 242 |
+
scale_mlp: torch.Tensor,
|
| 243 |
+
gate_mlp: torch.Tensor,
|
| 244 |
+
use_gradient_checkpointing: bool,
|
| 245 |
+
mixed_slice: torch.Tensor,
|
| 246 |
+
context_payload: Optional[dict],
|
| 247 |
+
) -> torch.Tensor:
|
| 248 |
+
"""Apply post-attention computations, with optional checkpointing.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
block: Transformer block for current layer.
|
| 252 |
+
residual_x: Residual input tokens before attention update, shape [B, S, D].
|
| 253 |
+
gate_msa: Gating tensor used after mixed self-attention.
|
| 254 |
+
shift_mlp: Shift tensor for MLP input modulation.
|
| 255 |
+
scale_mlp: Scale tensor for MLP input modulation.
|
| 256 |
+
gate_mlp: Gating tensor used after MLP.
|
| 257 |
+
use_gradient_checkpointing: If True and training, checkpoint this post block.
|
| 258 |
+
mixed_slice: Mixed-attention output for this expert, shape [B, S, H*Dh].
|
| 259 |
+
context_payload: Optional dict for cross-attention.
|
| 260 |
+
- `context`: encoder states [B, L, D]
|
| 261 |
+
- `mask`: attention mask [B, S, L] or [B, 1, S, L]
|
| 262 |
+
|
| 263 |
+
Returns:
|
| 264 |
+
Updated expert tokens after self-attn residual, optional cross-attn, and MLP.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
def _post_fn(
|
| 268 |
+
_mixed_slice: torch.Tensor,
|
| 269 |
+
_x: torch.Tensor,
|
| 270 |
+
_gate_msa: torch.Tensor,
|
| 271 |
+
_shift_mlp: torch.Tensor,
|
| 272 |
+
_scale_mlp: torch.Tensor,
|
| 273 |
+
_gate_mlp: torch.Tensor,
|
| 274 |
+
_block=block,
|
| 275 |
+
_context_payload=context_payload,
|
| 276 |
+
) -> torch.Tensor:
|
| 277 |
+
return self._apply_expert_post_block(
|
| 278 |
+
block=_block,
|
| 279 |
+
residual_x=_x,
|
| 280 |
+
mixed_attn_out=_mixed_slice,
|
| 281 |
+
gate_msa=_gate_msa,
|
| 282 |
+
shift_mlp=_shift_mlp,
|
| 283 |
+
scale_mlp=_scale_mlp,
|
| 284 |
+
gate_mlp=_gate_mlp,
|
| 285 |
+
context_payload=_context_payload,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if use_gradient_checkpointing and self.training:
|
| 289 |
+
return torch.utils.checkpoint.checkpoint(
|
| 290 |
+
_post_fn,
|
| 291 |
+
mixed_slice,
|
| 292 |
+
residual_x,
|
| 293 |
+
gate_msa,
|
| 294 |
+
shift_mlp,
|
| 295 |
+
scale_mlp,
|
| 296 |
+
gate_mlp,
|
| 297 |
+
use_reentrant=False,
|
| 298 |
+
)
|
| 299 |
+
return _post_fn(
|
| 300 |
+
mixed_slice,
|
| 301 |
+
residual_x,
|
| 302 |
+
gate_msa,
|
| 303 |
+
shift_mlp,
|
| 304 |
+
scale_mlp,
|
| 305 |
+
gate_mlp,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
def prefill_video_cache(
|
| 309 |
+
self,
|
| 310 |
+
video_tokens: torch.Tensor,
|
| 311 |
+
video_freqs: torch.Tensor,
|
| 312 |
+
video_t_mod: torch.Tensor,
|
| 313 |
+
video_context_payload: Optional[dict],
|
| 314 |
+
video_attention_mask: torch.Tensor,
|
| 315 |
+
) -> list[dict[str, torch.Tensor]]:
|
| 316 |
+
"""Prefill video branch once and cache per-layer K/V for action denoising.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
video_tokens: Video tokens before layer 0, shape [B, Sv, D].
|
| 320 |
+
video_freqs: Video RoPE frequencies, shape [Sv, 1, rope_dim].
|
| 321 |
+
video_t_mod: Video time modulation tensor.
|
| 322 |
+
video_context_payload: Optional dict for video cross-attention.
|
| 323 |
+
- `context`: encoder states [B, L, D]
|
| 324 |
+
- `mask`: attention mask [B, Sv, L] or [B, 1, Sv, L]
|
| 325 |
+
video_attention_mask: Video self-attention mask, shape [Sv, Sv].
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
Layer-wise cache list with length `num_layers`.
|
| 329 |
+
Each entry contains:
|
| 330 |
+
- `k`: video key tensor [B, Sv, H*Dh]
|
| 331 |
+
- `v`: video value tensor [B, Sv, H*Dh]
|
| 332 |
+
"""
|
| 333 |
+
if "video" not in self.mixtures:
|
| 334 |
+
raise ValueError("MoT requires `video` expert for `prefill_video_cache`.")
|
| 335 |
+
if video_attention_mask.ndim != 2:
|
| 336 |
+
raise ValueError(
|
| 337 |
+
f"`video_attention_mask` must be 2D [S,S], got shape {tuple(video_attention_mask.shape)}"
|
| 338 |
+
)
|
| 339 |
+
if video_attention_mask.shape[0] != video_attention_mask.shape[1]:
|
| 340 |
+
raise ValueError(
|
| 341 |
+
f"`video_attention_mask` must be square, got shape {tuple(video_attention_mask.shape)}"
|
| 342 |
+
)
|
| 343 |
+
if video_attention_mask.shape[0] != video_tokens.shape[1]:
|
| 344 |
+
raise ValueError(
|
| 345 |
+
"`video_attention_mask` seq length mismatch: "
|
| 346 |
+
f"mask={video_attention_mask.shape[0]} vs tokens={video_tokens.shape[1]}"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
expert = self.mixtures["video"]
|
| 350 |
+
x = video_tokens
|
| 351 |
+
kv_cache: list[dict[str, torch.Tensor]] = []
|
| 352 |
+
for layer_idx in range(self.num_layers):
|
| 353 |
+
block = expert.blocks[layer_idx]
|
| 354 |
+
# Build video Q/K/V from current layer input tokens.
|
| 355 |
+
(
|
| 356 |
+
q,
|
| 357 |
+
k,
|
| 358 |
+
v,
|
| 359 |
+
residual_x,
|
| 360 |
+
gate_msa,
|
| 361 |
+
shift_mlp,
|
| 362 |
+
scale_mlp,
|
| 363 |
+
gate_mlp,
|
| 364 |
+
use_gradient_checkpointing,
|
| 365 |
+
) = self._build_expert_attention_io(
|
| 366 |
+
expert=expert,
|
| 367 |
+
block=block,
|
| 368 |
+
x=x,
|
| 369 |
+
freqs=video_freqs,
|
| 370 |
+
t_mod=video_t_mod,
|
| 371 |
+
)
|
| 372 |
+
# Video prefill uses only video self-attention mask.
|
| 373 |
+
mixed = self._mixed_attention(
|
| 374 |
+
q_cat=q,
|
| 375 |
+
k_cat=k,
|
| 376 |
+
v_cat=v,
|
| 377 |
+
attention_mask=video_attention_mask,
|
| 378 |
+
)
|
| 379 |
+
# Update video tokens for the next layer and persist current layer K/V.
|
| 380 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 381 |
+
block=block,
|
| 382 |
+
residual_x=residual_x,
|
| 383 |
+
gate_msa=gate_msa,
|
| 384 |
+
shift_mlp=shift_mlp,
|
| 385 |
+
scale_mlp=scale_mlp,
|
| 386 |
+
gate_mlp=gate_mlp,
|
| 387 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 388 |
+
mixed_slice=mixed,
|
| 389 |
+
context_payload=video_context_payload,
|
| 390 |
+
)
|
| 391 |
+
kv_cache.append({"k": k, "v": v})
|
| 392 |
+
return kv_cache
|
| 393 |
+
|
| 394 |
+
def forward_action_with_video_cache(
|
| 395 |
+
self,
|
| 396 |
+
action_tokens: torch.Tensor,
|
| 397 |
+
action_freqs: torch.Tensor,
|
| 398 |
+
action_t_mod: torch.Tensor,
|
| 399 |
+
action_context_payload: Optional[dict],
|
| 400 |
+
video_kv_cache: list[dict[str, torch.Tensor]],
|
| 401 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 402 |
+
video_seq_len: int,
|
| 403 |
+
) -> torch.Tensor:
|
| 404 |
+
"""Run action branch with cached video K/V instead of recomputing video tokens.
|
| 405 |
+
|
| 406 |
+
Args:
|
| 407 |
+
action_tokens: Action tokens before layer 0, shape [B, Sa, D].
|
| 408 |
+
action_freqs: Action RoPE frequencies, shape [Sa, 1, rope_dim].
|
| 409 |
+
action_t_mod: Action time modulation tensor.
|
| 410 |
+
action_context_payload: Optional dict for action cross-attention.
|
| 411 |
+
- `context`: encoder states [B, L, D]
|
| 412 |
+
- `mask`: attention mask [B, Sa, L] or [B, 1, Sa, L]
|
| 413 |
+
video_kv_cache: Layer-wise cached video K/V from `prefill_video_cache`.
|
| 414 |
+
attention_mask: Joint [video+action] mask, shape [Sv+Sa, Sv+Sa].
|
| 415 |
+
video_seq_len: Video token count `Sv` in the joint sequence prefix.
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
Updated action tokens after all layers, shape [B, Sa, D].
|
| 419 |
+
"""
|
| 420 |
+
if "action" not in self.mixtures:
|
| 421 |
+
raise ValueError("MoT requires `action` expert for `forward_action_with_video_cache`.")
|
| 422 |
+
if len(video_kv_cache) != self.num_layers:
|
| 423 |
+
raise ValueError(
|
| 424 |
+
f"`video_kv_cache` must contain {self.num_layers} layers, got {len(video_kv_cache)}."
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
action_seq_len = int(action_tokens.shape[1])
|
| 428 |
+
total_seq_len = int(video_seq_len) + action_seq_len
|
| 429 |
+
attention_masks = self._resolve_attention_masks(
|
| 430 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
expert = self.mixtures["action"]
|
| 434 |
+
x = action_tokens
|
| 435 |
+
for layer_idx in range(self.num_layers):
|
| 436 |
+
block = expert.blocks[layer_idx]
|
| 437 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 438 |
+
action_attention_mask = layer_attention_mask[
|
| 439 |
+
video_seq_len:total_seq_len, :total_seq_len
|
| 440 |
+
]
|
| 441 |
+
# Action query/key/value are still step-dependent and must be recomputed each step.
|
| 442 |
+
(
|
| 443 |
+
q_action,
|
| 444 |
+
k_action,
|
| 445 |
+
v_action,
|
| 446 |
+
residual_x,
|
| 447 |
+
gate_msa,
|
| 448 |
+
shift_mlp,
|
| 449 |
+
scale_mlp,
|
| 450 |
+
gate_mlp,
|
| 451 |
+
use_gradient_checkpointing,
|
| 452 |
+
) = self._build_expert_attention_io(
|
| 453 |
+
expert=expert,
|
| 454 |
+
block=block,
|
| 455 |
+
x=x,
|
| 456 |
+
freqs=action_freqs,
|
| 457 |
+
t_mod=action_t_mod,
|
| 458 |
+
)
|
| 459 |
+
layer_cache = video_kv_cache[layer_idx]
|
| 460 |
+
if "k" not in layer_cache or "v" not in layer_cache:
|
| 461 |
+
raise ValueError(f"`video_kv_cache[{layer_idx}]` must contain `k` and `v`.")
|
| 462 |
+
|
| 463 |
+
k_video = layer_cache["k"]
|
| 464 |
+
v_video = layer_cache["v"]
|
| 465 |
+
if k_video.shape[1] != video_seq_len or v_video.shape[1] != video_seq_len:
|
| 466 |
+
raise ValueError(
|
| 467 |
+
f"`video_kv_cache[{layer_idx}]` seq len mismatch, expected {video_seq_len}."
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# Mixed attention: action queries attend to cached video K/V plus current action K/V.
|
| 471 |
+
k_cat = torch.cat([k_video, k_action], dim=1)
|
| 472 |
+
v_cat = torch.cat([v_video, v_action], dim=1)
|
| 473 |
+
mixed = self._mixed_attention(
|
| 474 |
+
q_cat=q_action,
|
| 475 |
+
k_cat=k_cat,
|
| 476 |
+
v_cat=v_cat,
|
| 477 |
+
attention_mask=action_attention_mask,
|
| 478 |
+
)
|
| 479 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 480 |
+
block=block,
|
| 481 |
+
residual_x=residual_x,
|
| 482 |
+
gate_msa=gate_msa,
|
| 483 |
+
shift_mlp=shift_mlp,
|
| 484 |
+
scale_mlp=scale_mlp,
|
| 485 |
+
gate_mlp=gate_mlp,
|
| 486 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 487 |
+
mixed_slice=mixed,
|
| 488 |
+
context_payload=action_context_payload,
|
| 489 |
+
)
|
| 490 |
+
return x
|
| 491 |
+
|
| 492 |
+
def forward(
|
| 493 |
+
self,
|
| 494 |
+
embeds_all: Dict[str, torch.Tensor],
|
| 495 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 496 |
+
freqs_all: Dict[str, torch.Tensor],
|
| 497 |
+
context_all: Dict[str, Optional[dict]],
|
| 498 |
+
t_mod_all: Dict[str, torch.Tensor],
|
| 499 |
+
):
|
| 500 |
+
missing = [k for k in self.expert_order if k not in embeds_all]
|
| 501 |
+
if missing:
|
| 502 |
+
raise ValueError(f"Missing expert tokens for {missing}")
|
| 503 |
+
missing = [k for k in self.expert_order if k not in freqs_all]
|
| 504 |
+
if missing:
|
| 505 |
+
raise ValueError(f"Missing expert freqs for {missing}")
|
| 506 |
+
missing = [k for k in self.expert_order if k not in t_mod_all]
|
| 507 |
+
if missing:
|
| 508 |
+
raise ValueError(f"Missing expert t_mod for {missing}")
|
| 509 |
+
|
| 510 |
+
tokens_all = {k: v for k, v in embeds_all.items()}
|
| 511 |
+
total_seq_len = sum(int(tokens_all[name].shape[1]) for name in self.expert_order)
|
| 512 |
+
attention_masks = self._resolve_attention_masks(
|
| 513 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
for layer_idx in range(self.num_layers):
|
| 517 |
+
q_chunks = []
|
| 518 |
+
k_chunks = []
|
| 519 |
+
v_chunks = []
|
| 520 |
+
cached = {}
|
| 521 |
+
seq_lens = []
|
| 522 |
+
|
| 523 |
+
for name in self.expert_order:
|
| 524 |
+
expert = self.mixtures[name]
|
| 525 |
+
block = expert.blocks[layer_idx]
|
| 526 |
+
x = tokens_all[name]
|
| 527 |
+
freqs = freqs_all[name]
|
| 528 |
+
t_mod = t_mod_all[name]
|
| 529 |
+
|
| 530 |
+
(
|
| 531 |
+
q,
|
| 532 |
+
k,
|
| 533 |
+
v,
|
| 534 |
+
residual_x,
|
| 535 |
+
gate_msa,
|
| 536 |
+
shift_mlp,
|
| 537 |
+
scale_mlp,
|
| 538 |
+
gate_mlp,
|
| 539 |
+
use_gradient_checkpointing,
|
| 540 |
+
) = self._build_expert_attention_io(
|
| 541 |
+
expert=expert,
|
| 542 |
+
block=block,
|
| 543 |
+
x=x,
|
| 544 |
+
freqs=freqs,
|
| 545 |
+
t_mod=t_mod,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
q_chunks.append(q)
|
| 549 |
+
k_chunks.append(k)
|
| 550 |
+
v_chunks.append(v)
|
| 551 |
+
seq_lens.append(x.shape[1])
|
| 552 |
+
cached[name] = {
|
| 553 |
+
"block": block,
|
| 554 |
+
"residual_x": residual_x,
|
| 555 |
+
"gate_msa": gate_msa,
|
| 556 |
+
"shift_mlp": shift_mlp,
|
| 557 |
+
"scale_mlp": scale_mlp,
|
| 558 |
+
"gate_mlp": gate_mlp,
|
| 559 |
+
"use_gradient_checkpointing": use_gradient_checkpointing,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
# 3. concat all tokens for mixed attention
|
| 563 |
+
q_cat = torch.cat(q_chunks, dim=1)
|
| 564 |
+
k_cat = torch.cat(k_chunks, dim=1)
|
| 565 |
+
v_cat = torch.cat(v_chunks, dim=1)
|
| 566 |
+
|
| 567 |
+
total_seq = q_cat.shape[1]
|
| 568 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 569 |
+
if layer_attention_mask.shape[-1] != total_seq:
|
| 570 |
+
raise ValueError(
|
| 571 |
+
"Attention mask seq length mismatch: "
|
| 572 |
+
f"mask={layer_attention_mask.shape[-1]} vs tokens={total_seq}"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
mixed = self._mixed_attention(
|
| 576 |
+
q_cat=q_cat,
|
| 577 |
+
k_cat=k_cat,
|
| 578 |
+
v_cat=v_cat,
|
| 579 |
+
attention_mask=layer_attention_mask,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
start = 0
|
| 583 |
+
for name, seq_len in zip(self.expert_order, seq_lens):
|
| 584 |
+
# 4. split mixed attention output and apply post-attention blocks for each expert
|
| 585 |
+
end = start + seq_len
|
| 586 |
+
mixed_slice = mixed[:, start:end, :]
|
| 587 |
+
cached_expert = cached[name]
|
| 588 |
+
block = cached_expert["block"]
|
| 589 |
+
context_payload = context_all.get(name)
|
| 590 |
+
|
| 591 |
+
updated_tokens = self._apply_post_with_optional_checkpoint(
|
| 592 |
+
block=block,
|
| 593 |
+
residual_x=cached_expert["residual_x"],
|
| 594 |
+
gate_msa=cached_expert["gate_msa"],
|
| 595 |
+
shift_mlp=cached_expert["shift_mlp"],
|
| 596 |
+
scale_mlp=cached_expert["scale_mlp"],
|
| 597 |
+
gate_mlp=cached_expert["gate_mlp"],
|
| 598 |
+
use_gradient_checkpointing=cached_expert["use_gradient_checkpointing"],
|
| 599 |
+
mixed_slice=mixed_slice,
|
| 600 |
+
context_payload=context_payload,
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
tokens_all[name] = updated_tokens
|
| 604 |
+
start = end
|
| 605 |
+
|
| 606 |
+
return tokens_all
|
tools/model_code/recorded/carrier/wan22/schedulers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/carrier/wan22/schedulers/scheduler_continuous.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class WanContinuousFlowMatchScheduler:
|
| 5 |
+
"""Continuous-time Flow-Matching scheduler with shift-based sampling."""
|
| 6 |
+
|
| 7 |
+
def __init__(self, num_train_timesteps: int = 1000, shift: float = 5.0, eps: float = 1e-10):
|
| 8 |
+
if num_train_timesteps <= 0:
|
| 9 |
+
raise ValueError(f"`num_train_timesteps` must be positive, got {num_train_timesteps}")
|
| 10 |
+
if shift <= 0:
|
| 11 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 12 |
+
self.num_train_timesteps = int(num_train_timesteps)
|
| 13 |
+
self.shift = float(shift)
|
| 14 |
+
self.eps = float(eps)
|
| 15 |
+
self._y_min, self._weight_norm_const = self._precompute_training_weight_stats()
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def _phi(u: torch.Tensor, shift: float) -> torch.Tensor:
|
| 19 |
+
return shift * u / (1.0 + (shift - 1.0) * u)
|
| 20 |
+
|
| 21 |
+
def _precompute_training_weight_stats(self) -> tuple[float, float]:
|
| 22 |
+
steps = self.num_train_timesteps
|
| 23 |
+
u_grid = torch.linspace(1.0, 0.0, steps + 1, dtype=torch.float64)[:-1]
|
| 24 |
+
t_grid = self._phi(u_grid, self.shift) * float(steps)
|
| 25 |
+
y_grid = torch.exp(-2.0 * ((t_grid - (steps / 2.0)) / steps) ** 2)
|
| 26 |
+
y_min = float(y_grid.min().item())
|
| 27 |
+
y_shifted_grid = y_grid - y_min
|
| 28 |
+
norm_const = float(y_shifted_grid.mean().item())
|
| 29 |
+
return y_min, norm_const
|
| 30 |
+
|
| 31 |
+
def sample_training_t(
|
| 32 |
+
self, batch_size: int, device: torch.device, dtype: torch.dtype
|
| 33 |
+
) -> torch.Tensor:
|
| 34 |
+
if batch_size <= 0:
|
| 35 |
+
raise ValueError(f"`batch_size` must be positive, got {batch_size}")
|
| 36 |
+
u = torch.rand((batch_size,), device=device, dtype=torch.float32)
|
| 37 |
+
sigma = self._phi(u, self.shift)
|
| 38 |
+
timestep = sigma * float(self.num_train_timesteps)
|
| 39 |
+
return timestep.to(dtype=dtype)
|
| 40 |
+
|
| 41 |
+
def training_weight(self, timestep: torch.Tensor) -> torch.Tensor:
|
| 42 |
+
t = timestep.to(dtype=torch.float32)
|
| 43 |
+
steps = float(self.num_train_timesteps)
|
| 44 |
+
y = torch.exp(-2.0 * ((t - (steps / 2.0)) / steps) ** 2)
|
| 45 |
+
y_shifted = y - self._y_min
|
| 46 |
+
weight = y_shifted / (self._weight_norm_const + self.eps)
|
| 47 |
+
if weight.numel() == 1:
|
| 48 |
+
return weight.reshape(())
|
| 49 |
+
return weight
|
| 50 |
+
|
| 51 |
+
def add_noise(
|
| 52 |
+
self, original_samples: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 53 |
+
) -> torch.Tensor:
|
| 54 |
+
sigma = (timestep / float(self.num_train_timesteps)).to(
|
| 55 |
+
original_samples.device, dtype=original_samples.dtype
|
| 56 |
+
)
|
| 57 |
+
if sigma.ndim == 0:
|
| 58 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 59 |
+
sigma = sigma.view(-1, *([1] * (original_samples.ndim - 1)))
|
| 60 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def training_target(
|
| 64 |
+
sample: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 65 |
+
) -> torch.Tensor:
|
| 66 |
+
del timestep
|
| 67 |
+
return noise - sample
|
| 68 |
+
|
| 69 |
+
def build_inference_schedule(
|
| 70 |
+
self,
|
| 71 |
+
num_inference_steps: int,
|
| 72 |
+
device: torch.device,
|
| 73 |
+
dtype: torch.dtype,
|
| 74 |
+
shift_override: float | None = None,
|
| 75 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 76 |
+
if num_inference_steps <= 0:
|
| 77 |
+
raise ValueError(f"`num_inference_steps` must be positive, got {num_inference_steps}")
|
| 78 |
+
shift = self.shift if shift_override is None else float(shift_override)
|
| 79 |
+
if shift <= 0:
|
| 80 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 81 |
+
|
| 82 |
+
u_steps = torch.linspace(
|
| 83 |
+
1.0, 0.0, num_inference_steps + 1, device=device, dtype=torch.float32
|
| 84 |
+
)
|
| 85 |
+
sigma_steps = self._phi(u_steps, shift)
|
| 86 |
+
timesteps = sigma_steps[:-1] * float(self.num_train_timesteps)
|
| 87 |
+
deltas = sigma_steps[1:] - sigma_steps[:-1]
|
| 88 |
+
return timesteps.to(dtype=dtype), deltas.to(dtype=dtype)
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def step(model_output: torch.Tensor, delta: torch.Tensor, sample: torch.Tensor) -> torch.Tensor:
|
| 92 |
+
delta = delta.to(sample.device, dtype=sample.dtype)
|
| 93 |
+
if delta.ndim == 0:
|
| 94 |
+
return sample + model_output * delta
|
| 95 |
+
delta = delta.view(-1, *([1] * (sample.ndim - 1)))
|
| 96 |
+
return sample + model_output * delta
|
tools/model_code/recorded/carrier/wan22/wan_video_dit.py
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import math
|
| 5 |
+
from typing import Any, Dict, Tuple, Optional
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from .helpers.gradient import gradient_checkpoint_forward
|
| 8 |
+
|
| 9 |
+
from logging import getLogger as get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def flash_attention(
|
| 15 |
+
q: torch.Tensor,
|
| 16 |
+
k: torch.Tensor,
|
| 17 |
+
v: torch.Tensor,
|
| 18 |
+
num_heads: int,
|
| 19 |
+
ctx_mask: Optional[torch.Tensor] = None,
|
| 20 |
+
compatibility_mode=True,
|
| 21 |
+
):
|
| 22 |
+
if compatibility_mode:
|
| 23 |
+
q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
|
| 24 |
+
k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
|
| 25 |
+
v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
|
| 26 |
+
x = F.scaled_dot_product_attention(q, k, v, attn_mask=ctx_mask)
|
| 27 |
+
x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
|
| 28 |
+
return x
|
| 29 |
+
else:
|
| 30 |
+
raise NotImplementedError(
|
| 31 |
+
"Only compatibility mode is implemented for flash attention. Please set compatibility_mode=True."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor):
|
| 36 |
+
return x * (1 + scale) + shift
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def sinusoidal_embedding_1d(dim, position):
|
| 40 |
+
sinusoid = torch.outer(
|
| 41 |
+
position.type(torch.float64),
|
| 42 |
+
torch.pow(
|
| 43 |
+
10000,
|
| 44 |
+
-torch.arange(dim // 2, dtype=torch.float64, device=position.device).div(dim // 2),
|
| 45 |
+
),
|
| 46 |
+
)
|
| 47 |
+
x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
|
| 48 |
+
return x.to(position.dtype)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def precompute_freqs_cis_3d(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 52 |
+
# 3d rope precompute
|
| 53 |
+
f_freqs_cis = precompute_freqs_cis(dim - 2 * (dim // 3), end, theta)
|
| 54 |
+
h_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 55 |
+
w_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 56 |
+
return f_freqs_cis, h_freqs_cis, w_freqs_cis
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def precompute_freqs_cis(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 60 |
+
# 1d rope precompute
|
| 61 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].double() / dim))
|
| 62 |
+
freqs = torch.outer(torch.arange(end, device=freqs.device), freqs)
|
| 63 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
|
| 64 |
+
return freqs_cis
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def rope_apply(x, freqs, num_heads):
|
| 68 |
+
x = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
|
| 69 |
+
x_out = torch.view_as_complex(
|
| 70 |
+
x.to(torch.float64).reshape(x.shape[0], x.shape[1], x.shape[2], -1, 2)
|
| 71 |
+
)
|
| 72 |
+
freqs = freqs.to(torch.complex64) if freqs.device.type == "npu" else freqs
|
| 73 |
+
x_out = torch.view_as_real(x_out * freqs).flatten(2)
|
| 74 |
+
return x_out.to(x.dtype)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def create_group_causal_attn_mask(
|
| 78 |
+
num_temporal_groups: int, num_query_per_group: int, num_key_per_group: int, mode: str = "causal"
|
| 79 |
+
) -> torch.Tensor:
|
| 80 |
+
"""
|
| 81 |
+
Creates a group-based attention mask for scaled dot-product attention with two modes:
|
| 82 |
+
'causal' and 'group_diagonal'.
|
| 83 |
+
|
| 84 |
+
Parameters:
|
| 85 |
+
- num_temporal_groups (int): The number of temporal groups (e.g., frames in a video sequence).
|
| 86 |
+
- num_query_per_group (int): The number of query tokens per temporal group. (e.g., latent tokens in a frame, H x W).
|
| 87 |
+
- num_key_per_group (int): The number of key tokens per temporal group. (e.g., action tokens per frame).
|
| 88 |
+
- mode (str): The mode of the attention mask. Options are:
|
| 89 |
+
- 'causal': Query tokens can attend to key tokens from the same or previous temporal groups.
|
| 90 |
+
- 'group_diagonal': Query tokens can attend only to key tokens from the same temporal group.
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
- attn_mask (torch.Tensor): A boolean tensor of shape (L, S), where:
|
| 94 |
+
- L = num_temporal_groups * num_query_per_group (total number of query tokens)
|
| 95 |
+
- S = num_temporal_groups * num_key_per_group (total number of key tokens)
|
| 96 |
+
The mask indicates where attention is allowed (True) and disallowed (False).
|
| 97 |
+
|
| 98 |
+
Example:
|
| 99 |
+
Input:
|
| 100 |
+
num_temporal_groups = 3
|
| 101 |
+
num_query_per_group = 4
|
| 102 |
+
num_key_per_group = 2
|
| 103 |
+
Output:
|
| 104 |
+
Causal Mask Shape: torch.Size([12, 6])
|
| 105 |
+
Group Diagonal Mask Shape: torch.Size([12, 6])
|
| 106 |
+
if mode='causal':
|
| 107 |
+
tensor([[ True, True, False, False, False, False],
|
| 108 |
+
[ True, True, False, False, False, False],
|
| 109 |
+
[ True, True, False, False, False, False],
|
| 110 |
+
[ True, True, False, False, False, False],
|
| 111 |
+
[ True, True, True, True, False, False],
|
| 112 |
+
[ True, True, True, True, False, False],
|
| 113 |
+
[ True, True, True, True, False, False],
|
| 114 |
+
[ True, True, True, True, False, False],
|
| 115 |
+
[ True, True, True, True, True, True],
|
| 116 |
+
[ True, True, True, True, True, True],
|
| 117 |
+
[ True, True, True, True, True, True],
|
| 118 |
+
[ True, True, True, True, True, True]])
|
| 119 |
+
|
| 120 |
+
if mode='group_diagonal':
|
| 121 |
+
tensor([[ True, True, False, False, False, False],
|
| 122 |
+
[ True, True, False, False, False, False],
|
| 123 |
+
[ True, True, False, False, False, False],
|
| 124 |
+
[ True, True, False, False, False, False],
|
| 125 |
+
[False, False, True, True, False, False],
|
| 126 |
+
[False, False, True, True, False, False],
|
| 127 |
+
[False, False, True, True, False, False],
|
| 128 |
+
[False, False, True, True, False, False],
|
| 129 |
+
[False, False, False, False, True, True],
|
| 130 |
+
[False, False, False, False, True, True],
|
| 131 |
+
[False, False, False, False, True, True],
|
| 132 |
+
[False, False, False, False, True, True]])
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
assert mode in ["causal", "group_diagonal"], f"Mode {mode} must be 'causal' or 'group_diagonal'"
|
| 136 |
+
|
| 137 |
+
# Total number of query and key tokens
|
| 138 |
+
total_num_query_tokens = (
|
| 139 |
+
num_temporal_groups * num_query_per_group
|
| 140 |
+
) # Total number of query tokens (L)
|
| 141 |
+
total_num_key_tokens = num_temporal_groups * num_key_per_group # Total number of key tokens (S)
|
| 142 |
+
|
| 143 |
+
# Generate time indices for query and key tokens (shape: [L] and [S])
|
| 144 |
+
query_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 145 |
+
num_query_per_group
|
| 146 |
+
) # Shape: [L]
|
| 147 |
+
key_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 148 |
+
num_key_per_group
|
| 149 |
+
) # Shape: [S]
|
| 150 |
+
|
| 151 |
+
# Expand dimensions to compute outer comparison
|
| 152 |
+
query_time_indices = query_time_indices.unsqueeze(1) # Shape: [L, 1]
|
| 153 |
+
key_time_indices = key_time_indices.unsqueeze(0) # Shape: [1, S]
|
| 154 |
+
|
| 155 |
+
if mode == "causal":
|
| 156 |
+
# Causal Mode: Query can attend to keys where key_time <= query_time
|
| 157 |
+
attn_mask = query_time_indices >= key_time_indices # Shape: [L, S]
|
| 158 |
+
elif mode == "group_diagonal":
|
| 159 |
+
# Group Diagonal Mode: Query can attend only to keys where key_time == query_time
|
| 160 |
+
attn_mask = query_time_indices == key_time_indices # Shape: [L, S]
|
| 161 |
+
|
| 162 |
+
assert attn_mask.shape == (
|
| 163 |
+
total_num_query_tokens,
|
| 164 |
+
total_num_key_tokens,
|
| 165 |
+
), "Attention mask shape mismatch"
|
| 166 |
+
return attn_mask
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class RMSNorm(nn.Module):
|
| 170 |
+
def __init__(self, dim, eps=1e-5):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.eps = eps
|
| 173 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 174 |
+
|
| 175 |
+
def norm(self, x):
|
| 176 |
+
return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
|
| 177 |
+
|
| 178 |
+
def forward(self, x):
|
| 179 |
+
dtype = x.dtype
|
| 180 |
+
return self.norm(x.float()).to(dtype) * self.weight
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class AttentionModule(nn.Module):
|
| 184 |
+
def __init__(self, num_heads):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.num_heads = num_heads
|
| 187 |
+
|
| 188 |
+
def forward(self, q, k, v, ctx_mask=None):
|
| 189 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 190 |
+
return x
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SelfAttention(nn.Module):
|
| 194 |
+
def __init__(self, hidden_dim: int, attn_head_dim: int, num_heads: int, eps: float = 1e-6):
|
| 195 |
+
super().__init__()
|
| 196 |
+
self.hidden_dim = hidden_dim
|
| 197 |
+
self.num_heads = num_heads
|
| 198 |
+
self.attn_head_dim = attn_head_dim
|
| 199 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 200 |
+
|
| 201 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 202 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 203 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 204 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 205 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 206 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 207 |
+
|
| 208 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 209 |
+
|
| 210 |
+
def forward(self, x, freqs, self_attn_mask: Optional[torch.Tensor] = None):
|
| 211 |
+
q = self.norm_q(self.q(x))
|
| 212 |
+
k = self.norm_k(self.k(x))
|
| 213 |
+
v = self.v(x)
|
| 214 |
+
q = rope_apply(q, freqs, self.num_heads)
|
| 215 |
+
k = rope_apply(k, freqs, self.num_heads)
|
| 216 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=self_attn_mask)
|
| 217 |
+
return self.o(x)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class CrossAttention(nn.Module):
|
| 221 |
+
def __init__(
|
| 222 |
+
self,
|
| 223 |
+
hidden_dim: int,
|
| 224 |
+
attn_head_dim: int,
|
| 225 |
+
num_heads: int,
|
| 226 |
+
eps: float = 1e-6,
|
| 227 |
+
):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.hidden_dim = hidden_dim
|
| 230 |
+
self.num_heads = num_heads
|
| 231 |
+
self.attn_head_dim = attn_head_dim
|
| 232 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 233 |
+
|
| 234 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 235 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 236 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 237 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 238 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 239 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 240 |
+
|
| 241 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 242 |
+
|
| 243 |
+
def forward(self, x: torch.Tensor, ctx: torch.Tensor, ctx_mask: Optional[torch.Tensor] = None):
|
| 244 |
+
q = self.norm_q(self.q(x))
|
| 245 |
+
k = self.norm_k(self.k(ctx))
|
| 246 |
+
v = self.v(ctx)
|
| 247 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 248 |
+
return self.o(x)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class GateModule(nn.Module):
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
def forward(self, x, gate, residual):
|
| 258 |
+
return x + gate * residual
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class DiTBlock(nn.Module):
|
| 262 |
+
def __init__(
|
| 263 |
+
self, hidden_dim: int, attn_head_dim: int, num_heads: int, ffn_dim: int, eps: float = 1e-6
|
| 264 |
+
):
|
| 265 |
+
super().__init__()
|
| 266 |
+
self.hidden_dim = hidden_dim
|
| 267 |
+
self.attn_head_dim = attn_head_dim
|
| 268 |
+
self.num_heads = num_heads
|
| 269 |
+
self.ffn_dim = ffn_dim
|
| 270 |
+
|
| 271 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 272 |
+
self.cross_attn = CrossAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 273 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 274 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 275 |
+
self.norm3 = nn.LayerNorm(hidden_dim, eps=eps)
|
| 276 |
+
self.ffn = nn.Sequential(
|
| 277 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 278 |
+
nn.GELU(approximate="tanh"),
|
| 279 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 280 |
+
)
|
| 281 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 282 |
+
self.gate = GateModule()
|
| 283 |
+
|
| 284 |
+
def forward(
|
| 285 |
+
self,
|
| 286 |
+
x,
|
| 287 |
+
context,
|
| 288 |
+
t_mod,
|
| 289 |
+
freqs,
|
| 290 |
+
context_mask=None,
|
| 291 |
+
self_attn_mask: Optional[torch.Tensor] = None,
|
| 292 |
+
):
|
| 293 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 294 |
+
context_mask = context_mask.unsqueeze(1) # (B, 1, seq_len, context_len), 1 for heads
|
| 295 |
+
has_seq = len(t_mod.shape) == 4
|
| 296 |
+
chunk_dim = 2 if has_seq else 1
|
| 297 |
+
# msa: multi-head self-attention mlp: multi-layer perceptron
|
| 298 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 299 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 300 |
+
).chunk(6, dim=chunk_dim)
|
| 301 |
+
if has_seq:
|
| 302 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 303 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 304 |
+
shift_msa.squeeze(2),
|
| 305 |
+
scale_msa.squeeze(2),
|
| 306 |
+
gate_msa.squeeze(2),
|
| 307 |
+
shift_mlp.squeeze(2),
|
| 308 |
+
scale_mlp.squeeze(2),
|
| 309 |
+
gate_mlp.squeeze(2),
|
| 310 |
+
)
|
| 311 |
+
input_x = modulate(self.norm1(x), shift_msa, scale_msa)
|
| 312 |
+
x = self.gate(x, gate_msa, self.self_attn(input_x, freqs, self_attn_mask=self_attn_mask))
|
| 313 |
+
x = x + self.cross_attn(self.norm3(x), context, ctx_mask=context_mask)
|
| 314 |
+
input_x = modulate(self.norm2(x), shift_mlp, scale_mlp)
|
| 315 |
+
x = self.gate(x, gate_mlp, self.ffn(input_x))
|
| 316 |
+
return x
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class MLP(torch.nn.Module):
|
| 320 |
+
def __init__(self, in_dim, out_dim, has_pos_emb=False):
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.proj = torch.nn.Sequential(
|
| 323 |
+
nn.LayerNorm(in_dim),
|
| 324 |
+
nn.Linear(in_dim, in_dim),
|
| 325 |
+
nn.GELU(),
|
| 326 |
+
nn.Linear(in_dim, out_dim),
|
| 327 |
+
nn.LayerNorm(out_dim),
|
| 328 |
+
)
|
| 329 |
+
self.has_pos_emb = has_pos_emb
|
| 330 |
+
if has_pos_emb:
|
| 331 |
+
self.emb_pos = torch.nn.Parameter(torch.zeros((1, 514, 1280)))
|
| 332 |
+
|
| 333 |
+
def forward(self, x):
|
| 334 |
+
if self.has_pos_emb:
|
| 335 |
+
x = x + self.emb_pos.to(dtype=x.dtype, device=x.device)
|
| 336 |
+
return self.proj(x)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class Head(nn.Module):
|
| 340 |
+
def __init__(self, dim: int, out_dim: int, patch_size: Tuple[int, int, int], eps: float):
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.dim = dim
|
| 343 |
+
self.patch_size = patch_size
|
| 344 |
+
self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
|
| 345 |
+
self.head = nn.Linear(dim, out_dim * math.prod(patch_size))
|
| 346 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
|
| 347 |
+
|
| 348 |
+
def forward(self, x, t_mod):
|
| 349 |
+
if len(t_mod.shape) == 3:
|
| 350 |
+
shift, scale = (
|
| 351 |
+
self.modulation.unsqueeze(0).to(dtype=t_mod.dtype, device=t_mod.device)
|
| 352 |
+
+ t_mod.unsqueeze(2)
|
| 353 |
+
).chunk(2, dim=2)
|
| 354 |
+
x = self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 355 |
+
else:
|
| 356 |
+
shift, scale = (
|
| 357 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 358 |
+
).chunk(2, dim=1)
|
| 359 |
+
x = self.head(self.norm(x) * (1 + scale) + shift)
|
| 360 |
+
return x
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class WanVideoDiT(torch.nn.Module):
|
| 364 |
+
def __init__(
|
| 365 |
+
self,
|
| 366 |
+
hidden_dim: int,
|
| 367 |
+
in_dim: int,
|
| 368 |
+
ffn_dim: int,
|
| 369 |
+
out_dim: int,
|
| 370 |
+
text_dim: int,
|
| 371 |
+
freq_dim: int,
|
| 372 |
+
eps: float,
|
| 373 |
+
patch_size: Tuple[int, int, int],
|
| 374 |
+
num_heads: int,
|
| 375 |
+
attn_head_dim: int,
|
| 376 |
+
num_layers: int,
|
| 377 |
+
has_image_input: bool,
|
| 378 |
+
has_image_pos_emb: bool = False,
|
| 379 |
+
has_ref_conv: bool = False,
|
| 380 |
+
add_control_adapter: bool = False,
|
| 381 |
+
in_dim_control_adapter: int = 24,
|
| 382 |
+
seperated_timestep: bool = False,
|
| 383 |
+
require_vae_embedding: bool = False,
|
| 384 |
+
require_clip_embedding: bool = False,
|
| 385 |
+
fuse_vae_embedding_in_latents: bool = True,
|
| 386 |
+
action_conditioned: bool = False,
|
| 387 |
+
action_dim: int = 7,
|
| 388 |
+
action_group_causal_mask_mode="causal",
|
| 389 |
+
video_attention_mask_mode: str = "bidirectional",
|
| 390 |
+
use_gradient_checkpointing: bool = False,
|
| 391 |
+
):
|
| 392 |
+
super().__init__()
|
| 393 |
+
self.hidden_dim = hidden_dim
|
| 394 |
+
self.in_dim = in_dim
|
| 395 |
+
self.freq_dim = freq_dim
|
| 396 |
+
self.patch_size = patch_size
|
| 397 |
+
self.num_heads = num_heads
|
| 398 |
+
self.attn_head_dim = attn_head_dim
|
| 399 |
+
self.seperated_timestep = seperated_timestep
|
| 400 |
+
self.require_vae_embedding = require_vae_embedding
|
| 401 |
+
self.require_clip_embedding = require_clip_embedding
|
| 402 |
+
self.fuse_vae_embedding_in_latents = fuse_vae_embedding_in_latents
|
| 403 |
+
self.video_attention_mask_mode = str(video_attention_mask_mode)
|
| 404 |
+
|
| 405 |
+
if num_heads <= 0:
|
| 406 |
+
raise ValueError(f"`num_heads` must be > 0, got {num_heads}")
|
| 407 |
+
if attn_head_dim <= 0:
|
| 408 |
+
raise ValueError(f"`attn_head_dim` must be > 0, got {attn_head_dim}")
|
| 409 |
+
if attn_head_dim % 2 != 0:
|
| 410 |
+
raise ValueError(f"`attn_head_dim` must be even for RoPE, got {attn_head_dim}")
|
| 411 |
+
|
| 412 |
+
self.action_conditioned = action_conditioned
|
| 413 |
+
self.action_dim = action_dim
|
| 414 |
+
assert has_image_input == False
|
| 415 |
+
assert require_clip_embedding == False
|
| 416 |
+
assert (
|
| 417 |
+
require_vae_embedding == False and fuse_vae_embedding_in_latents == True
|
| 418 |
+
), "Only support fusing vae embedding in latents"
|
| 419 |
+
|
| 420 |
+
self.patch_embedding = nn.Conv3d(
|
| 421 |
+
in_dim, hidden_dim, kernel_size=patch_size, stride=patch_size
|
| 422 |
+
)
|
| 423 |
+
self.text_embedding = nn.Sequential(
|
| 424 |
+
nn.Linear(text_dim, hidden_dim),
|
| 425 |
+
nn.GELU(approximate="tanh"),
|
| 426 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 427 |
+
)
|
| 428 |
+
self.time_embedding = nn.Sequential(
|
| 429 |
+
nn.Linear(freq_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim)
|
| 430 |
+
)
|
| 431 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 432 |
+
self.blocks = nn.ModuleList(
|
| 433 |
+
[
|
| 434 |
+
DiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 435 |
+
for _ in range(num_layers)
|
| 436 |
+
]
|
| 437 |
+
)
|
| 438 |
+
self.head = Head(hidden_dim, out_dim, patch_size, eps)
|
| 439 |
+
self.freqs = precompute_freqs_cis_3d(attn_head_dim)
|
| 440 |
+
if has_ref_conv:
|
| 441 |
+
self.ref_conv = nn.Conv2d(16, hidden_dim, kernel_size=(2, 2), stride=(2, 2))
|
| 442 |
+
self.has_image_pos_emb = has_image_pos_emb
|
| 443 |
+
self.has_ref_conv = has_ref_conv
|
| 444 |
+
self.control_adapter = None
|
| 445 |
+
|
| 446 |
+
if self.action_conditioned:
|
| 447 |
+
self.action_embedding = nn.Linear(action_dim, hidden_dim)
|
| 448 |
+
self.action_group_causal_mask_mode = action_group_causal_mask_mode
|
| 449 |
+
|
| 450 |
+
self.use_gradient_checkpointing = use_gradient_checkpointing
|
| 451 |
+
if self.use_gradient_checkpointing:
|
| 452 |
+
logger.info(
|
| 453 |
+
"Using gradient checkpointing for DiT blocks. This will save memory but use more computation."
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
def patchify(
|
| 457 |
+
self, x: torch.Tensor, control_camera_latents_input: Optional[torch.Tensor] = None
|
| 458 |
+
):
|
| 459 |
+
x = self.patch_embedding(x)
|
| 460 |
+
if self.control_adapter is not None and control_camera_latents_input is not None:
|
| 461 |
+
y_camera = self.control_adapter(control_camera_latents_input)
|
| 462 |
+
x = [u + v for u, v in zip(x, y_camera)]
|
| 463 |
+
x = x[0].unsqueeze(0)
|
| 464 |
+
return x
|
| 465 |
+
|
| 466 |
+
def unpatchify(self, x: torch.Tensor, grid_size: torch.Tensor):
|
| 467 |
+
return rearrange(
|
| 468 |
+
x,
|
| 469 |
+
"b (f h w) (x y z c) -> b c (f x) (h y) (w z)",
|
| 470 |
+
f=grid_size[0],
|
| 471 |
+
h=grid_size[1],
|
| 472 |
+
w=grid_size[2],
|
| 473 |
+
x=self.patch_size[0],
|
| 474 |
+
y=self.patch_size[1],
|
| 475 |
+
z=self.patch_size[2],
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
def _validate_forward_inputs(
|
| 479 |
+
self,
|
| 480 |
+
x: torch.Tensor,
|
| 481 |
+
timestep: torch.Tensor,
|
| 482 |
+
context: torch.Tensor,
|
| 483 |
+
context_mask: Optional[torch.Tensor],
|
| 484 |
+
action: Optional[torch.Tensor],
|
| 485 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 486 |
+
if x.ndim != 5:
|
| 487 |
+
raise ValueError(f"`latents` must be 5D [B, C, T, H, W], got shape {tuple(x.shape)}")
|
| 488 |
+
num_latent_frames = x.shape[2]
|
| 489 |
+
if context.ndim != 3:
|
| 490 |
+
raise ValueError(f"`context` must be 3D [B, L, D], got shape {tuple(context.shape)}")
|
| 491 |
+
if timestep.ndim != 1:
|
| 492 |
+
raise ValueError(f"`timestep` must be 1D [B] or [1], got shape {tuple(timestep.shape)}")
|
| 493 |
+
if self.action_conditioned:
|
| 494 |
+
allow_text_only_single_frame = num_latent_frames == 1 and action is None
|
| 495 |
+
if not allow_text_only_single_frame:
|
| 496 |
+
assert action is not None, "Action input is required for action-conditioned model."
|
| 497 |
+
if action.ndim != 3:
|
| 498 |
+
raise ValueError(
|
| 499 |
+
f"`action` must be 3D [B, action_horizon, action_dim], got shape {tuple(action.shape)}"
|
| 500 |
+
)
|
| 501 |
+
if action.shape[2] != self.action_dim:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
f"`action` last dimension must be {self.action_dim}, got {action.shape[2]}"
|
| 504 |
+
)
|
| 505 |
+
if num_latent_frames <= 1:
|
| 506 |
+
raise ValueError(
|
| 507 |
+
f"video length must be > 1 for action-conditioned model, got {num_latent_frames}"
|
| 508 |
+
)
|
| 509 |
+
if action.shape[1] % (num_latent_frames - 1) != 0:
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"action horizon must be divisible by (num_latent_frames - 1), got action_horizon={action.shape[1]}"
|
| 512 |
+
)
|
| 513 |
+
if context_mask is None:
|
| 514 |
+
context_mask = torch.ones(
|
| 515 |
+
(context.shape[0], context.shape[1]), dtype=torch.bool, device=context.device
|
| 516 |
+
)
|
| 517 |
+
else:
|
| 518 |
+
if context_mask.ndim != 2:
|
| 519 |
+
raise ValueError(
|
| 520 |
+
f"`context_mask` must be 2D [B, L], got shape {tuple(context_mask.shape)}"
|
| 521 |
+
)
|
| 522 |
+
if (
|
| 523 |
+
context_mask.shape[0] != context.shape[0]
|
| 524 |
+
or context_mask.shape[1] != context.shape[1]
|
| 525 |
+
):
|
| 526 |
+
raise ValueError(
|
| 527 |
+
f"`context_mask` shape must match `context` shape [B, L], got {tuple(context_mask.shape)} vs {tuple(context.shape)}"
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
batch_size = x.shape[0]
|
| 531 |
+
if batch_size != context.shape[0]:
|
| 532 |
+
if not self.training and batch_size == 1:
|
| 533 |
+
x = x.expand(context.shape[0], -1, -1, -1, -1)
|
| 534 |
+
batch_size = context.shape[0]
|
| 535 |
+
else:
|
| 536 |
+
raise ValueError(
|
| 537 |
+
f"Batch mismatch between latents and context: {batch_size} vs {context.shape[0]}."
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
if timestep.shape[0] not in (1, batch_size):
|
| 541 |
+
raise ValueError(
|
| 542 |
+
f"`timestep` length must be 1 or batch_size({batch_size}), got {timestep.shape[0]}"
|
| 543 |
+
)
|
| 544 |
+
if timestep.shape[0] == 1 and batch_size > 1:
|
| 545 |
+
assert not self.training, "During training, timestep length must match batch_size."
|
| 546 |
+
timestep = timestep.expand(batch_size)
|
| 547 |
+
return x, timestep, context_mask
|
| 548 |
+
|
| 549 |
+
def build_video_to_video_mask(
|
| 550 |
+
self,
|
| 551 |
+
video_seq_len: int,
|
| 552 |
+
video_tokens_per_frame: int,
|
| 553 |
+
device: torch.device,
|
| 554 |
+
) -> torch.Tensor:
|
| 555 |
+
if video_seq_len <= 0:
|
| 556 |
+
raise ValueError(f"`video_seq_len` must be positive, got {video_seq_len}")
|
| 557 |
+
if video_tokens_per_frame <= 0:
|
| 558 |
+
raise ValueError(
|
| 559 |
+
f"`video_tokens_per_frame` must be positive, got {video_tokens_per_frame}"
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if self.video_attention_mask_mode == "bidirectional":
|
| 563 |
+
return torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 564 |
+
|
| 565 |
+
if self.video_attention_mask_mode == "per_frame_causal":
|
| 566 |
+
if video_seq_len % video_tokens_per_frame != 0:
|
| 567 |
+
raise ValueError(
|
| 568 |
+
"`video_seq_len` must be divisible by `video_tokens_per_frame` in `per_frame_causal` mode, "
|
| 569 |
+
f"got {video_seq_len} and {video_tokens_per_frame}"
|
| 570 |
+
)
|
| 571 |
+
num_video_frames = video_seq_len // video_tokens_per_frame
|
| 572 |
+
frame_causal = torch.tril(
|
| 573 |
+
torch.ones((num_video_frames, num_video_frames), dtype=torch.bool, device=device)
|
| 574 |
+
)
|
| 575 |
+
return frame_causal.repeat_interleave(video_tokens_per_frame, dim=0).repeat_interleave(
|
| 576 |
+
video_tokens_per_frame, dim=1
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
if self.video_attention_mask_mode == "first_frame_causal":
|
| 580 |
+
video_mask = torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 581 |
+
first_frame_tokens = min(video_tokens_per_frame, video_seq_len)
|
| 582 |
+
video_mask[:first_frame_tokens, first_frame_tokens:] = False
|
| 583 |
+
return video_mask
|
| 584 |
+
|
| 585 |
+
raise ValueError(f"Unsupported video attention mask mode: {self.video_attention_mask_mode}")
|
| 586 |
+
|
| 587 |
+
def pre_dit(
|
| 588 |
+
self,
|
| 589 |
+
x: torch.Tensor,
|
| 590 |
+
timestep: torch.Tensor,
|
| 591 |
+
context: torch.Tensor,
|
| 592 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 593 |
+
action: Optional[torch.Tensor] = None,
|
| 594 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 595 |
+
control_camera_latents_input: Optional[torch.Tensor] = None,
|
| 596 |
+
) -> Dict[str, Any]:
|
| 597 |
+
x, timestep, context_mask = self._validate_forward_inputs(
|
| 598 |
+
x=x,
|
| 599 |
+
timestep=timestep,
|
| 600 |
+
context=context,
|
| 601 |
+
context_mask=context_mask,
|
| 602 |
+
action=action,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
batch_size = x.shape[0]
|
| 606 |
+
patch_h = int(self.patch_size[1])
|
| 607 |
+
patch_w = int(self.patch_size[2])
|
| 608 |
+
if x.shape[3] % patch_h != 0 or x.shape[4] % patch_w != 0:
|
| 609 |
+
raise ValueError(
|
| 610 |
+
"Latent spatial shape must be divisible by DiT patch size, "
|
| 611 |
+
f"got HxW=({x.shape[3]}, {x.shape[4]}), patch=({patch_h}, {patch_w})"
|
| 612 |
+
)
|
| 613 |
+
tokens_per_frame = (x.shape[3] // patch_h) * (x.shape[4] // patch_w)
|
| 614 |
+
|
| 615 |
+
if self.seperated_timestep and fuse_vae_embedding_in_latents:
|
| 616 |
+
if not hasattr(self, "patch_size") or len(self.patch_size) < 3:
|
| 617 |
+
raise ValueError(f"Invalid dit.patch_size: {getattr(self, 'patch_size', None)}")
|
| 618 |
+
|
| 619 |
+
token_timesteps = torch.ones(
|
| 620 |
+
(batch_size, x.shape[2], tokens_per_frame),
|
| 621 |
+
dtype=timestep.dtype,
|
| 622 |
+
device=timestep.device,
|
| 623 |
+
) * timestep.view(batch_size, 1, 1)
|
| 624 |
+
token_timesteps[:, 0, :] = 0
|
| 625 |
+
token_timesteps = token_timesteps.reshape(batch_size, -1)
|
| 626 |
+
token_t_emb = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1))
|
| 627 |
+
t = self.time_embedding(token_t_emb).reshape(batch_size, -1, self.hidden_dim)
|
| 628 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 629 |
+
else:
|
| 630 |
+
raise NotImplementedError(
|
| 631 |
+
"Only support seperated_timestep with fuse_vae_embedding_in_latents for now."
|
| 632 |
+
)
|
| 633 |
+
t = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, timestep))
|
| 634 |
+
t_mod = self.time_projection(t).unflatten(1, (6, self.hidden_dim))
|
| 635 |
+
x = self.patchify(x, control_camera_latents_input=control_camera_latents_input)
|
| 636 |
+
f, h, w = x.shape[2:]
|
| 637 |
+
|
| 638 |
+
context = self.text_embedding(context) # (B, L, dim)
|
| 639 |
+
context_len = context.shape[1]
|
| 640 |
+
if self.action_conditioned and action is not None:
|
| 641 |
+
action_len = action.shape[1]
|
| 642 |
+
action_emb = self.action_embedding(action) # (B, action_len, dim)
|
| 643 |
+
action_pos_embed = sinusoidal_embedding_1d(
|
| 644 |
+
self.hidden_dim, torch.arange(action_len, device=action_emb.device)
|
| 645 |
+
) # (action_len, dim)
|
| 646 |
+
action_emb = action_emb + action_pos_embed.unsqueeze(0) # (B, action_len, dim)
|
| 647 |
+
context = torch.cat([context, action_emb], dim=1) # (B, context_len + action_len, dim)
|
| 648 |
+
|
| 649 |
+
# new mask
|
| 650 |
+
num_temporal_groups = f - 1 # first latent frame do not attend to actions
|
| 651 |
+
if num_temporal_groups <= 0:
|
| 652 |
+
raise ValueError(
|
| 653 |
+
"Action-conditioned context mask requires at least 2 latent frames when `action` is provided."
|
| 654 |
+
)
|
| 655 |
+
assert (
|
| 656 |
+
action_emb.shape[1] % num_temporal_groups == 0
|
| 657 |
+
), f"Action embedding length {action_emb.shape[1]} must be divisible by number of temporal groups {num_temporal_groups}"
|
| 658 |
+
# Each latent frame (from the 2nd one) attends to the corresponding group of action tokens
|
| 659 |
+
action_group_mask = create_group_causal_attn_mask(
|
| 660 |
+
num_temporal_groups=num_temporal_groups,
|
| 661 |
+
num_query_per_group=tokens_per_frame,
|
| 662 |
+
num_key_per_group=action_len // num_temporal_groups,
|
| 663 |
+
mode=self.action_group_causal_mask_mode,
|
| 664 |
+
).to(
|
| 665 |
+
context.device
|
| 666 |
+
) # ((f-1)*tokens_per_frame, action_len)
|
| 667 |
+
|
| 668 |
+
seq_len = f * h * w # query length
|
| 669 |
+
final_context_mask = torch.zeros(
|
| 670 |
+
(batch_size, seq_len, context.shape[1]), dtype=torch.bool, device=context.device
|
| 671 |
+
) # (B, seq_len, L + action_len)
|
| 672 |
+
# all latent frames attend to text tokens
|
| 673 |
+
final_context_mask[:, :, :context_len] = context_mask.unsqueeze(1).expand(
|
| 674 |
+
-1, seq_len, -1
|
| 675 |
+
) # (B, seq_len, L)
|
| 676 |
+
# latent frames from the 2nd one attend to action tokens
|
| 677 |
+
final_context_mask[:, tokens_per_frame:, context_len:] = action_group_mask.unsqueeze(
|
| 678 |
+
0
|
| 679 |
+
).expand(
|
| 680 |
+
batch_size, -1, -1
|
| 681 |
+
) # (B, seq_len, action_len)
|
| 682 |
+
context_mask = final_context_mask
|
| 683 |
+
elif self.action_conditioned and action is None:
|
| 684 |
+
if f != 1:
|
| 685 |
+
raise ValueError(
|
| 686 |
+
"Action-conditioned model requires `action` unless running single-frame text-only mode with num_latent_frames=1."
|
| 687 |
+
)
|
| 688 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 689 |
+
else:
|
| 690 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 691 |
+
|
| 692 |
+
x_tokens = rearrange(x, "b c f h w -> b (f h w) c").contiguous()
|
| 693 |
+
|
| 694 |
+
freqs = (
|
| 695 |
+
torch.cat(
|
| 696 |
+
[
|
| 697 |
+
self.freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
|
| 698 |
+
self.freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
|
| 699 |
+
self.freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1),
|
| 700 |
+
],
|
| 701 |
+
dim=-1,
|
| 702 |
+
)
|
| 703 |
+
.reshape(f * h * w, 1, -1)
|
| 704 |
+
.to(x_tokens.device)
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
return {
|
| 708 |
+
"tokens": x_tokens,
|
| 709 |
+
"freqs": freqs,
|
| 710 |
+
"t": t,
|
| 711 |
+
"t_mod": t_mod,
|
| 712 |
+
"context": context,
|
| 713 |
+
"context_mask": context_mask,
|
| 714 |
+
"meta": {
|
| 715 |
+
"grid_size": (f, h, w),
|
| 716 |
+
"tokens_per_frame": tokens_per_frame,
|
| 717 |
+
"batch_size": batch_size,
|
| 718 |
+
},
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
def post_dit(self, x_tokens: torch.Tensor, pre_state: Dict[str, Any]) -> torch.Tensor:
|
| 722 |
+
f, h, w = pre_state["meta"]["grid_size"]
|
| 723 |
+
x = self.head(x_tokens, pre_state["t"])
|
| 724 |
+
x = self.unpatchify(x, (f, h, w))
|
| 725 |
+
return x
|
| 726 |
+
|
| 727 |
+
def forward(
|
| 728 |
+
self,
|
| 729 |
+
x: torch.Tensor,
|
| 730 |
+
timestep: torch.Tensor,
|
| 731 |
+
context: torch.Tensor,
|
| 732 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 733 |
+
action: Optional[torch.Tensor] = None,
|
| 734 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 735 |
+
):
|
| 736 |
+
pre_state = self.pre_dit(
|
| 737 |
+
x=x,
|
| 738 |
+
timestep=timestep,
|
| 739 |
+
context=context,
|
| 740 |
+
context_mask=context_mask,
|
| 741 |
+
action=action,
|
| 742 |
+
fuse_vae_embedding_in_latents=fuse_vae_embedding_in_latents,
|
| 743 |
+
)
|
| 744 |
+
x_tokens = pre_state["tokens"]
|
| 745 |
+
context_emb = pre_state["context"]
|
| 746 |
+
t_mod = pre_state["t_mod"]
|
| 747 |
+
freqs = pre_state["freqs"]
|
| 748 |
+
context_attn_mask = pre_state["context_mask"]
|
| 749 |
+
self_attn_mask = (
|
| 750 |
+
self.build_video_to_video_mask(
|
| 751 |
+
video_seq_len=x_tokens.shape[1],
|
| 752 |
+
video_tokens_per_frame=int(pre_state["meta"]["tokens_per_frame"]),
|
| 753 |
+
device=x_tokens.device,
|
| 754 |
+
)
|
| 755 |
+
if self.video_attention_mask_mode != "bidirectional"
|
| 756 |
+
else None
|
| 757 |
+
) # special rule for faster speed
|
| 758 |
+
|
| 759 |
+
for block in self.blocks:
|
| 760 |
+
if self.use_gradient_checkpointing:
|
| 761 |
+
x_tokens = gradient_checkpoint_forward(
|
| 762 |
+
block,
|
| 763 |
+
self.use_gradient_checkpointing,
|
| 764 |
+
x_tokens,
|
| 765 |
+
context_emb,
|
| 766 |
+
t_mod,
|
| 767 |
+
freqs,
|
| 768 |
+
context_mask=context_attn_mask,
|
| 769 |
+
self_attn_mask=self_attn_mask,
|
| 770 |
+
)
|
| 771 |
+
else:
|
| 772 |
+
x_tokens = block(
|
| 773 |
+
x_tokens,
|
| 774 |
+
context_emb,
|
| 775 |
+
t_mod,
|
| 776 |
+
freqs,
|
| 777 |
+
context_mask=context_attn_mask,
|
| 778 |
+
self_attn_mask=self_attn_mask,
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
return self.post_dit(x_tokens, pre_state)
|
tools/model_code/recorded/coupling/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/coupling/hr_mot.py
ADDED
|
@@ -0,0 +1,1385 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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&R two-expert flow model with independent demonstration/coupling ablations.
|
| 2 |
+
|
| 3 |
+
The adapted robot-only FastWAM control uses no text or cross-attention.
|
| 4 |
+
Human video/motion are clean self-attention conditions in the carrier variant.
|
| 5 |
+
future_video_action_coupling controls ONLY the two future-stream cross edges.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from dataclasses import asdict, dataclass, field
|
| 11 |
+
import math
|
| 12 |
+
from typing import Optional, Sequence
|
| 13 |
+
|
| 14 |
+
import torch
|
| 15 |
+
from einops import rearrange
|
| 16 |
+
from torch import nn
|
| 17 |
+
from torch.nn import functional as F
|
| 18 |
+
|
| 19 |
+
from .wan22.mot import MoT
|
| 20 |
+
from .wan22.schedulers.scheduler_continuous import WanContinuousFlowMatchScheduler
|
| 21 |
+
from .wan22.wan_video_dit import (
|
| 22 |
+
GateModule,
|
| 23 |
+
SelfAttention,
|
| 24 |
+
precompute_freqs_cis,
|
| 25 |
+
precompute_freqs_cis_3d,
|
| 26 |
+
sinusoidal_embedding_1d,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
ROLE_ROBOT_CURRENT = 0
|
| 30 |
+
ROLE_HUMAN_CONTEXT = 1
|
| 31 |
+
ROLE_ROBOT_FUTURE = 2
|
| 32 |
+
NUM_ROLES = 3
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
@dataclass(frozen=True)
|
| 36 |
+
class HRMoTConfig:
|
| 37 |
+
"""Shapes for the ~0.6B H&R MoT. Only trainable modules are counted."""
|
| 38 |
+
|
| 39 |
+
# Latent geometry, fixed by the frozen Wan2.2 VAE and the chosen image size.
|
| 40 |
+
latent_channels: int = 48
|
| 41 |
+
latent_height: int = 14
|
| 42 |
+
latent_width: int = 24
|
| 43 |
+
patch_height: int = 2
|
| 44 |
+
patch_width: int = 2
|
| 45 |
+
|
| 46 |
+
# Ordered RGB segment length handed to the VAE, per stream. The Wan2.2 VAE
|
| 47 |
+
# folds each run of 4 frames into one latent step, so T=9 -> 3 latent steps:
|
| 48 |
+
# z0 <- f0, z1 <- f1..4, z2 <- f5..8. The robot's z0 is the clean current
|
| 49 |
+
# condition; z1.. are what gets denoised.
|
| 50 |
+
num_rgb_frames: int = 9
|
| 51 |
+
vae_temporal_factor: int = 4
|
| 52 |
+
|
| 53 |
+
# Control steps between consecutive video frames. FastWAM keeps every 4th of
|
| 54 |
+
# 33 control steps as a video frame, so 9 frames span 32 steps (1.09 s at the
|
| 55 |
+
# data's 29.4 fps). Reading 9 contiguous frames instead spans 8 steps = 0.27 s,
|
| 56 |
+
# in which almost nothing happens: the gripper changes in 6.4% of 8-step
|
| 57 |
+
# windows versus 25.4% of 32-step ones.
|
| 58 |
+
frame_stride: int = 4
|
| 59 |
+
|
| 60 |
+
# Contiguous robot action steps predicted per sample, covering the video span.
|
| 61 |
+
action_horizon: int = 32
|
| 62 |
+
|
| 63 |
+
action_dim: int = 7
|
| 64 |
+
|
| 65 |
+
# Clean anchors for the action expert. Without them it predicts an absolute
|
| 66 |
+
# end-effector pose (x spans 103..346 mm) with no idea where the arm is now
|
| 67 |
+
# and no aligned human counterpart, having to infer both from pixels through
|
| 68 |
+
# the shared attention. Measured on the anchorless baseline, removing the
|
| 69 |
+
# human cost the action branch +362% -- far more than it cost video, the
|
| 70 |
+
# signature of an unanchored pathway.
|
| 71 |
+
# robot_state_f0 [7] where the arm is at t0
|
| 72 |
+
# human_action t1..tH [action_horizon, 84] raw wrist frame + hand coords
|
| 73 |
+
# False reproduces the anchorless baseline.
|
| 74 |
+
use_state_context: bool = True
|
| 75 |
+
# These two switches preserve the action-condition slots and every module,
|
| 76 |
+
# but hard-mask the corresponding sources. They are therefore suitable for
|
| 77 |
+
# same-size carrier ablations, unlike `use_state_context=False`.
|
| 78 |
+
use_robot_state_context: bool = True
|
| 79 |
+
# Keep the action-side robot-current anchor while hard-masking every mapped
|
| 80 |
+
# human-motion token. This defines the same-size human-video-only control:
|
| 81 |
+
# all modules and parameters remain present, but no 84-D human signal is a
|
| 82 |
+
# readable key/value for any prediction query.
|
| 83 |
+
use_human_motion_context: bool = True
|
| 84 |
+
# Hard-mask every human video latent while retaining the slots, projections,
|
| 85 |
+
# role parameters and sequence length for a strict robot-video-only control.
|
| 86 |
+
use_human_video_context: bool = True
|
| 87 |
+
human_action_dim: int = 84
|
| 88 |
+
|
| 89 |
+
# Native robot-only FastWAM sequence. Human slots and human projection
|
| 90 |
+
# modules are physically absent rather than retained as masked carriers.
|
| 91 |
+
# The robot-current 7-D state is retained as the proprioceptive condition.
|
| 92 |
+
direct_fastwam_robot_only: bool = False
|
| 93 |
+
future_video_action_coupling: bool = True
|
| 94 |
+
|
| 95 |
+
# Whether the human z0 latent step may also be dropped. With it pinned on, the
|
| 96 |
+
# "no human context at all" path is never trained, its availability embedding
|
| 97 |
+
# row never receives gradient, and any measurement of that condition is out of
|
| 98 |
+
# distribution. Pinning it also lets the model lean entirely on the
|
| 99 |
+
# same-moment cross-embodiment correspondence instead of reading the
|
| 100 |
+
# demonstration. Droppable by default, as part of the same 10% regularizer.
|
| 101 |
+
droppable_human_current: bool = True
|
| 102 |
+
|
| 103 |
+
# Shared across experts -- MoT mixes attention, so head geometry must match.
|
| 104 |
+
num_layers: int = 22
|
| 105 |
+
num_heads: int = 10
|
| 106 |
+
attn_head_dim: int = 128
|
| 107 |
+
|
| 108 |
+
video_hidden_dim: int = 1280
|
| 109 |
+
video_ffn_dim: int = 5120
|
| 110 |
+
action_hidden_dim: int = 640
|
| 111 |
+
action_ffn_dim: int = 2560
|
| 112 |
+
|
| 113 |
+
freq_dim: int = 256
|
| 114 |
+
max_rope_position: int = 1024
|
| 115 |
+
eps: float = 1e-6
|
| 116 |
+
|
| 117 |
+
gradient_checkpointing: bool = True
|
| 118 |
+
|
| 119 |
+
# Attention ablation. "softmax" is the original quadratic mixed
|
| 120 |
+
# self-attention. "linear" keeps the same Q/K/V/O projections, RoPE,
|
| 121 |
+
# experts, tokens and visibility semantics, but replaces every mixed
|
| 122 |
+
# attention kernel with normalized ELU+1 linear attention.
|
| 123 |
+
mixed_attention_type: str = "softmax"
|
| 124 |
+
|
| 125 |
+
# Human-condition availability. Robot z0 is never masked. Human z0 is
|
| 126 |
+
# droppable by default together with both human-future latent steps, yielding
|
| 127 |
+
# 2^3 = 8 patterns; --pin-human-current restores the legacy 4-pattern contract.
|
| 128 |
+
#
|
| 129 |
+
# This is a *regularizer*, not a curriculum: the point is that the model can
|
| 130 |
+
# still be asked for fewer human steps at inference, not that it should train
|
| 131 |
+
# mostly on degraded context. Dropping context on half the samples actively
|
| 132 |
+
# weakens the human pathway, which is the pathway under study. Default is 0.9
|
| 133 |
+
# full context, i.e. a 10% dropout rate.
|
| 134 |
+
full_human_context_prob: float = 0.9
|
| 135 |
+
# None preserves the legacy sampler. An explicit mass drops all human
|
| 136 |
+
# video and motion; partial patterns share the remaining mass uniformly.
|
| 137 |
+
none_human_context_prob: Optional[float] = None
|
| 138 |
+
|
| 139 |
+
# Flow-matching schedule (FastWAM defaults).
|
| 140 |
+
video_train_shift: float = 5.0
|
| 141 |
+
video_infer_shift: float = 5.0
|
| 142 |
+
action_train_shift: float = 5.0
|
| 143 |
+
action_infer_shift: float = 5.0
|
| 144 |
+
num_train_timesteps: int = 1000
|
| 145 |
+
|
| 146 |
+
# The video loss averages over ~250k scalars per sample and the action loss
|
| 147 |
+
# over ~21. Summing the two raw means gives the video term a far smaller and
|
| 148 |
+
# noisier per-element gradient, which is one of the failures the previous run
|
| 149 |
+
# hit. These weights are the knob for that balance.
|
| 150 |
+
loss_lambda_video: float = 1.0
|
| 151 |
+
loss_lambda_action: float = 1.0
|
| 152 |
+
|
| 153 |
+
def validate(self) -> None:
|
| 154 |
+
if not 0.0 <= self.full_human_context_prob <= 1.0:
|
| 155 |
+
raise ValueError("full_human_context_prob must be in [0, 1]")
|
| 156 |
+
if self.none_human_context_prob is not None:
|
| 157 |
+
if not self.droppable_human_current:
|
| 158 |
+
raise ValueError("explicit no-context probability requires droppable human z0")
|
| 159 |
+
if not 0.0 <= self.none_human_context_prob <= 1.0:
|
| 160 |
+
raise ValueError("none_human_context_prob must be in [0, 1]")
|
| 161 |
+
if self.full_human_context_prob + self.none_human_context_prob > 1.0:
|
| 162 |
+
raise ValueError("full and no-context probabilities must sum to at most one")
|
| 163 |
+
if self.direct_fastwam_robot_only:
|
| 164 |
+
if self.use_human_video_context or self.use_human_motion_context:
|
| 165 |
+
raise ValueError(
|
| 166 |
+
"direct_fastwam_robot_only requires both human context sources off"
|
| 167 |
+
)
|
| 168 |
+
if not self.use_state_context or not self.use_robot_state_context:
|
| 169 |
+
raise ValueError(
|
| 170 |
+
"direct_fastwam_robot_only requires the robot-current state condition"
|
| 171 |
+
)
|
| 172 |
+
if self.mixed_attention_type != "softmax":
|
| 173 |
+
raise ValueError("direct FastWAM uses the original softmax attention kernel")
|
| 174 |
+
if self.use_state_context and self.human_action_dim != 84:
|
| 175 |
+
raise ValueError(
|
| 176 |
+
"raw H&R human motion must be 84-D "
|
| 177 |
+
"(transformed_hand_frames + transformed_hand_coords); "
|
| 178 |
+
f"got human_action_dim={self.human_action_dim}"
|
| 179 |
+
)
|
| 180 |
+
if self.frame_stride < 1:
|
| 181 |
+
raise ValueError(f"frame_stride must be >= 1, got {self.frame_stride}")
|
| 182 |
+
if self.action_horizon != self.video_span:
|
| 183 |
+
raise ValueError(
|
| 184 |
+
"action_horizon must equal the video span "
|
| 185 |
+
f"(num_rgb_frames-1)*frame_stride = {self.video_span}, "
|
| 186 |
+
f"got {self.action_horizon}"
|
| 187 |
+
)
|
| 188 |
+
if self.latent_height % self.patch_height or self.latent_width % self.patch_width:
|
| 189 |
+
raise ValueError(
|
| 190 |
+
f"latent size ({self.latent_height}, {self.latent_width}) must be divisible "
|
| 191 |
+
f"by DiT patch ({self.patch_height}, {self.patch_width})"
|
| 192 |
+
)
|
| 193 |
+
if self.num_rgb_frames < 5 or (self.num_rgb_frames - 1) % self.vae_temporal_factor:
|
| 194 |
+
raise ValueError(
|
| 195 |
+
"num_rgb_frames must be >=5 with (T-1) % "
|
| 196 |
+
f"{self.vae_temporal_factor} == 0, got {self.num_rgb_frames}"
|
| 197 |
+
)
|
| 198 |
+
# Guard the indices actually used, not the frame count: the video stream
|
| 199 |
+
# indexes `frame_rope_positions` and the action stream indexes up to
|
| 200 |
+
# num_action_tokens, either of which can exceed num_rgb_frames.
|
| 201 |
+
highest = max((*self.frame_rope_positions, self.num_action_tokens))
|
| 202 |
+
if highest >= self.max_rope_position:
|
| 203 |
+
raise ValueError(
|
| 204 |
+
f"RoPE position {highest} exceeds the precomputed table "
|
| 205 |
+
f"({self.max_rope_position})"
|
| 206 |
+
)
|
| 207 |
+
# rope_apply consumes head_dim/2 complex frequencies; the 3D split must
|
| 208 |
+
# add back up to exactly that or the rotation silently misaligns.
|
| 209 |
+
head_dim = self.attn_head_dim
|
| 210 |
+
f_dim = head_dim - 2 * (head_dim // 3)
|
| 211 |
+
complex_total = (f_dim // 2) + 2 * ((head_dim // 3) // 2)
|
| 212 |
+
if complex_total != head_dim // 2:
|
| 213 |
+
raise ValueError(
|
| 214 |
+
f"attn_head_dim={head_dim} does not split evenly into 3D RoPE "
|
| 215 |
+
f"({complex_total} complex frequencies, need {head_dim // 2}); "
|
| 216 |
+
"use a value such as 96 or 128"
|
| 217 |
+
)
|
| 218 |
+
for name, dim in (
|
| 219 |
+
("video_hidden_dim", self.video_hidden_dim),
|
| 220 |
+
("action_hidden_dim", self.action_hidden_dim),
|
| 221 |
+
):
|
| 222 |
+
if dim <= 0:
|
| 223 |
+
raise ValueError(f"{name} must be positive")
|
| 224 |
+
if self.num_layers <= 0 or self.num_heads <= 0:
|
| 225 |
+
raise ValueError("num_layers and num_heads must be positive")
|
| 226 |
+
if self.mixed_attention_type not in {"softmax", "linear"}:
|
| 227 |
+
raise ValueError(
|
| 228 |
+
"mixed_attention_type must be 'softmax' or 'linear', got "
|
| 229 |
+
f"{self.mixed_attention_type!r}"
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
@property
|
| 233 |
+
def num_latent_steps(self) -> int:
|
| 234 |
+
"""1 + (T-1)/4 per stream."""
|
| 235 |
+
return 1 + (self.num_rgb_frames - 1) // self.vae_temporal_factor
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def num_horizons(self) -> int:
|
| 239 |
+
"""Predicted robot latent steps: everything after the clean z0."""
|
| 240 |
+
return self.num_latent_steps - 1
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def video_span(self) -> int:
|
| 244 |
+
"""Control steps covered by the video window."""
|
| 245 |
+
return (self.num_rgb_frames - 1) * self.frame_stride
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def num_action_tokens(self) -> int:
|
| 249 |
+
"""One robot state per predicted control step."""
|
| 250 |
+
return self.action_horizon
|
| 251 |
+
|
| 252 |
+
@property
|
| 253 |
+
def latent_step_frames(self) -> tuple[int, ...]:
|
| 254 |
+
"""Last CONTROL STEP each latent step covers.
|
| 255 |
+
|
| 256 |
+
The VAE folds 4 video frames into one latent step and each video frame is
|
| 257 |
+
`frame_stride` control steps apart, so a latent step spans
|
| 258 |
+
`4 * frame_stride` control steps: with stride 4 that is 0 / 16 / 32.
|
| 259 |
+
Expressing this in control steps rather than video-frame index is what
|
| 260 |
+
lets a predicted robot latent step share a RoPE position with the human
|
| 261 |
+
latent step covering the same real time.
|
| 262 |
+
"""
|
| 263 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 264 |
+
return (0, *((index + 1) * span for index in range(self.num_latent_steps - 1)))
|
| 265 |
+
|
| 266 |
+
@property
|
| 267 |
+
def tokens_per_frame(self) -> int:
|
| 268 |
+
return (self.latent_height // self.patch_height) * (self.latent_width // self.patch_width)
|
| 269 |
+
|
| 270 |
+
@property
|
| 271 |
+
def num_action_condition_tokens(self) -> int:
|
| 272 |
+
"""Robot state at t0 plus one human-motion token per control step."""
|
| 273 |
+
if self.direct_fastwam_robot_only:
|
| 274 |
+
return 1
|
| 275 |
+
return (1 + self.num_action_tokens) if self.use_state_context else 0
|
| 276 |
+
|
| 277 |
+
@property
|
| 278 |
+
def num_action_sequence(self) -> int:
|
| 279 |
+
return self.num_action_condition_tokens + self.num_action_tokens
|
| 280 |
+
|
| 281 |
+
@property
|
| 282 |
+
def action_rope_positions(self) -> tuple[int, ...]:
|
| 283 |
+
"""Control-step index per action token, condition block first.
|
| 284 |
+
|
| 285 |
+
A predicted state at step i shares its RoPE position with the human motion
|
| 286 |
+
at step i, mirroring how a predicted robot latent step shares a position
|
| 287 |
+
with the human latent step covering the same real time.
|
| 288 |
+
"""
|
| 289 |
+
future = tuple(range(1, self.num_action_tokens + 1))
|
| 290 |
+
if self.direct_fastwam_robot_only:
|
| 291 |
+
return (0, *future)
|
| 292 |
+
if not self.use_state_context:
|
| 293 |
+
return future
|
| 294 |
+
return (0, *future, *future)
|
| 295 |
+
|
| 296 |
+
def human_action_latent_step(self) -> tuple[int, ...]:
|
| 297 |
+
"""Which human latent step each human-motion token follows for availability.
|
| 298 |
+
|
| 299 |
+
Control steps 1..16 fall inside latent step 1, 17..32 inside step 2, so a
|
| 300 |
+
masked human latent step masks the action tokens covering the same real
|
| 301 |
+
time. Clamped in case the horizon ever overruns the video span.
|
| 302 |
+
"""
|
| 303 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 304 |
+
last = self.num_latent_steps - 1
|
| 305 |
+
return tuple(min(1 + (index // span), last) for index in range(self.num_action_tokens))
|
| 306 |
+
|
| 307 |
+
@property
|
| 308 |
+
def num_condition_frames(self) -> int:
|
| 309 |
+
"""robot z0 + every human latent step."""
|
| 310 |
+
if self.direct_fastwam_robot_only:
|
| 311 |
+
return 1
|
| 312 |
+
return 1 + self.num_latent_steps
|
| 313 |
+
|
| 314 |
+
@property
|
| 315 |
+
def num_video_frames(self) -> int:
|
| 316 |
+
"""condition slots + predicted robot latent steps."""
|
| 317 |
+
if self.direct_fastwam_robot_only:
|
| 318 |
+
return self.num_latent_steps
|
| 319 |
+
return self.num_condition_frames + self.num_horizons
|
| 320 |
+
|
| 321 |
+
@property
|
| 322 |
+
def num_condition_tokens(self) -> int:
|
| 323 |
+
return self.num_condition_frames * self.tokens_per_frame
|
| 324 |
+
|
| 325 |
+
@property
|
| 326 |
+
def num_video_tokens(self) -> int:
|
| 327 |
+
return self.num_video_frames * self.tokens_per_frame
|
| 328 |
+
|
| 329 |
+
@property
|
| 330 |
+
def frame_rope_positions(self) -> tuple[int, ...]:
|
| 331 |
+
"""Temporal RoPE index per latent-step slot, in RGB-frame units.
|
| 332 |
+
|
| 333 |
+
A predicted robot latent step shares its temporal position with the human
|
| 334 |
+
latent step covering the same frames; the role embedding is what separates
|
| 335 |
+
them. That alignment is the point.
|
| 336 |
+
"""
|
| 337 |
+
steps = self.latent_step_frames
|
| 338 |
+
if self.direct_fastwam_robot_only:
|
| 339 |
+
return steps
|
| 340 |
+
return (steps[0], *steps, *steps[1:])
|
| 341 |
+
|
| 342 |
+
@property
|
| 343 |
+
def frame_roles(self) -> tuple[int, ...]:
|
| 344 |
+
if self.direct_fastwam_robot_only:
|
| 345 |
+
return (
|
| 346 |
+
ROLE_ROBOT_CURRENT,
|
| 347 |
+
*([ROLE_ROBOT_FUTURE] * self.num_horizons),
|
| 348 |
+
)
|
| 349 |
+
return (
|
| 350 |
+
ROLE_ROBOT_CURRENT,
|
| 351 |
+
*([ROLE_HUMAN_CONTEXT] * self.num_latent_steps),
|
| 352 |
+
*([ROLE_ROBOT_FUTURE] * self.num_horizons),
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
def to_dict(self) -> dict[str, object]:
|
| 356 |
+
return asdict(self)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def build_condition_prediction_mask(
|
| 360 |
+
*,
|
| 361 |
+
num_condition_tokens: int,
|
| 362 |
+
num_video_tokens: int,
|
| 363 |
+
num_action_tokens: int,
|
| 364 |
+
device: torch.device | None = None,
|
| 365 |
+
) -> torch.Tensor:
|
| 366 |
+
"""Visibility over the concatenated [video, action] MoT sequence.
|
| 367 |
+
|
| 368 |
+
Condition queries (robot current + human ground truth) see condition keys
|
| 369 |
+
only, so the clean context never leaks information from the noisy targets.
|
| 370 |
+
Prediction queries (robot future video + robot future action) see everything.
|
| 371 |
+
"""
|
| 372 |
+
|
| 373 |
+
if not 0 < num_condition_tokens <= num_video_tokens:
|
| 374 |
+
raise ValueError(
|
| 375 |
+
f"num_condition_tokens={num_condition_tokens} must be in (0, {num_video_tokens}]"
|
| 376 |
+
)
|
| 377 |
+
if num_action_tokens <= 0:
|
| 378 |
+
raise ValueError("num_action_tokens must be positive")
|
| 379 |
+
total = num_video_tokens + num_action_tokens
|
| 380 |
+
mask = torch.zeros((total, total), dtype=torch.bool, device=device)
|
| 381 |
+
mask[:num_condition_tokens, :num_condition_tokens] = True
|
| 382 |
+
mask[num_condition_tokens:, :] = True
|
| 383 |
+
return mask
|
| 384 |
+
|
| 385 |
+
|
| 386 |
+
def build_availability_attention_mask(
|
| 387 |
+
config: "HRMoTConfig",
|
| 388 |
+
human_mask: torch.Tensor,
|
| 389 |
+
*,
|
| 390 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 391 |
+
device: torch.device | None = None,
|
| 392 |
+
) -> torch.Tensor:
|
| 393 |
+
"""Per-sample [B, 1, S, S] visibility over the concatenated [video, action] sequence.
|
| 394 |
+
|
| 395 |
+
`human_mask` is [B, 1+K] with True = that human video step was
|
| 396 |
+
supplied. `human_motion_mask` has the same shape and controls the mapped
|
| 397 |
+
84-D motion tokens. It defaults to `human_mask`, preserving the joint-mask
|
| 398 |
+
training contract and every existing caller.
|
| 399 |
+
|
| 400 |
+
Rows follow the group-level contract:
|
| 401 |
+
|
| 402 |
+
valid condition (R0, H0, available H*) -> valid condition only
|
| 403 |
+
missing condition (masked-out H*) -> itself only, output discarded
|
| 404 |
+
prediction (robot future + state) -> valid condition + prediction
|
| 405 |
+
|
| 406 |
+
Missing frames are excluded as keys entirely, so no query ever reads them.
|
| 407 |
+
Their own rows are diagonal-only purely to keep the softmax well defined; a
|
| 408 |
+
fully-False row would produce NaN.
|
| 409 |
+
"""
|
| 410 |
+
|
| 411 |
+
tokens_per_frame = config.tokens_per_frame
|
| 412 |
+
human_slots = config.num_latent_steps
|
| 413 |
+
batch = human_mask.shape[0]
|
| 414 |
+
if human_mask.shape != (batch, human_slots):
|
| 415 |
+
raise ValueError(f"human_mask must be [B, {human_slots}], got {tuple(human_mask.shape)}")
|
| 416 |
+
device = device if device is not None else human_mask.device
|
| 417 |
+
human_mask = human_mask.to(device=device, dtype=torch.bool)
|
| 418 |
+
if human_motion_mask is None:
|
| 419 |
+
human_motion_mask = human_mask
|
| 420 |
+
if human_motion_mask.shape != (batch, human_slots):
|
| 421 |
+
raise ValueError(
|
| 422 |
+
f"human_motion_mask must be [B, {human_slots}], got "
|
| 423 |
+
f"{tuple(human_motion_mask.shape)}"
|
| 424 |
+
)
|
| 425 |
+
human_motion_mask = human_motion_mask.to(device=device, dtype=torch.bool)
|
| 426 |
+
if config.direct_fastwam_robot_only:
|
| 427 |
+
# FastWAM's native graph, with the clean proprio token represented
|
| 428 |
+
# in-sequence instead of through cross-attention:
|
| 429 |
+
# video current -> current video + proprio
|
| 430 |
+
# video future -> all video + proprio (first-frame-causal)
|
| 431 |
+
# action future -> current video + proprio + all future actions
|
| 432 |
+
# There are no human carrier slots and no video/action-future coupling.
|
| 433 |
+
video_tokens = config.num_video_tokens
|
| 434 |
+
current_video = config.tokens_per_frame
|
| 435 |
+
state_index = video_tokens
|
| 436 |
+
action_start = state_index + 1
|
| 437 |
+
total = video_tokens + config.num_action_sequence
|
| 438 |
+
mask = torch.zeros((batch, total, total), dtype=torch.bool, device=device)
|
| 439 |
+
mask[:, :current_video, :current_video] = True
|
| 440 |
+
mask[:, current_video:video_tokens, :video_tokens] = True
|
| 441 |
+
mask[:, :video_tokens, state_index] = True
|
| 442 |
+
mask[:, state_index, :current_video] = True
|
| 443 |
+
mask[:, state_index, state_index] = True
|
| 444 |
+
mask[:, action_start:, :current_video] = True
|
| 445 |
+
mask[:, action_start:, state_index:] = True
|
| 446 |
+
return mask.unsqueeze(1)
|
| 447 |
+
if not config.use_human_video_context:
|
| 448 |
+
human_mask = torch.zeros_like(human_mask)
|
| 449 |
+
if not config.use_human_motion_context:
|
| 450 |
+
human_motion_mask = torch.zeros_like(human_motion_mask)
|
| 451 |
+
|
| 452 |
+
# --- video side: robot z0, human z0.., then the predicted robot steps ------
|
| 453 |
+
frame_available = torch.ones((batch, config.num_video_frames), dtype=torch.bool, device=device)
|
| 454 |
+
frame_available[:, 1 : 1 + human_slots] = human_mask
|
| 455 |
+
is_condition_frame = torch.zeros(config.num_video_frames, dtype=torch.bool, device=device)
|
| 456 |
+
is_condition_frame[: config.num_condition_frames] = True
|
| 457 |
+
|
| 458 |
+
valid = (frame_available & is_condition_frame[None, :]).repeat_interleave(
|
| 459 |
+
tokens_per_frame, dim=1
|
| 460 |
+
)
|
| 461 |
+
missing = ((~frame_available) & is_condition_frame[None, :]).repeat_interleave(
|
| 462 |
+
tokens_per_frame, dim=1
|
| 463 |
+
)
|
| 464 |
+
prediction = (
|
| 465 |
+
(~is_condition_frame)[None, :].expand(batch, -1).repeat_interleave(tokens_per_frame, dim=1)
|
| 466 |
+
)
|
| 467 |
+
|
| 468 |
+
# --- action side: optional clean anchors, then the predicted states --------
|
| 469 |
+
if config.use_state_context:
|
| 470 |
+
# The robot anchor slot is retained in same-size ablations, but can be
|
| 471 |
+
# made a missing (diagonal-only) key/value.
|
| 472 |
+
robot_now = torch.full(
|
| 473 |
+
(batch, 1),
|
| 474 |
+
bool(config.use_robot_state_context),
|
| 475 |
+
dtype=torch.bool,
|
| 476 |
+
device=device,
|
| 477 |
+
)
|
| 478 |
+
# A human-motion token inherits the availability of the latent step whose
|
| 479 |
+
# control steps it covers, so masking a human step masks its motion too.
|
| 480 |
+
steps = torch.tensor(config.human_action_latent_step(), dtype=torch.long, device=device)
|
| 481 |
+
human_now = human_motion_mask[:, steps]
|
| 482 |
+
action_valid = torch.cat((robot_now, human_now), dim=1)
|
| 483 |
+
action_missing = torch.cat((~robot_now, ~human_now), dim=1)
|
| 484 |
+
else:
|
| 485 |
+
action_valid = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 486 |
+
action_missing = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 487 |
+
action_prediction = torch.ones(
|
| 488 |
+
(batch, config.num_action_tokens), dtype=torch.bool, device=device
|
| 489 |
+
)
|
| 490 |
+
zeros_pred = torch.zeros_like(action_prediction)
|
| 491 |
+
|
| 492 |
+
valid = torch.cat((valid, action_valid, zeros_pred), dim=1)
|
| 493 |
+
missing = torch.cat((missing, action_missing, zeros_pred), dim=1)
|
| 494 |
+
prediction = torch.cat((prediction, torch.zeros_like(action_valid), action_prediction), dim=1)
|
| 495 |
+
|
| 496 |
+
total = valid.shape[1]
|
| 497 |
+
mask = valid[:, :, None] & valid[:, None, :]
|
| 498 |
+
mask |= prediction[:, :, None] & (valid | prediction)[:, None, :]
|
| 499 |
+
mask |= missing[:, :, None] & torch.eye(total, dtype=torch.bool, device=device)[None]
|
| 500 |
+
if not config.future_video_action_coupling:
|
| 501 |
+
video_start = config.num_condition_frames * tokens_per_frame
|
| 502 |
+
video_end = config.num_video_tokens
|
| 503 |
+
action_start = video_end + config.num_action_condition_tokens
|
| 504 |
+
mask[:, video_start:video_end, action_start:] = False
|
| 505 |
+
mask[:, action_start:, video_start:video_end] = False
|
| 506 |
+
return mask.unsqueeze(1)
|
| 507 |
+
|
| 508 |
+
|
| 509 |
+
def build_linear_attention_groups(
|
| 510 |
+
config: "HRMoTConfig", attention_mask: torch.Tensor
|
| 511 |
+
) -> dict[str, torch.Tensor]:
|
| 512 |
+
"""Recover the three exact H&R visibility groups for linear attention.
|
| 513 |
+
|
| 514 |
+
The prediction positions are fixed by the sequence layout. A condition key
|
| 515 |
+
with exactly one reader is a hard-masked slot because missing slots have a
|
| 516 |
+
diagonal-only row/column. Keeping this derivation tied to the canonical
|
| 517 |
+
attention mask prevents the linear backend from drifting from softmax mask
|
| 518 |
+
semantics when availability patterns change.
|
| 519 |
+
"""
|
| 520 |
+
|
| 521 |
+
if attention_mask.ndim != 4 or attention_mask.shape[1] != 1:
|
| 522 |
+
raise ValueError("attention_mask must be [B,1,S,S], got " f"{tuple(attention_mask.shape)}")
|
| 523 |
+
batch, _, rows, cols = attention_mask.shape
|
| 524 |
+
expected = config.num_video_tokens + config.num_action_sequence
|
| 525 |
+
if rows != expected or cols != expected:
|
| 526 |
+
raise ValueError(f"attention_mask must have S={expected}, got {(rows, cols)}")
|
| 527 |
+
prediction = torch.zeros((batch, expected), dtype=torch.bool, device=attention_mask.device)
|
| 528 |
+
prediction[:, config.num_condition_tokens : config.num_video_tokens] = True
|
| 529 |
+
action_start = config.num_video_tokens + config.num_action_condition_tokens
|
| 530 |
+
prediction[:, action_start:] = True
|
| 531 |
+
readers_per_key = attention_mask[:, 0].to(torch.int32).sum(dim=-2)
|
| 532 |
+
missing = (~prediction) & (readers_per_key == 1)
|
| 533 |
+
condition = (~prediction) & (~missing)
|
| 534 |
+
return {"condition": condition, "prediction": prediction, "missing": missing}
|
| 535 |
+
|
| 536 |
+
|
| 537 |
+
class HRDiTBlock(nn.Module):
|
| 538 |
+
"""FastWAM's DiT block minus cross-attention: all conditioning is in-sequence."""
|
| 539 |
+
|
| 540 |
+
def __init__(
|
| 541 |
+
self,
|
| 542 |
+
hidden_dim: int,
|
| 543 |
+
attn_head_dim: int,
|
| 544 |
+
num_heads: int,
|
| 545 |
+
ffn_dim: int,
|
| 546 |
+
eps: float = 1e-6,
|
| 547 |
+
) -> None:
|
| 548 |
+
super().__init__()
|
| 549 |
+
self.hidden_dim = hidden_dim
|
| 550 |
+
self.attn_head_dim = attn_head_dim
|
| 551 |
+
self.num_heads = num_heads
|
| 552 |
+
self.ffn_dim = ffn_dim
|
| 553 |
+
|
| 554 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 555 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 556 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 557 |
+
self.ffn = nn.Sequential(
|
| 558 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 559 |
+
nn.GELU(approximate="tanh"),
|
| 560 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 561 |
+
)
|
| 562 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 563 |
+
self.gate = GateModule()
|
| 564 |
+
|
| 565 |
+
|
| 566 |
+
class HRHead(nn.Module):
|
| 567 |
+
"""Final AdaLN-modulated projection, driven by the same per-token timestep."""
|
| 568 |
+
|
| 569 |
+
def __init__(self, hidden_dim: int, out_dim: int, eps: float = 1e-6) -> None:
|
| 570 |
+
super().__init__()
|
| 571 |
+
self.norm = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 572 |
+
self.head = nn.Linear(hidden_dim, out_dim)
|
| 573 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, hidden_dim) / hidden_dim**0.5)
|
| 574 |
+
|
| 575 |
+
def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 576 |
+
# x, t: [B, S, hidden]
|
| 577 |
+
modulation = self.modulation.unsqueeze(0).to(dtype=t.dtype, device=t.device)
|
| 578 |
+
shift, scale = (modulation + t.unsqueeze(2)).chunk(2, dim=2)
|
| 579 |
+
return self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 580 |
+
|
| 581 |
+
|
| 582 |
+
class _ExpertBase(nn.Module):
|
| 583 |
+
"""Shared timestep-modulation plumbing and the MoT-required attributes."""
|
| 584 |
+
|
| 585 |
+
def __init__(
|
| 586 |
+
self,
|
| 587 |
+
*,
|
| 588 |
+
hidden_dim: int,
|
| 589 |
+
ffn_dim: int,
|
| 590 |
+
num_layers: int,
|
| 591 |
+
num_heads: int,
|
| 592 |
+
attn_head_dim: int,
|
| 593 |
+
freq_dim: int,
|
| 594 |
+
eps: float,
|
| 595 |
+
gradient_checkpointing: bool,
|
| 596 |
+
) -> None:
|
| 597 |
+
super().__init__()
|
| 598 |
+
self.hidden_dim = hidden_dim
|
| 599 |
+
self.num_heads = num_heads
|
| 600 |
+
self.attn_head_dim = attn_head_dim
|
| 601 |
+
self.freq_dim = freq_dim
|
| 602 |
+
self.use_gradient_checkpointing = bool(gradient_checkpointing)
|
| 603 |
+
|
| 604 |
+
self.blocks = nn.ModuleList(
|
| 605 |
+
HRDiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 606 |
+
for _ in range(num_layers)
|
| 607 |
+
)
|
| 608 |
+
self.time_embedding = nn.Sequential(
|
| 609 |
+
nn.Linear(freq_dim, hidden_dim),
|
| 610 |
+
nn.SiLU(),
|
| 611 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 612 |
+
)
|
| 613 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 614 |
+
self._rope_cache: dict[tuple[torch.device, int], torch.Tensor] = {}
|
| 615 |
+
|
| 616 |
+
def embed_timesteps(self, token_timesteps: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 617 |
+
"""[B, S] per-token flow time -> (t [B, S, D], t_mod [B, S, 6, D])."""
|
| 618 |
+
|
| 619 |
+
batch, seq_len = token_timesteps.shape
|
| 620 |
+
embedded = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1).float())
|
| 621 |
+
t = self.time_embedding(embedded).reshape(batch, seq_len, self.hidden_dim)
|
| 622 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 623 |
+
return t, t_mod
|
| 624 |
+
|
| 625 |
+
|
| 626 |
+
class HRVideoExpert(_ExpertBase):
|
| 627 |
+
"""Video expert over per-frame Wan2.2 latents with 3D RoPE and role embeddings."""
|
| 628 |
+
|
| 629 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 630 |
+
super().__init__(
|
| 631 |
+
hidden_dim=config.video_hidden_dim,
|
| 632 |
+
ffn_dim=config.video_ffn_dim,
|
| 633 |
+
num_layers=config.num_layers,
|
| 634 |
+
num_heads=config.num_heads,
|
| 635 |
+
attn_head_dim=config.attn_head_dim,
|
| 636 |
+
freq_dim=config.freq_dim,
|
| 637 |
+
eps=config.eps,
|
| 638 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 639 |
+
)
|
| 640 |
+
self.config = config
|
| 641 |
+
patch = (1, config.patch_height, config.patch_width)
|
| 642 |
+
self.patch_size = patch
|
| 643 |
+
self.patch_embedding = nn.Conv3d(
|
| 644 |
+
config.latent_channels, config.video_hidden_dim, kernel_size=patch, stride=patch
|
| 645 |
+
)
|
| 646 |
+
self.role_embedding = nn.Parameter(torch.zeros(NUM_ROLES, config.video_hidden_dim))
|
| 647 |
+
# Availability code read by the *prediction* tokens. It has to live here,
|
| 648 |
+
# not on the human slots: under the hard mask nothing can read a missing
|
| 649 |
+
# frame, so a marker placed on it would be permanently unreachable and
|
| 650 |
+
# carry zero gradient. One embedding per (human slot, available?) pair,
|
| 651 |
+
# summed, tells the predictor exactly which human frames were supplied.
|
| 652 |
+
if not config.direct_fastwam_robot_only:
|
| 653 |
+
self.availability_embedding = nn.Parameter(
|
| 654 |
+
torch.zeros(config.num_latent_steps, 2, config.video_hidden_dim)
|
| 655 |
+
)
|
| 656 |
+
self.head = HRHead(
|
| 657 |
+
config.video_hidden_dim,
|
| 658 |
+
config.latent_channels * config.patch_height * config.patch_width,
|
| 659 |
+
config.eps,
|
| 660 |
+
)
|
| 661 |
+
# Kept off the module buffer registry: complex tensors do not survive DDP
|
| 662 |
+
# buffer broadcast cleanly, and these are deterministic constants anyway.
|
| 663 |
+
self._freqs_3d = precompute_freqs_cis_3d(config.attn_head_dim, end=config.max_rope_position)
|
| 664 |
+
|
| 665 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 666 |
+
"""[num_video_tokens, 1, head_dim/2] complex, in frame-major token order."""
|
| 667 |
+
|
| 668 |
+
key = (device, 0)
|
| 669 |
+
cached = self._rope_cache.get(key)
|
| 670 |
+
if cached is not None:
|
| 671 |
+
return cached
|
| 672 |
+
config = self.config
|
| 673 |
+
grid_h = config.latent_height // config.patch_height
|
| 674 |
+
grid_w = config.latent_width // config.patch_width
|
| 675 |
+
f_freqs, h_freqs, w_freqs = (x.to(device) for x in self._freqs_3d)
|
| 676 |
+
positions = torch.tensor(config.frame_rope_positions, dtype=torch.long, device=device)
|
| 677 |
+
num_frames = positions.numel()
|
| 678 |
+
freqs = torch.cat(
|
| 679 |
+
(
|
| 680 |
+
f_freqs[positions]
|
| 681 |
+
.view(num_frames, 1, 1, -1)
|
| 682 |
+
.expand(num_frames, grid_h, grid_w, -1),
|
| 683 |
+
h_freqs[:grid_h].view(1, grid_h, 1, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 684 |
+
w_freqs[:grid_w].view(1, 1, grid_w, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 685 |
+
),
|
| 686 |
+
dim=-1,
|
| 687 |
+
).reshape(num_frames * grid_h * grid_w, 1, -1)
|
| 688 |
+
self._rope_cache[key] = freqs
|
| 689 |
+
return freqs
|
| 690 |
+
|
| 691 |
+
def embed(self, latents: torch.Tensor, human_mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 692 |
+
"""[B, N, C, h, w] latents -> [B, N*tokens_per_frame, D] tokens.
|
| 693 |
+
|
| 694 |
+
`human_mask` is [B, 1+K] with True = this human frame is provided. Frames
|
| 695 |
+
marked False are replaced by `absent_human_embedding`, so they keep their
|
| 696 |
+
slot, role and RoPE position but carry no information from any episode.
|
| 697 |
+
"""
|
| 698 |
+
|
| 699 |
+
config = self.config
|
| 700 |
+
if latents.ndim != 5:
|
| 701 |
+
raise ValueError(f"latents must be [B, N, C, h, w], got {tuple(latents.shape)}")
|
| 702 |
+
if latents.shape[1] != config.num_video_frames:
|
| 703 |
+
raise ValueError(
|
| 704 |
+
f"expected {config.num_video_frames} video frames, got {latents.shape[1]}"
|
| 705 |
+
)
|
| 706 |
+
if latents.shape[2:] != (
|
| 707 |
+
config.latent_channels,
|
| 708 |
+
config.latent_height,
|
| 709 |
+
config.latent_width,
|
| 710 |
+
):
|
| 711 |
+
raise ValueError(
|
| 712 |
+
f"latent shape {tuple(latents.shape[2:])} does not match config "
|
| 713 |
+
f"({config.latent_channels}, {config.latent_height}, {config.latent_width})"
|
| 714 |
+
)
|
| 715 |
+
# patch_size[0] == 1, so the conv never mixes two frames together.
|
| 716 |
+
x = self.patch_embedding(latents.permute(0, 2, 1, 3, 4))
|
| 717 |
+
tokens = rearrange(x, "b d n h w -> b n (h w) d")
|
| 718 |
+
if config.direct_fastwam_robot_only and human_mask is not None:
|
| 719 |
+
raise ValueError("direct FastWAM has no human video mask or carrier slots")
|
| 720 |
+
if human_mask is not None:
|
| 721 |
+
start = 1 # human latent steps occupy [1, 1 + num_latent_steps)
|
| 722 |
+
end = 1 + config.num_latent_steps
|
| 723 |
+
if human_mask.shape != (tokens.shape[0], end - start):
|
| 724 |
+
raise ValueError(
|
| 725 |
+
f"human_mask must be [B, {end - start}], got {tuple(human_mask.shape)}"
|
| 726 |
+
)
|
| 727 |
+
keep = human_mask[:, :, None, None].to(torch.bool).to(tokens.device)
|
| 728 |
+
# Whole-frame masking: every token of a human frame is dropped
|
| 729 |
+
# together, never a scattered subset of patches. The hard attention
|
| 730 |
+
# mask already makes these unreadable; zeroing also removes the data.
|
| 731 |
+
human = tokens[:, start:end] * keep.to(tokens.dtype)
|
| 732 |
+
# Availability code onto the robot-future (prediction) frames.
|
| 733 |
+
slots = torch.arange(end - start, device=tokens.device)
|
| 734 |
+
if config.use_human_video_context:
|
| 735 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 736 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 737 |
+
].sum(dim=1)[:, None, None, :]
|
| 738 |
+
else:
|
| 739 |
+
# A fixed "all absent" code would not carry episode data, but it
|
| 740 |
+
# would create a side channel absent from the robot-z0-only claim.
|
| 741 |
+
# Keep a zero-valued autograd edge so DDP still reduces this
|
| 742 |
+
# retained same-size parameter instead of flagging it unused.
|
| 743 |
+
code = self.availability_embedding.sum().to(tokens.dtype) * 0.0
|
| 744 |
+
future = tokens[:, end:] + code
|
| 745 |
+
tokens = torch.cat((tokens[:, :start], human, future), dim=1)
|
| 746 |
+
roles = torch.tensor(config.frame_roles, dtype=torch.long, device=latents.device)
|
| 747 |
+
tokens = tokens + self.role_embedding[roles][None, :, None, :].to(tokens.dtype)
|
| 748 |
+
if not config.use_human_video_context and not config.direct_fastwam_robot_only:
|
| 749 |
+
tokens[:, 1 : 1 + config.num_latent_steps] = 0
|
| 750 |
+
return rearrange(tokens, "b n s d -> b (n s) d")
|
| 751 |
+
|
| 752 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor, num_frames: int) -> torch.Tensor:
|
| 753 |
+
"""[B, N*tokens_per_frame, D] -> [B, N, C, h, w] velocity in latent space."""
|
| 754 |
+
|
| 755 |
+
config = self.config
|
| 756 |
+
grid_h = config.latent_height // config.patch_height
|
| 757 |
+
grid_w = config.latent_width // config.patch_width
|
| 758 |
+
x = self.head(tokens, t)
|
| 759 |
+
return rearrange(
|
| 760 |
+
x,
|
| 761 |
+
"b (n h w) (c ph pw) -> b n c (h ph) (w pw)",
|
| 762 |
+
n=num_frames,
|
| 763 |
+
h=grid_h,
|
| 764 |
+
w=grid_w,
|
| 765 |
+
ph=config.patch_height,
|
| 766 |
+
pw=config.patch_width,
|
| 767 |
+
)
|
| 768 |
+
|
| 769 |
+
|
| 770 |
+
class HRActionExpert(_ExpertBase):
|
| 771 |
+
"""Action expert over one token per future horizon, with 1D RoPE on the horizon."""
|
| 772 |
+
|
| 773 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 774 |
+
super().__init__(
|
| 775 |
+
hidden_dim=config.action_hidden_dim,
|
| 776 |
+
ffn_dim=config.action_ffn_dim,
|
| 777 |
+
num_layers=config.num_layers,
|
| 778 |
+
num_heads=config.num_heads,
|
| 779 |
+
attn_head_dim=config.attn_head_dim,
|
| 780 |
+
freq_dim=config.freq_dim,
|
| 781 |
+
eps=config.eps,
|
| 782 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 783 |
+
)
|
| 784 |
+
self.config = config
|
| 785 |
+
self.action_embedding = nn.Linear(config.action_dim, config.action_hidden_dim)
|
| 786 |
+
if not config.direct_fastwam_robot_only:
|
| 787 |
+
self.availability_embedding = nn.Parameter(
|
| 788 |
+
torch.zeros(config.num_latent_steps, 2, config.action_hidden_dim)
|
| 789 |
+
)
|
| 790 |
+
if config.use_state_context:
|
| 791 |
+
# The robot anchor reuses action_embedding: it is the same 7-D
|
| 792 |
+
# quantity, so the same projection is the right one. Human hand
|
| 793 |
+
# motion is a different 84-D modality and gets its own projection.
|
| 794 |
+
if not config.direct_fastwam_robot_only:
|
| 795 |
+
self.human_action_embedding = nn.Linear(
|
| 796 |
+
config.human_action_dim, config.action_hidden_dim
|
| 797 |
+
)
|
| 798 |
+
self.action_role_embedding = nn.Parameter(
|
| 799 |
+
torch.zeros(NUM_ROLES, config.action_hidden_dim)
|
| 800 |
+
)
|
| 801 |
+
self.head = HRHead(config.action_hidden_dim, config.action_dim, config.eps)
|
| 802 |
+
self._freqs_1d = precompute_freqs_cis(config.attn_head_dim, end=config.max_rope_position)
|
| 803 |
+
|
| 804 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 805 |
+
key = (device, 0)
|
| 806 |
+
cached = self._rope_cache.get(key)
|
| 807 |
+
if cached is not None:
|
| 808 |
+
return cached
|
| 809 |
+
positions = torch.tensor(self.config.action_rope_positions, dtype=torch.long, device=device)
|
| 810 |
+
freqs = self._freqs_1d.to(device)[positions].view(positions.numel(), 1, -1)
|
| 811 |
+
self._rope_cache[key] = freqs
|
| 812 |
+
return freqs
|
| 813 |
+
|
| 814 |
+
def embed(
|
| 815 |
+
self,
|
| 816 |
+
actions: torch.Tensor,
|
| 817 |
+
human_mask: torch.Tensor | None = None,
|
| 818 |
+
robot_current_state: torch.Tensor | None = None,
|
| 819 |
+
human_future_action: torch.Tensor | None = None,
|
| 820 |
+
) -> torch.Tensor:
|
| 821 |
+
"""-> [B, num_action_sequence, D], condition block first when enabled."""
|
| 822 |
+
|
| 823 |
+
config = self.config
|
| 824 |
+
if actions.ndim != 3 or actions.shape[1:] != (
|
| 825 |
+
config.num_action_tokens,
|
| 826 |
+
config.action_dim,
|
| 827 |
+
):
|
| 828 |
+
raise ValueError(
|
| 829 |
+
f"actions must be [B, {config.num_action_tokens}, {config.action_dim}], "
|
| 830 |
+
f"got {tuple(actions.shape)}"
|
| 831 |
+
)
|
| 832 |
+
predicted = self.action_embedding(actions)
|
| 833 |
+
if config.use_state_context:
|
| 834 |
+
if robot_current_state is None:
|
| 835 |
+
raise ValueError("use_state_context requires robot_current_state")
|
| 836 |
+
if not config.direct_fastwam_robot_only and human_future_action is None:
|
| 837 |
+
raise ValueError(
|
| 838 |
+
"use_state_context requires robot_current_state and 84-D human_future_action"
|
| 839 |
+
)
|
| 840 |
+
if robot_current_state.shape[1:] != (config.action_dim,):
|
| 841 |
+
raise ValueError(
|
| 842 |
+
f"robot_current_state must be [B, {config.action_dim}], "
|
| 843 |
+
f"got {tuple(robot_current_state.shape)}"
|
| 844 |
+
)
|
| 845 |
+
if not config.direct_fastwam_robot_only:
|
| 846 |
+
if human_future_action.shape[1:] != (
|
| 847 |
+
config.num_action_tokens,
|
| 848 |
+
config.human_action_dim,
|
| 849 |
+
):
|
| 850 |
+
raise ValueError(
|
| 851 |
+
f"human_future_action must be [B, {config.num_action_tokens}, "
|
| 852 |
+
f"{config.human_action_dim}], got {tuple(human_future_action.shape)}"
|
| 853 |
+
)
|
| 854 |
+
role = self.action_role_embedding.to(predicted.dtype)
|
| 855 |
+
anchor = self.action_embedding(robot_current_state)[:, None, :]
|
| 856 |
+
anchor = anchor + role[ROLE_ROBOT_CURRENT]
|
| 857 |
+
if not config.use_robot_state_context:
|
| 858 |
+
anchor = torch.zeros_like(anchor)
|
| 859 |
+
predicted = predicted + role[ROLE_ROBOT_FUTURE]
|
| 860 |
+
if config.direct_fastwam_robot_only:
|
| 861 |
+
tokens = torch.cat((anchor, predicted), dim=1)
|
| 862 |
+
return tokens
|
| 863 |
+
human = self.human_action_embedding(human_future_action) + role[ROLE_HUMAN_CONTEXT]
|
| 864 |
+
if human_mask is not None:
|
| 865 |
+
# Zero a masked step's human-motion tokens as well; the hard attention
|
| 866 |
+
# mask already makes them unreadable, this also drops the data.
|
| 867 |
+
steps = torch.tensor(config.human_action_latent_step(), device=human.device)
|
| 868 |
+
keep = human_mask.to(human.device)[:, steps][:, :, None]
|
| 869 |
+
human = human * keep.to(human.dtype)
|
| 870 |
+
tokens = torch.cat((anchor, human, predicted), dim=1)
|
| 871 |
+
else:
|
| 872 |
+
tokens = predicted
|
| 873 |
+
if human_mask is not None and not config.direct_fastwam_robot_only:
|
| 874 |
+
if config.use_human_motion_context:
|
| 875 |
+
slots = torch.arange(human_mask.shape[1], device=tokens.device)
|
| 876 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 877 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 878 |
+
].sum(dim=1)[:, None, :]
|
| 879 |
+
else:
|
| 880 |
+
# Same zero-edge contract as the video expert: no information or
|
| 881 |
+
# numerical effect, while every retained parameter participates.
|
| 882 |
+
code = self.availability_embedding.sum().to(tokens.dtype) * 0.0
|
| 883 |
+
tokens = tokens + code
|
| 884 |
+
return tokens
|
| 885 |
+
|
| 886 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 887 |
+
return self.head(tokens, t)
|
| 888 |
+
|
| 889 |
+
|
| 890 |
+
class HRMoTFlowModel(nn.Module):
|
| 891 |
+
"""The trainable ~0.6B model. VAE encoding happens outside, in the trainer."""
|
| 892 |
+
|
| 893 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 894 |
+
super().__init__()
|
| 895 |
+
config.validate()
|
| 896 |
+
self.config = config
|
| 897 |
+
# MoT owns the experts. Registering them a second time on this module
|
| 898 |
+
# would duplicate every tensor in state_dict, so they are reached through
|
| 899 |
+
# properties instead of attributes.
|
| 900 |
+
self.mot = MoT(
|
| 901 |
+
mixtures={"video": HRVideoExpert(config), "action": HRActionExpert(config)},
|
| 902 |
+
mot_checkpoint_mixed_attn=config.gradient_checkpointing,
|
| 903 |
+
mixed_attention_type=config.mixed_attention_type,
|
| 904 |
+
)
|
| 905 |
+
self.train_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 906 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_train_shift
|
| 907 |
+
)
|
| 908 |
+
self.infer_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 909 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_infer_shift
|
| 910 |
+
)
|
| 911 |
+
self.train_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 912 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_train_shift
|
| 913 |
+
)
|
| 914 |
+
self.infer_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 915 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_infer_shift
|
| 916 |
+
)
|
| 917 |
+
self.reset_parameters()
|
| 918 |
+
|
| 919 |
+
@property
|
| 920 |
+
def video_expert(self) -> HRVideoExpert:
|
| 921 |
+
return self.mot.mixtures["video"]
|
| 922 |
+
|
| 923 |
+
@property
|
| 924 |
+
def action_expert(self) -> HRActionExpert:
|
| 925 |
+
return self.mot.mixtures["action"]
|
| 926 |
+
|
| 927 |
+
def reset_parameters(self) -> None:
|
| 928 |
+
"""Random init only. No pretrained weights enter the trainable model."""
|
| 929 |
+
|
| 930 |
+
def init_linear(module: nn.Module) -> None:
|
| 931 |
+
if isinstance(module, (nn.Linear, nn.Conv3d)):
|
| 932 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 933 |
+
if module.bias is not None:
|
| 934 |
+
nn.init.zeros_(module.bias)
|
| 935 |
+
|
| 936 |
+
self.apply(init_linear)
|
| 937 |
+
nn.init.normal_(self.video_expert.role_embedding, mean=0.0, std=0.02)
|
| 938 |
+
for expert in (self.video_expert, self.action_expert):
|
| 939 |
+
if hasattr(expert, "availability_embedding"):
|
| 940 |
+
nn.init.normal_(expert.availability_embedding, mean=0.0, std=0.02)
|
| 941 |
+
if self.config.use_state_context:
|
| 942 |
+
nn.init.normal_(self.action_expert.action_role_embedding, mean=0.0, std=0.02)
|
| 943 |
+
# Wan/DiT init: `modulation` keeps its randn/sqrt(dim) scale (set in the
|
| 944 |
+
# block) and residual output projections are down-scaled by depth so a
|
| 945 |
+
# 22-layer stack does not blow up at step 0.
|
| 946 |
+
residual_std = 0.02 / math.sqrt(2.0 * self.config.num_layers)
|
| 947 |
+
# The final head is initialized *near* zero rather than at zero. Exactly
|
| 948 |
+
# zero makes the model emit zero velocity, which is stable, but it also
|
| 949 |
+
# makes d(loss)/d(head input) identically zero: on the first step only the
|
| 950 |
+
# two head tensors per expert receive gradient and the other 679 do not.
|
| 951 |
+
# A tiny nonzero scale keeps the near-zero start and lets gradient reach
|
| 952 |
+
# every parameter from step 1.
|
| 953 |
+
head_std = 1e-4
|
| 954 |
+
for expert in (self.video_expert, self.action_expert):
|
| 955 |
+
for block in expert.blocks:
|
| 956 |
+
nn.init.normal_(block.self_attn.o.weight, mean=0.0, std=residual_std)
|
| 957 |
+
nn.init.normal_(block.ffn[-1].weight, mean=0.0, std=residual_std)
|
| 958 |
+
nn.init.normal_(expert.head.head.weight, mean=0.0, std=head_std)
|
| 959 |
+
nn.init.zeros_(expert.head.head.bias)
|
| 960 |
+
|
| 961 |
+
def attention_mask(
|
| 962 |
+
self,
|
| 963 |
+
human_mask: torch.Tensor,
|
| 964 |
+
*,
|
| 965 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 966 |
+
device: torch.device,
|
| 967 |
+
) -> torch.Tensor:
|
| 968 |
+
return build_availability_attention_mask(
|
| 969 |
+
self.config,
|
| 970 |
+
human_mask,
|
| 971 |
+
human_motion_mask=human_motion_mask,
|
| 972 |
+
device=device,
|
| 973 |
+
)
|
| 974 |
+
|
| 975 |
+
def human_availability_patterns(self, device: torch.device) -> torch.Tensor:
|
| 976 |
+
"""Every availability pattern over the maskable human latent steps.
|
| 977 |
+
|
| 978 |
+
All 2^Tz patterns when the human current step is droppable, otherwise the
|
| 979 |
+
2^(Tz-1) patterns that keep it.
|
| 980 |
+
"""
|
| 981 |
+
|
| 982 |
+
slots = self.config.num_latent_steps
|
| 983 |
+
if not self.config.droppable_human_current:
|
| 984 |
+
slots -= 1
|
| 985 |
+
codes = torch.arange(2**slots, device=device)
|
| 986 |
+
bits = torch.arange(slots, device=device)
|
| 987 |
+
return ((codes[:, None] >> bits[None, :]) & 1).bool()
|
| 988 |
+
|
| 989 |
+
def sample_human_mask(
|
| 990 |
+
self,
|
| 991 |
+
batch: int,
|
| 992 |
+
*,
|
| 993 |
+
device: torch.device,
|
| 994 |
+
generator: Optional[torch.Generator] = None,
|
| 995 |
+
) -> torch.Tensor:
|
| 996 |
+
"""[B, Tz] bool. True = that human latent step is supplied.
|
| 997 |
+
|
| 998 |
+
With no explicit none probability, non-full samples are uniform over
|
| 999 |
+
all other patterns. With an explicit none probability, full and none
|
| 1000 |
+
have their configured masses and only partial patterns are uniform.
|
| 1001 |
+
|
| 1002 |
+
When `droppable_human_current` is set, the human z0 step is included in
|
| 1003 |
+
the draw, so "no human context at all" is a trained condition rather than
|
| 1004 |
+
an out-of-distribution query, and the model cannot lean entirely on the
|
| 1005 |
+
same-moment cross-embodiment correspondence.
|
| 1006 |
+
"""
|
| 1007 |
+
|
| 1008 |
+
config = self.config
|
| 1009 |
+
patterns = self.human_availability_patterns(device)
|
| 1010 |
+
# With explicit no-context mass, draw only partial patterns here.
|
| 1011 |
+
first_pattern = 0 if config.none_human_context_prob is None else 1
|
| 1012 |
+
choice = torch.randint(
|
| 1013 |
+
first_pattern, patterns.shape[0] - 1, (batch,), device=device, generator=generator
|
| 1014 |
+
)
|
| 1015 |
+
drawn = patterns[choice]
|
| 1016 |
+
uniform = torch.rand(batch, device=device, generator=generator)
|
| 1017 |
+
use_full = uniform < float(config.full_human_context_prob)
|
| 1018 |
+
drawn = torch.where(use_full[:, None], torch.ones_like(drawn), drawn)
|
| 1019 |
+
if config.none_human_context_prob is not None:
|
| 1020 |
+
use_none = uniform >= 1.0 - config.none_human_context_prob
|
| 1021 |
+
drawn = torch.where(use_none[:, None], torch.zeros_like(drawn), drawn)
|
| 1022 |
+
if config.droppable_human_current:
|
| 1023 |
+
return drawn
|
| 1024 |
+
current = torch.ones((batch, 1), dtype=torch.bool, device=device)
|
| 1025 |
+
return torch.cat((current, drawn), dim=1)
|
| 1026 |
+
|
| 1027 |
+
def _token_timesteps(
|
| 1028 |
+
self, timestep: torch.Tensor, *, num_frames: int, noisy_frames: int
|
| 1029 |
+
) -> torch.Tensor:
|
| 1030 |
+
"""Clean condition frames get t=0; only the robot future frames carry t=s."""
|
| 1031 |
+
|
| 1032 |
+
config = self.config
|
| 1033 |
+
batch = timestep.shape[0]
|
| 1034 |
+
per_frame = torch.zeros((batch, num_frames), dtype=torch.float32, device=timestep.device)
|
| 1035 |
+
per_frame[:, num_frames - noisy_frames :] = timestep.float()[:, None]
|
| 1036 |
+
return per_frame.repeat_interleave(config.tokens_per_frame, dim=1)
|
| 1037 |
+
|
| 1038 |
+
def forward_tokens(
|
| 1039 |
+
self,
|
| 1040 |
+
*,
|
| 1041 |
+
robot_current_latent: torch.Tensor,
|
| 1042 |
+
human_latents: torch.Tensor,
|
| 1043 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 1044 |
+
noisy_robot_future_action: torch.Tensor,
|
| 1045 |
+
timestep_video: torch.Tensor,
|
| 1046 |
+
timestep_action: torch.Tensor,
|
| 1047 |
+
human_mask: torch.Tensor | None = None,
|
| 1048 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 1049 |
+
robot_current_state: torch.Tensor | None = None,
|
| 1050 |
+
human_future_action: torch.Tensor | None = None,
|
| 1051 |
+
) -> tuple[dict[str, torch.Tensor], torch.Tensor, torch.Tensor]:
|
| 1052 |
+
"""Run the MoT and return (tokens_out, video_t, action_t).
|
| 1053 |
+
|
| 1054 |
+
`tokens_out["video"]` still holds the condition positions, which
|
| 1055 |
+
`predict_velocity` drops. Tests use them to prove the attention mask
|
| 1056 |
+
really isolates condition tokens from the noisy prediction tokens.
|
| 1057 |
+
"""
|
| 1058 |
+
|
| 1059 |
+
config = self.config
|
| 1060 |
+
if robot_current_latent.ndim != 5 or robot_current_latent.shape[1] != 1:
|
| 1061 |
+
raise ValueError(
|
| 1062 |
+
f"robot_current_latent must be [B, 1, C, h, w], got "
|
| 1063 |
+
f"{tuple(robot_current_latent.shape)}"
|
| 1064 |
+
)
|
| 1065 |
+
if (
|
| 1066 |
+
not config.direct_fastwam_robot_only
|
| 1067 |
+
and human_latents.shape[1] != config.num_latent_steps
|
| 1068 |
+
):
|
| 1069 |
+
raise ValueError(
|
| 1070 |
+
f"human_latents must carry {config.num_latent_steps} latent steps, "
|
| 1071 |
+
f"got {human_latents.shape[1]}"
|
| 1072 |
+
)
|
| 1073 |
+
if noisy_robot_future_latents.shape[1] != config.num_horizons:
|
| 1074 |
+
raise ValueError(
|
| 1075 |
+
f"noisy_robot_future_latents must carry {config.num_horizons} horizons, "
|
| 1076 |
+
f"got {noisy_robot_future_latents.shape[1]}"
|
| 1077 |
+
)
|
| 1078 |
+
|
| 1079 |
+
if config.direct_fastwam_robot_only:
|
| 1080 |
+
latents = torch.cat((robot_current_latent, noisy_robot_future_latents), dim=1)
|
| 1081 |
+
else:
|
| 1082 |
+
latents = torch.cat(
|
| 1083 |
+
(robot_current_latent, human_latents, noisy_robot_future_latents), dim=1
|
| 1084 |
+
)
|
| 1085 |
+
device = latents.device
|
| 1086 |
+
|
| 1087 |
+
if human_mask is None:
|
| 1088 |
+
supplied_human_mask = torch.ones(
|
| 1089 |
+
(latents.shape[0], config.num_latent_steps),
|
| 1090 |
+
dtype=torch.bool,
|
| 1091 |
+
device=device,
|
| 1092 |
+
)
|
| 1093 |
+
else:
|
| 1094 |
+
supplied_human_mask = human_mask.to(device=device, dtype=torch.bool)
|
| 1095 |
+
if human_motion_mask is None:
|
| 1096 |
+
human_motion_mask = supplied_human_mask
|
| 1097 |
+
else:
|
| 1098 |
+
human_motion_mask = human_motion_mask.to(device=device, dtype=torch.bool)
|
| 1099 |
+
# Configuration-level ablations fail closed: callers cannot accidentally
|
| 1100 |
+
# re-enable a source by passing an all-True runtime mask.
|
| 1101 |
+
human_mask = (
|
| 1102 |
+
supplied_human_mask
|
| 1103 |
+
if config.use_human_video_context
|
| 1104 |
+
else torch.zeros_like(supplied_human_mask)
|
| 1105 |
+
)
|
| 1106 |
+
if not config.use_human_motion_context:
|
| 1107 |
+
human_motion_mask = torch.zeros_like(human_motion_mask)
|
| 1108 |
+
video_tokens = self.video_expert.embed(
|
| 1109 |
+
latents,
|
| 1110 |
+
human_mask=None if config.direct_fastwam_robot_only else human_mask,
|
| 1111 |
+
)
|
| 1112 |
+
action_tokens = self.action_expert.embed(
|
| 1113 |
+
noisy_robot_future_action,
|
| 1114 |
+
human_mask=None if config.direct_fastwam_robot_only else human_motion_mask,
|
| 1115 |
+
robot_current_state=robot_current_state,
|
| 1116 |
+
human_future_action=human_future_action,
|
| 1117 |
+
)
|
| 1118 |
+
|
| 1119 |
+
video_token_t = self._token_timesteps(
|
| 1120 |
+
timestep_video,
|
| 1121 |
+
num_frames=config.num_video_frames,
|
| 1122 |
+
noisy_frames=config.num_horizons,
|
| 1123 |
+
)
|
| 1124 |
+
# Condition tokens are clean (t=0); only the predicted states carry t=s.
|
| 1125 |
+
action_token_t = torch.zeros(
|
| 1126 |
+
(latents.shape[0], config.num_action_sequence),
|
| 1127 |
+
dtype=torch.float32,
|
| 1128 |
+
device=device,
|
| 1129 |
+
)
|
| 1130 |
+
action_token_t[:, config.num_action_condition_tokens :] = timestep_action.float()[:, None]
|
| 1131 |
+
|
| 1132 |
+
video_t, video_t_mod = self.video_expert.embed_timesteps(video_token_t)
|
| 1133 |
+
action_t, action_t_mod = self.action_expert.embed_timesteps(action_token_t)
|
| 1134 |
+
|
| 1135 |
+
mask = self.attention_mask(human_mask, human_motion_mask=human_motion_mask, device=device)
|
| 1136 |
+
linear_groups = (
|
| 1137 |
+
build_linear_attention_groups(config, mask)
|
| 1138 |
+
if config.mixed_attention_type == "linear"
|
| 1139 |
+
else None
|
| 1140 |
+
)
|
| 1141 |
+
tokens_out = self.mot(
|
| 1142 |
+
embeds_all={"video": video_tokens, "action": action_tokens},
|
| 1143 |
+
attention_mask=mask,
|
| 1144 |
+
freqs_all={
|
| 1145 |
+
"video": self.video_expert.rope_freqs(device),
|
| 1146 |
+
"action": self.action_expert.rope_freqs(device),
|
| 1147 |
+
},
|
| 1148 |
+
# No cross-attention: human context lives in the self-attention sequence.
|
| 1149 |
+
context_all={"video": None, "action": None},
|
| 1150 |
+
t_mod_all={"video": video_t_mod, "action": action_t_mod},
|
| 1151 |
+
linear_attention_groups=linear_groups,
|
| 1152 |
+
)
|
| 1153 |
+
return tokens_out, video_t, action_t
|
| 1154 |
+
|
| 1155 |
+
def predict_velocity(
|
| 1156 |
+
self,
|
| 1157 |
+
*,
|
| 1158 |
+
robot_current_latent: torch.Tensor,
|
| 1159 |
+
human_latents: torch.Tensor,
|
| 1160 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 1161 |
+
noisy_robot_future_action: torch.Tensor,
|
| 1162 |
+
timestep_video: torch.Tensor,
|
| 1163 |
+
timestep_action: torch.Tensor,
|
| 1164 |
+
human_mask: torch.Tensor | None = None,
|
| 1165 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 1166 |
+
robot_current_state: torch.Tensor | None = None,
|
| 1167 |
+
human_future_action: torch.Tensor | None = None,
|
| 1168 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1169 |
+
"""Return flow velocity for the robot future latents and actions."""
|
| 1170 |
+
|
| 1171 |
+
config = self.config
|
| 1172 |
+
tokens_out, video_t, action_t = self.forward_tokens(
|
| 1173 |
+
robot_current_latent=robot_current_latent,
|
| 1174 |
+
human_latents=human_latents,
|
| 1175 |
+
noisy_robot_future_latents=noisy_robot_future_latents,
|
| 1176 |
+
noisy_robot_future_action=noisy_robot_future_action,
|
| 1177 |
+
timestep_video=timestep_video,
|
| 1178 |
+
timestep_action=timestep_action,
|
| 1179 |
+
human_mask=human_mask,
|
| 1180 |
+
human_motion_mask=human_motion_mask,
|
| 1181 |
+
robot_current_state=robot_current_state,
|
| 1182 |
+
human_future_action=human_future_action,
|
| 1183 |
+
)
|
| 1184 |
+
# Only the robot-future slice is a prediction; drop the condition tokens.
|
| 1185 |
+
start = config.num_condition_tokens
|
| 1186 |
+
pred_video = self.video_expert.unembed(
|
| 1187 |
+
tokens_out["video"][:, start:, :],
|
| 1188 |
+
video_t[:, start:, :],
|
| 1189 |
+
num_frames=config.num_horizons,
|
| 1190 |
+
)
|
| 1191 |
+
start_action = config.num_action_condition_tokens
|
| 1192 |
+
pred_action = self.action_expert.unembed(
|
| 1193 |
+
tokens_out["action"][:, start_action:, :], action_t[:, start_action:, :]
|
| 1194 |
+
)
|
| 1195 |
+
return pred_video, pred_action
|
| 1196 |
+
|
| 1197 |
+
def training_loss(
|
| 1198 |
+
self,
|
| 1199 |
+
*,
|
| 1200 |
+
robot_current_latent: torch.Tensor,
|
| 1201 |
+
human_latents: torch.Tensor,
|
| 1202 |
+
robot_future_latents: torch.Tensor,
|
| 1203 |
+
robot_future_action: torch.Tensor,
|
| 1204 |
+
generator: Optional[torch.Generator] = None,
|
| 1205 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1206 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1207 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1208 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1209 |
+
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 1210 |
+
config = self.config
|
| 1211 |
+
batch = robot_future_latents.shape[0]
|
| 1212 |
+
device = robot_future_latents.device
|
| 1213 |
+
dtype = robot_future_latents.dtype
|
| 1214 |
+
|
| 1215 |
+
timestep_video = self.train_video_scheduler.sample_training_t(batch, device, dtype)
|
| 1216 |
+
timestep_action = self.train_action_scheduler.sample_training_t(batch, device, dtype)
|
| 1217 |
+
|
| 1218 |
+
noise_video = torch.randn(
|
| 1219 |
+
robot_future_latents.shape, device=device, dtype=dtype, generator=generator
|
| 1220 |
+
)
|
| 1221 |
+
noise_action = torch.randn(
|
| 1222 |
+
robot_future_action.shape, device=device, dtype=dtype, generator=generator
|
| 1223 |
+
)
|
| 1224 |
+
noisy_video = self.train_video_scheduler.add_noise(
|
| 1225 |
+
robot_future_latents, noise_video, timestep_video
|
| 1226 |
+
)
|
| 1227 |
+
noisy_action = self.train_action_scheduler.add_noise(
|
| 1228 |
+
robot_future_action, noise_action, timestep_action
|
| 1229 |
+
)
|
| 1230 |
+
target_video = self.train_video_scheduler.training_target(
|
| 1231 |
+
robot_future_latents, noise_video, timestep_video
|
| 1232 |
+
)
|
| 1233 |
+
target_action = self.train_action_scheduler.training_target(
|
| 1234 |
+
robot_future_action, noise_action, timestep_action
|
| 1235 |
+
)
|
| 1236 |
+
|
| 1237 |
+
if human_mask is None:
|
| 1238 |
+
human_mask = self.sample_human_mask(batch, device=device, generator=generator)
|
| 1239 |
+
|
| 1240 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1241 |
+
robot_current_latent=robot_current_latent,
|
| 1242 |
+
human_latents=human_latents,
|
| 1243 |
+
noisy_robot_future_latents=noisy_video,
|
| 1244 |
+
noisy_robot_future_action=noisy_action,
|
| 1245 |
+
timestep_video=timestep_video,
|
| 1246 |
+
timestep_action=timestep_action,
|
| 1247 |
+
human_mask=human_mask,
|
| 1248 |
+
human_motion_mask=human_motion_mask,
|
| 1249 |
+
robot_current_state=robot_current_state,
|
| 1250 |
+
human_future_action=human_future_action,
|
| 1251 |
+
)
|
| 1252 |
+
|
| 1253 |
+
# Per-sample means, then the scheduler's timestep weighting -- matching
|
| 1254 |
+
# FastWAM rather than averaging a single scalar over the whole batch.
|
| 1255 |
+
video_per_sample = (pred_video.float() - target_video.float()).pow(2).flatten(1).mean(dim=1)
|
| 1256 |
+
action_per_sample = (
|
| 1257 |
+
(pred_action.float() - target_action.float()).pow(2).flatten(1).mean(dim=1)
|
| 1258 |
+
)
|
| 1259 |
+
video_weight = self.train_video_scheduler.training_weight(timestep_video).to(
|
| 1260 |
+
video_per_sample.device, video_per_sample.dtype
|
| 1261 |
+
)
|
| 1262 |
+
action_weight = self.train_action_scheduler.training_weight(timestep_action).to(
|
| 1263 |
+
action_per_sample.device, action_per_sample.dtype
|
| 1264 |
+
)
|
| 1265 |
+
loss_video = (video_per_sample * video_weight).mean()
|
| 1266 |
+
loss_action = (action_per_sample * action_weight).mean()
|
| 1267 |
+
total = config.loss_lambda_video * loss_video + config.loss_lambda_action * loss_action
|
| 1268 |
+
return total, {
|
| 1269 |
+
"loss_video": loss_video.detach(),
|
| 1270 |
+
"loss_action": loss_action.detach(),
|
| 1271 |
+
"loss_video_unweighted": video_per_sample.mean().detach(),
|
| 1272 |
+
"loss_action_unweighted": action_per_sample.mean().detach(),
|
| 1273 |
+
"human_full_fraction": human_mask.all(dim=1).float().mean().detach(),
|
| 1274 |
+
"human_none_fraction": (~human_mask.any(dim=1)).float().mean().detach(),
|
| 1275 |
+
"human_frames_kept": (
|
| 1276 |
+
human_mask.sum(dim=1).float().mean().detach()
|
| 1277 |
+
if config.use_human_video_context
|
| 1278 |
+
else torch.zeros((), device=device)
|
| 1279 |
+
),
|
| 1280 |
+
}
|
| 1281 |
+
|
| 1282 |
+
@torch.no_grad()
|
| 1283 |
+
def generate(
|
| 1284 |
+
self,
|
| 1285 |
+
*,
|
| 1286 |
+
robot_current_latent: torch.Tensor,
|
| 1287 |
+
human_latents: torch.Tensor,
|
| 1288 |
+
num_inference_steps: int = 20,
|
| 1289 |
+
sigma_shift: Optional[float] = None,
|
| 1290 |
+
generator: Optional[torch.Generator] = None,
|
| 1291 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1292 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1293 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1294 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1295 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1296 |
+
"""FastWAM-style joint flow integration in latent + action space.
|
| 1297 |
+
|
| 1298 |
+
This is the latent-space core and returns
|
| 1299 |
+
(robot_future_latents, normalized robot_future_state). It does not touch
|
| 1300 |
+
the VAE, which lives outside the model so DDP never syncs its 705M frozen
|
| 1301 |
+
parameters. For RGB frames and un-normalized state use
|
| 1302 |
+
`fasterwam.models.hr_inference.generate_rollout`.
|
| 1303 |
+
|
| 1304 |
+
`human_mask` is [B, 1+K] and controls human video steps.
|
| 1305 |
+
`human_motion_mask` controls the 84-D motion tokens mapped to those
|
| 1306 |
+
steps. It defaults to `human_mask` for the standard model and to an
|
| 1307 |
+
all-False mask for a configured human-video-only model.
|
| 1308 |
+
"""
|
| 1309 |
+
|
| 1310 |
+
config = self.config
|
| 1311 |
+
batch = robot_current_latent.shape[0]
|
| 1312 |
+
device = robot_current_latent.device
|
| 1313 |
+
dtype = robot_current_latent.dtype
|
| 1314 |
+
|
| 1315 |
+
latents_video = torch.randn(
|
| 1316 |
+
(
|
| 1317 |
+
batch,
|
| 1318 |
+
config.num_horizons,
|
| 1319 |
+
config.latent_channels,
|
| 1320 |
+
config.latent_height,
|
| 1321 |
+
config.latent_width,
|
| 1322 |
+
),
|
| 1323 |
+
device=device,
|
| 1324 |
+
dtype=dtype,
|
| 1325 |
+
generator=generator,
|
| 1326 |
+
)
|
| 1327 |
+
latents_action = torch.randn(
|
| 1328 |
+
(batch, config.num_action_tokens, config.action_dim),
|
| 1329 |
+
device=device,
|
| 1330 |
+
dtype=dtype,
|
| 1331 |
+
generator=generator,
|
| 1332 |
+
)
|
| 1333 |
+
|
| 1334 |
+
timesteps_video, deltas_video = self.infer_video_scheduler.build_inference_schedule(
|
| 1335 |
+
num_inference_steps=num_inference_steps,
|
| 1336 |
+
device=device,
|
| 1337 |
+
dtype=dtype,
|
| 1338 |
+
shift_override=sigma_shift,
|
| 1339 |
+
)
|
| 1340 |
+
timesteps_action, deltas_action = self.infer_action_scheduler.build_inference_schedule(
|
| 1341 |
+
num_inference_steps=num_inference_steps,
|
| 1342 |
+
device=device,
|
| 1343 |
+
dtype=dtype,
|
| 1344 |
+
shift_override=sigma_shift,
|
| 1345 |
+
)
|
| 1346 |
+
|
| 1347 |
+
for step in range(num_inference_steps):
|
| 1348 |
+
step_t_video = timesteps_video[step].expand(batch)
|
| 1349 |
+
step_t_action = timesteps_action[step].expand(batch)
|
| 1350 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1351 |
+
robot_current_latent=robot_current_latent,
|
| 1352 |
+
human_latents=human_latents,
|
| 1353 |
+
noisy_robot_future_latents=latents_video,
|
| 1354 |
+
noisy_robot_future_action=latents_action,
|
| 1355 |
+
timestep_video=step_t_video,
|
| 1356 |
+
timestep_action=step_t_action,
|
| 1357 |
+
human_mask=human_mask,
|
| 1358 |
+
human_motion_mask=human_motion_mask,
|
| 1359 |
+
robot_current_state=robot_current_state,
|
| 1360 |
+
human_future_action=human_future_action,
|
| 1361 |
+
)
|
| 1362 |
+
latents_video = self.infer_video_scheduler.step(
|
| 1363 |
+
pred_video, deltas_video[step], latents_video
|
| 1364 |
+
)
|
| 1365 |
+
latents_action = self.infer_action_scheduler.step(
|
| 1366 |
+
pred_action, deltas_action[step], latents_action
|
| 1367 |
+
)
|
| 1368 |
+
return latents_video, latents_action
|
| 1369 |
+
|
| 1370 |
+
def forward(self, *args, **kwargs):
|
| 1371 |
+
return self.training_loss(*args, **kwargs)
|
| 1372 |
+
|
| 1373 |
+
|
| 1374 |
+
def count_parameters(model: nn.Module) -> int:
|
| 1375 |
+
return sum(parameter.numel() for parameter in model.parameters())
|
| 1376 |
+
|
| 1377 |
+
|
| 1378 |
+
def parameter_breakdown(model: HRMoTFlowModel) -> dict[str, int]:
|
| 1379 |
+
return {
|
| 1380 |
+
"total": count_parameters(model),
|
| 1381 |
+
"video_expert": count_parameters(model.video_expert),
|
| 1382 |
+
"action_expert": count_parameters(model.action_expert),
|
| 1383 |
+
"video_blocks": sum(count_parameters(b) for b in model.video_expert.blocks),
|
| 1384 |
+
"action_blocks": sum(count_parameters(b) for b in model.action_expert.blocks),
|
| 1385 |
+
}
|
tools/model_code/recorded/coupling/wan22/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/coupling/wan22/helpers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/coupling/wan22/helpers/gradient.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def create_custom_forward(module):
|
| 5 |
+
def custom_forward(*inputs, **kwargs):
|
| 6 |
+
return module(*inputs, **kwargs)
|
| 7 |
+
|
| 8 |
+
return custom_forward
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def gradient_checkpoint_forward(
|
| 12 |
+
model,
|
| 13 |
+
use_gradient_checkpointing,
|
| 14 |
+
*args,
|
| 15 |
+
**kwargs,
|
| 16 |
+
):
|
| 17 |
+
if use_gradient_checkpointing:
|
| 18 |
+
model_output = torch.utils.checkpoint.checkpoint(
|
| 19 |
+
create_custom_forward(model),
|
| 20 |
+
*args,
|
| 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Dict, Optional, Sequence
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
import torch.nn.functional as F
|
| 8 |
+
|
| 9 |
+
from .wan_video_dit import flash_attention, modulate, rope_apply
|
| 10 |
+
from logging import getLogger as get_logger
|
| 11 |
+
|
| 12 |
+
logger = get_logger(__name__)
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class MoT(nn.Module):
|
| 16 |
+
def __init__(
|
| 17 |
+
self,
|
| 18 |
+
mixtures: Dict[str, nn.Module],
|
| 19 |
+
mot_checkpoint_mixed_attn: bool = True,
|
| 20 |
+
mixed_attention_type: str = "softmax",
|
| 21 |
+
):
|
| 22 |
+
super().__init__()
|
| 23 |
+
if not mixtures:
|
| 24 |
+
raise ValueError("`mixtures` cannot be empty.")
|
| 25 |
+
if "video" not in mixtures or "action" not in mixtures:
|
| 26 |
+
raise ValueError("`mixtures` must include both 'video' and 'action' experts.")
|
| 27 |
+
|
| 28 |
+
self.mixtures = nn.ModuleDict(mixtures)
|
| 29 |
+
self.expert_order = list(self.mixtures.keys())
|
| 30 |
+
self.mot_checkpoint_mixed_attn = mot_checkpoint_mixed_attn
|
| 31 |
+
self.mixed_attention_type = str(mixed_attention_type)
|
| 32 |
+
if self.mixed_attention_type not in {"softmax", "linear"}:
|
| 33 |
+
raise ValueError(
|
| 34 |
+
"mixed_attention_type must be 'softmax' or 'linear', got "
|
| 35 |
+
f"{self.mixed_attention_type!r}"
|
| 36 |
+
)
|
| 37 |
+
if mot_checkpoint_mixed_attn:
|
| 38 |
+
logger.info(
|
| 39 |
+
"Using gradient checkpointing for mixture attention. This will save memory but use more computation."
|
| 40 |
+
)
|
| 41 |
+
|
| 42 |
+
first_expert = self.mixtures[self.expert_order[0]]
|
| 43 |
+
self.num_layers = len(first_expert.blocks)
|
| 44 |
+
self.num_heads = first_expert.num_heads
|
| 45 |
+
self.attn_head_dim = first_expert.attn_head_dim
|
| 46 |
+
|
| 47 |
+
for name in self.expert_order[1:]:
|
| 48 |
+
expert = self.mixtures[name]
|
| 49 |
+
if len(expert.blocks) != self.num_layers:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
f"All experts must have same number of layers; got {self.num_layers} and {len(expert.blocks)}"
|
| 52 |
+
)
|
| 53 |
+
if expert.num_heads != self.num_heads:
|
| 54 |
+
raise ValueError(
|
| 55 |
+
f"All experts must have same num_heads; got {self.num_heads} and {expert.num_heads}"
|
| 56 |
+
)
|
| 57 |
+
if expert.attn_head_dim != self.attn_head_dim:
|
| 58 |
+
raise ValueError(
|
| 59 |
+
"All experts must have same attn_head_dim; "
|
| 60 |
+
f"got {self.attn_head_dim} and {expert.attn_head_dim}"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
logger.info(
|
| 64 |
+
f"Initialized MoT with experts: {self.expert_order}, num_layers={self.num_layers}"
|
| 65 |
+
)
|
| 66 |
+
for name in self.expert_order:
|
| 67 |
+
expert = self.mixtures[name]
|
| 68 |
+
logger.info(
|
| 69 |
+
f" Expert '{name}': num_params={sum(p.numel() for p in expert.parameters()) / 1e9:.2f} B"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
@staticmethod
|
| 73 |
+
def _split_modulation(block, t_mod: torch.Tensor):
|
| 74 |
+
has_seq = len(t_mod.shape) == 4
|
| 75 |
+
chunk_dim = 2 if has_seq else 1
|
| 76 |
+
|
| 77 |
+
base_mod = block.modulation.to(dtype=t_mod.dtype, device=t_mod.device)
|
| 78 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (base_mod + t_mod).chunk(
|
| 79 |
+
6, dim=chunk_dim
|
| 80 |
+
)
|
| 81 |
+
if has_seq:
|
| 82 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 83 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 84 |
+
shift_msa.squeeze(2),
|
| 85 |
+
scale_msa.squeeze(2),
|
| 86 |
+
gate_msa.squeeze(2),
|
| 87 |
+
shift_mlp.squeeze(2),
|
| 88 |
+
scale_mlp.squeeze(2),
|
| 89 |
+
gate_mlp.squeeze(2),
|
| 90 |
+
)
|
| 91 |
+
return shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp
|
| 92 |
+
|
| 93 |
+
def _mixed_attention(
|
| 94 |
+
self,
|
| 95 |
+
q_cat: torch.Tensor,
|
| 96 |
+
k_cat: torch.Tensor,
|
| 97 |
+
v_cat: torch.Tensor,
|
| 98 |
+
attention_mask: torch.Tensor,
|
| 99 |
+
linear_attention_groups: Optional[Dict[str, torch.Tensor]] = None,
|
| 100 |
+
linear_q_den: Optional[torch.Tensor] = None,
|
| 101 |
+
linear_k_den: Optional[torch.Tensor] = None,
|
| 102 |
+
) -> torch.Tensor:
|
| 103 |
+
attn_mask = attention_mask.to(device=q_cat.device)
|
| 104 |
+
|
| 105 |
+
def _forward(
|
| 106 |
+
q: torch.Tensor,
|
| 107 |
+
k: torch.Tensor,
|
| 108 |
+
v: torch.Tensor,
|
| 109 |
+
q_den: torch.Tensor,
|
| 110 |
+
k_den: torch.Tensor,
|
| 111 |
+
) -> torch.Tensor:
|
| 112 |
+
if self.mixed_attention_type == "linear":
|
| 113 |
+
if linear_attention_groups is None:
|
| 114 |
+
raise ValueError(
|
| 115 |
+
"linear mixed attention requires explicit condition/prediction/missing groups"
|
| 116 |
+
)
|
| 117 |
+
return self._linear_mixed_attention(q, k, v, q_den, k_den, linear_attention_groups)
|
| 118 |
+
return flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=attn_mask)
|
| 119 |
+
|
| 120 |
+
if self.mixed_attention_type == "linear":
|
| 121 |
+
if linear_q_den is None or linear_k_den is None:
|
| 122 |
+
raise ValueError("linear attention requires unrotated denominator features")
|
| 123 |
+
q_den = linear_q_den
|
| 124 |
+
k_den = linear_k_den
|
| 125 |
+
else:
|
| 126 |
+
# These arguments are ignored by the softmax branch, but passing
|
| 127 |
+
# tensors keeps the checkpoint closure explicit and gradient-safe.
|
| 128 |
+
q_den = q_cat
|
| 129 |
+
k_den = k_cat
|
| 130 |
+
|
| 131 |
+
if self.mot_checkpoint_mixed_attn and self.training:
|
| 132 |
+
return torch.utils.checkpoint.checkpoint(
|
| 133 |
+
_forward,
|
| 134 |
+
q_cat,
|
| 135 |
+
k_cat,
|
| 136 |
+
v_cat,
|
| 137 |
+
q_den,
|
| 138 |
+
k_den,
|
| 139 |
+
use_reentrant=False,
|
| 140 |
+
)
|
| 141 |
+
return _forward(q_cat, k_cat, v_cat, q_den, k_den)
|
| 142 |
+
|
| 143 |
+
def _linear_mixed_attention(
|
| 144 |
+
self,
|
| 145 |
+
q_cat: torch.Tensor,
|
| 146 |
+
k_cat: torch.Tensor,
|
| 147 |
+
v_cat: torch.Tensor,
|
| 148 |
+
q_den_cat: torch.Tensor,
|
| 149 |
+
k_den_cat: torch.Tensor,
|
| 150 |
+
groups: Dict[str, torch.Tensor],
|
| 151 |
+
) -> torch.Tensor:
|
| 152 |
+
"""Normalized ELU+1 linear attention with the H&R visibility contract.
|
| 153 |
+
|
| 154 |
+
Valid condition queries read valid condition keys. Prediction queries
|
| 155 |
+
read valid conditions plus every prediction. Missing-condition queries
|
| 156 |
+
read only themselves and are never exposed as keys to another token.
|
| 157 |
+
The sufficient statistics are accumulated in FP32 for stability, then
|
| 158 |
+
cast back to the input dtype. This is O(S * Dh^2), not O(S^2 * Dh).
|
| 159 |
+
"""
|
| 160 |
+
|
| 161 |
+
batch, seq_len, packed = q_cat.shape
|
| 162 |
+
if packed != self.num_heads * self.attn_head_dim:
|
| 163 |
+
raise ValueError(
|
| 164 |
+
f"packed attention dim {packed} != heads*head_dim "
|
| 165 |
+
f"{self.num_heads * self.attn_head_dim}"
|
| 166 |
+
)
|
| 167 |
+
required = {"condition", "prediction", "missing"}
|
| 168 |
+
if set(groups) != required:
|
| 169 |
+
raise ValueError(
|
| 170 |
+
f"linear_attention_groups must have exactly {sorted(required)}, got {sorted(groups)}"
|
| 171 |
+
)
|
| 172 |
+
normalized = {}
|
| 173 |
+
for name in required:
|
| 174 |
+
value = groups[name].to(device=q_cat.device, dtype=torch.bool)
|
| 175 |
+
if value.shape != (batch, seq_len):
|
| 176 |
+
raise ValueError(
|
| 177 |
+
f"linear_attention_groups[{name!r}] must be [B,S] "
|
| 178 |
+
f"= {(batch, seq_len)}, got {tuple(value.shape)}"
|
| 179 |
+
)
|
| 180 |
+
normalized[name] = value
|
| 181 |
+
membership = sum(value.to(torch.int8) for value in normalized.values())
|
| 182 |
+
if not bool((membership == 1).all()):
|
| 183 |
+
raise ValueError("linear attention groups must partition every token exactly once")
|
| 184 |
+
|
| 185 |
+
q_num = q_cat.reshape(batch, seq_len, self.num_heads, self.attn_head_dim)
|
| 186 |
+
k_num = k_cat.reshape(batch, seq_len, self.num_heads, self.attn_head_dim)
|
| 187 |
+
q_den = q_den_cat.reshape(batch, seq_len, self.num_heads, self.attn_head_dim)
|
| 188 |
+
k_den = k_den_cat.reshape(batch, seq_len, self.num_heads, self.attn_head_dim)
|
| 189 |
+
|
| 190 |
+
def pooled(pool: torch.Tensor) -> torch.Tensor:
|
| 191 |
+
weight = pool[:, :, None, None].to(k_num.dtype)
|
| 192 |
+
selected_k_num = k_num * weight
|
| 193 |
+
selected_k_den = k_den * weight
|
| 194 |
+
kv = torch.einsum("bshd,bshe->bhde", selected_k_num, v_float)
|
| 195 |
+
k_sum = selected_k_den.sum(dim=1)
|
| 196 |
+
numerator = torch.einsum("bshd,bhde->bshe", q_num, kv)
|
| 197 |
+
denominator = torch.einsum("bshd,bhd->bsh", q_den, k_sum).unsqueeze(-1)
|
| 198 |
+
return numerator / denominator.clamp_min(1e-6)
|
| 199 |
+
|
| 200 |
+
# CUDA autocast would otherwise silently execute einsum in BF16 even
|
| 201 |
+
# when its inputs were explicitly converted to float. The sufficient
|
| 202 |
+
# statistics and normalization are intentionally FP32.
|
| 203 |
+
with torch.autocast(device_type=q_cat.device.type, enabled=False):
|
| 204 |
+
q_num = q_num.float()
|
| 205 |
+
k_num = k_num.float()
|
| 206 |
+
q_den = q_den.float()
|
| 207 |
+
k_den = k_den.float()
|
| 208 |
+
v_float = v_cat.reshape(batch, seq_len, self.num_heads, self.attn_head_dim).float()
|
| 209 |
+
condition_out = pooled(normalized["condition"])
|
| 210 |
+
readable = normalized["condition"] | normalized["prediction"]
|
| 211 |
+
prediction_out = pooled(readable)
|
| 212 |
+
# A missing condition has a diagonal-only row in the canonical
|
| 213 |
+
# mask, so its output is exactly its own value.
|
| 214 |
+
output = torch.where(normalized["condition"][:, :, None, None], condition_out, v_float)
|
| 215 |
+
output = torch.where(normalized["prediction"][:, :, None, None], prediction_out, output)
|
| 216 |
+
return output.to(q_cat.dtype).reshape(batch, seq_len, packed)
|
| 217 |
+
|
| 218 |
+
def _resolve_attention_masks(
|
| 219 |
+
self,
|
| 220 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 221 |
+
expected_seq_len: int,
|
| 222 |
+
) -> list[torch.Tensor]:
|
| 223 |
+
if isinstance(attention_mask, torch.Tensor):
|
| 224 |
+
attention_masks = [attention_mask] * self.num_layers
|
| 225 |
+
else:
|
| 226 |
+
attention_masks = list(attention_mask)
|
| 227 |
+
if len(attention_masks) != self.num_layers:
|
| 228 |
+
raise ValueError(
|
| 229 |
+
f"`attention_mask` must contain {self.num_layers} layers, got {len(attention_masks)}."
|
| 230 |
+
)
|
| 231 |
+
|
| 232 |
+
for layer_idx, layer_mask in enumerate(attention_masks):
|
| 233 |
+
if not isinstance(layer_mask, torch.Tensor):
|
| 234 |
+
raise ValueError(
|
| 235 |
+
f"`attention_mask[{layer_idx}]` must be torch.Tensor, got {type(layer_mask)}."
|
| 236 |
+
)
|
| 237 |
+
# [S,S] shares one mask across the batch; [B,S,S] and [B,1,S,S] give a
|
| 238 |
+
# per-sample mask, which is what a per-sample condition-availability
|
| 239 |
+
# pattern needs. All three broadcast correctly in
|
| 240 |
+
# scaled_dot_product_attention against q of shape [B,heads,S,D].
|
| 241 |
+
if layer_mask.ndim not in (2, 3, 4):
|
| 242 |
+
raise ValueError(
|
| 243 |
+
f"`attention_mask[{layer_idx}]` must be [S,S], [B,S,S] or [B,1,S,S], "
|
| 244 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 245 |
+
)
|
| 246 |
+
if layer_mask.shape[-1] != layer_mask.shape[-2]:
|
| 247 |
+
raise ValueError(
|
| 248 |
+
f"`attention_mask[{layer_idx}]` must be square in its last two dims, "
|
| 249 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 250 |
+
)
|
| 251 |
+
if layer_mask.shape[-1] != expected_seq_len:
|
| 252 |
+
raise ValueError(
|
| 253 |
+
f"`attention_mask[{layer_idx}]` seq length mismatch: "
|
| 254 |
+
f"mask={layer_mask.shape[-1]} vs expected_total={expected_seq_len}"
|
| 255 |
+
)
|
| 256 |
+
return attention_masks
|
| 257 |
+
|
| 258 |
+
@staticmethod
|
| 259 |
+
def _apply_expert_post_block(
|
| 260 |
+
block,
|
| 261 |
+
residual_x: torch.Tensor,
|
| 262 |
+
mixed_attn_out: torch.Tensor,
|
| 263 |
+
gate_msa: torch.Tensor,
|
| 264 |
+
shift_mlp: torch.Tensor,
|
| 265 |
+
scale_mlp: torch.Tensor,
|
| 266 |
+
gate_mlp: torch.Tensor,
|
| 267 |
+
context_payload: Optional[dict],
|
| 268 |
+
) -> torch.Tensor:
|
| 269 |
+
x = block.gate(residual_x, gate_msa, block.self_attn.o(mixed_attn_out))
|
| 270 |
+
|
| 271 |
+
if context_payload is not None:
|
| 272 |
+
context = context_payload.get("context")
|
| 273 |
+
if context is not None:
|
| 274 |
+
context_mask = context_payload.get("mask")
|
| 275 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 276 |
+
context_mask = context_mask.unsqueeze(1)
|
| 277 |
+
x = x + block.cross_attn(block.norm3(x), context, ctx_mask=context_mask)
|
| 278 |
+
|
| 279 |
+
mlp_input = modulate(block.norm2(x), shift_mlp, scale_mlp)
|
| 280 |
+
x = block.gate(x, gate_mlp, block.ffn(mlp_input))
|
| 281 |
+
return x
|
| 282 |
+
|
| 283 |
+
def _build_expert_attention_io(
|
| 284 |
+
self,
|
| 285 |
+
expert,
|
| 286 |
+
block,
|
| 287 |
+
x: torch.Tensor,
|
| 288 |
+
freqs: torch.Tensor,
|
| 289 |
+
t_mod: torch.Tensor,
|
| 290 |
+
) -> tuple[
|
| 291 |
+
torch.Tensor,
|
| 292 |
+
torch.Tensor,
|
| 293 |
+
torch.Tensor,
|
| 294 |
+
torch.Tensor,
|
| 295 |
+
torch.Tensor,
|
| 296 |
+
torch.Tensor,
|
| 297 |
+
torch.Tensor,
|
| 298 |
+
torch.Tensor,
|
| 299 |
+
torch.Tensor,
|
| 300 |
+
torch.Tensor,
|
| 301 |
+
bool,
|
| 302 |
+
]:
|
| 303 |
+
"""Build per-expert attention tensors and post-block states.
|
| 304 |
+
|
| 305 |
+
Args:
|
| 306 |
+
expert: Expert module that owns this `block`; only used to read
|
| 307 |
+
`use_gradient_checkpointing`.
|
| 308 |
+
block: Transformer block for current layer (`expert.blocks[layer_idx]`).
|
| 309 |
+
x: Current expert tokens, shape [B, S, D].
|
| 310 |
+
freqs: RoPE frequencies aligned with token sequence, shape [S, 1, rope_dim].
|
| 311 |
+
t_mod: Time modulation tensor for this expert/layer.
|
| 312 |
+
|
| 313 |
+
Returns:
|
| 314 |
+
q: Query used by the attention numerator, shape [B, S, H*Dh].
|
| 315 |
+
k: Key used by the attention numerator, shape [B, S, H*Dh].
|
| 316 |
+
v: Value after v-proj, shape [B, S, H*Dh].
|
| 317 |
+
q_den: Query used by the linear-attention denominator.
|
| 318 |
+
k_den: Key used by the linear-attention denominator.
|
| 319 |
+
residual_x: Original input `x` for residual path in post block.
|
| 320 |
+
gate_msa: Gating tensor for self-attention residual branch.
|
| 321 |
+
shift_mlp: Shift tensor for MLP modulation.
|
| 322 |
+
scale_mlp: Scale tensor for MLP modulation.
|
| 323 |
+
gate_mlp: Gating tensor for MLP residual branch.
|
| 324 |
+
use_gradient_checkpointing: Whether this expert enables checkpointing.
|
| 325 |
+
"""
|
| 326 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self._split_modulation(
|
| 327 |
+
block, t_mod
|
| 328 |
+
)
|
| 329 |
+
attn_input = modulate(block.norm1(x), shift_msa, scale_msa)
|
| 330 |
+
|
| 331 |
+
q = block.self_attn.norm_q(block.self_attn.q(attn_input))
|
| 332 |
+
k = block.self_attn.norm_k(block.self_attn.k(attn_input))
|
| 333 |
+
v = block.self_attn.v(attn_input)
|
| 334 |
+
|
| 335 |
+
if self.mixed_attention_type == "linear":
|
| 336 |
+
# RoFormer-compatible linear RoPE: rotate the positive feature map
|
| 337 |
+
# in the numerator, but keep its unrotated version in the positive
|
| 338 |
+
# denominator. Do all feature preparation outside autocast.
|
| 339 |
+
with torch.autocast(device_type=q.device.type, enabled=False):
|
| 340 |
+
q_den = F.elu(q.float()) + 1.0
|
| 341 |
+
k_den = F.elu(k.float()) + 1.0
|
| 342 |
+
q = rope_apply(q_den, freqs, block.num_heads)
|
| 343 |
+
k = rope_apply(k_den, freqs, block.num_heads)
|
| 344 |
+
else:
|
| 345 |
+
q = rope_apply(q, freqs, block.num_heads)
|
| 346 |
+
k = rope_apply(k, freqs, block.num_heads)
|
| 347 |
+
q_den = q
|
| 348 |
+
k_den = k
|
| 349 |
+
|
| 350 |
+
use_gradient_checkpointing = bool(getattr(expert, "use_gradient_checkpointing", False))
|
| 351 |
+
return (
|
| 352 |
+
q,
|
| 353 |
+
k,
|
| 354 |
+
v,
|
| 355 |
+
q_den,
|
| 356 |
+
k_den,
|
| 357 |
+
x,
|
| 358 |
+
gate_msa,
|
| 359 |
+
shift_mlp,
|
| 360 |
+
scale_mlp,
|
| 361 |
+
gate_mlp,
|
| 362 |
+
use_gradient_checkpointing,
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
def _apply_post_with_optional_checkpoint(
|
| 366 |
+
self,
|
| 367 |
+
block,
|
| 368 |
+
residual_x: torch.Tensor,
|
| 369 |
+
gate_msa: torch.Tensor,
|
| 370 |
+
shift_mlp: torch.Tensor,
|
| 371 |
+
scale_mlp: torch.Tensor,
|
| 372 |
+
gate_mlp: torch.Tensor,
|
| 373 |
+
use_gradient_checkpointing: bool,
|
| 374 |
+
mixed_slice: torch.Tensor,
|
| 375 |
+
context_payload: Optional[dict],
|
| 376 |
+
) -> torch.Tensor:
|
| 377 |
+
"""Apply post-attention computations, with optional checkpointing.
|
| 378 |
+
|
| 379 |
+
Args:
|
| 380 |
+
block: Transformer block for current layer.
|
| 381 |
+
residual_x: Residual input tokens before attention update, shape [B, S, D].
|
| 382 |
+
gate_msa: Gating tensor used after mixed self-attention.
|
| 383 |
+
shift_mlp: Shift tensor for MLP input modulation.
|
| 384 |
+
scale_mlp: Scale tensor for MLP input modulation.
|
| 385 |
+
gate_mlp: Gating tensor used after MLP.
|
| 386 |
+
use_gradient_checkpointing: If True and training, checkpoint this post block.
|
| 387 |
+
mixed_slice: Mixed-attention output for this expert, shape [B, S, H*Dh].
|
| 388 |
+
context_payload: Optional dict for cross-attention.
|
| 389 |
+
- `context`: encoder states [B, L, D]
|
| 390 |
+
- `mask`: attention mask [B, S, L] or [B, 1, S, L]
|
| 391 |
+
|
| 392 |
+
Returns:
|
| 393 |
+
Updated expert tokens after self-attn residual, optional cross-attn, and MLP.
|
| 394 |
+
"""
|
| 395 |
+
|
| 396 |
+
def _post_fn(
|
| 397 |
+
_mixed_slice: torch.Tensor,
|
| 398 |
+
_x: torch.Tensor,
|
| 399 |
+
_gate_msa: torch.Tensor,
|
| 400 |
+
_shift_mlp: torch.Tensor,
|
| 401 |
+
_scale_mlp: torch.Tensor,
|
| 402 |
+
_gate_mlp: torch.Tensor,
|
| 403 |
+
_block=block,
|
| 404 |
+
_context_payload=context_payload,
|
| 405 |
+
) -> torch.Tensor:
|
| 406 |
+
return self._apply_expert_post_block(
|
| 407 |
+
block=_block,
|
| 408 |
+
residual_x=_x,
|
| 409 |
+
mixed_attn_out=_mixed_slice,
|
| 410 |
+
gate_msa=_gate_msa,
|
| 411 |
+
shift_mlp=_shift_mlp,
|
| 412 |
+
scale_mlp=_scale_mlp,
|
| 413 |
+
gate_mlp=_gate_mlp,
|
| 414 |
+
context_payload=_context_payload,
|
| 415 |
+
)
|
| 416 |
+
|
| 417 |
+
if use_gradient_checkpointing and self.training:
|
| 418 |
+
return torch.utils.checkpoint.checkpoint(
|
| 419 |
+
_post_fn,
|
| 420 |
+
mixed_slice,
|
| 421 |
+
residual_x,
|
| 422 |
+
gate_msa,
|
| 423 |
+
shift_mlp,
|
| 424 |
+
scale_mlp,
|
| 425 |
+
gate_mlp,
|
| 426 |
+
use_reentrant=False,
|
| 427 |
+
)
|
| 428 |
+
return _post_fn(
|
| 429 |
+
mixed_slice,
|
| 430 |
+
residual_x,
|
| 431 |
+
gate_msa,
|
| 432 |
+
shift_mlp,
|
| 433 |
+
scale_mlp,
|
| 434 |
+
gate_mlp,
|
| 435 |
+
)
|
| 436 |
+
|
| 437 |
+
def prefill_video_cache(
|
| 438 |
+
self,
|
| 439 |
+
video_tokens: torch.Tensor,
|
| 440 |
+
video_freqs: torch.Tensor,
|
| 441 |
+
video_t_mod: torch.Tensor,
|
| 442 |
+
video_context_payload: Optional[dict],
|
| 443 |
+
video_attention_mask: torch.Tensor,
|
| 444 |
+
) -> list[dict[str, torch.Tensor]]:
|
| 445 |
+
"""Prefill video branch once and cache per-layer K/V for action denoising.
|
| 446 |
+
|
| 447 |
+
Args:
|
| 448 |
+
video_tokens: Video tokens before layer 0, shape [B, Sv, D].
|
| 449 |
+
video_freqs: Video RoPE frequencies, shape [Sv, 1, rope_dim].
|
| 450 |
+
video_t_mod: Video time modulation tensor.
|
| 451 |
+
video_context_payload: Optional dict for video cross-attention.
|
| 452 |
+
- `context`: encoder states [B, L, D]
|
| 453 |
+
- `mask`: attention mask [B, Sv, L] or [B, 1, Sv, L]
|
| 454 |
+
video_attention_mask: Video self-attention mask, shape [Sv, Sv].
|
| 455 |
+
|
| 456 |
+
Returns:
|
| 457 |
+
Layer-wise cache list with length `num_layers`.
|
| 458 |
+
Each entry contains:
|
| 459 |
+
- `k`: video key tensor [B, Sv, H*Dh]
|
| 460 |
+
- `v`: video value tensor [B, Sv, H*Dh]
|
| 461 |
+
"""
|
| 462 |
+
if "video" not in self.mixtures:
|
| 463 |
+
raise ValueError("MoT requires `video` expert for `prefill_video_cache`.")
|
| 464 |
+
if self.mixed_attention_type == "linear":
|
| 465 |
+
raise NotImplementedError(
|
| 466 |
+
"linear mixed attention does not support the legacy video K/V cache; "
|
| 467 |
+
"use the full joint-sequence forward path"
|
| 468 |
+
)
|
| 469 |
+
if video_attention_mask.ndim != 2:
|
| 470 |
+
raise ValueError(
|
| 471 |
+
f"`video_attention_mask` must be 2D [S,S], got shape {tuple(video_attention_mask.shape)}"
|
| 472 |
+
)
|
| 473 |
+
if video_attention_mask.shape[0] != video_attention_mask.shape[1]:
|
| 474 |
+
raise ValueError(
|
| 475 |
+
f"`video_attention_mask` must be square, got shape {tuple(video_attention_mask.shape)}"
|
| 476 |
+
)
|
| 477 |
+
if video_attention_mask.shape[0] != video_tokens.shape[1]:
|
| 478 |
+
raise ValueError(
|
| 479 |
+
"`video_attention_mask` seq length mismatch: "
|
| 480 |
+
f"mask={video_attention_mask.shape[0]} vs tokens={video_tokens.shape[1]}"
|
| 481 |
+
)
|
| 482 |
+
|
| 483 |
+
expert = self.mixtures["video"]
|
| 484 |
+
x = video_tokens
|
| 485 |
+
kv_cache: list[dict[str, torch.Tensor]] = []
|
| 486 |
+
for layer_idx in range(self.num_layers):
|
| 487 |
+
block = expert.blocks[layer_idx]
|
| 488 |
+
# Build video Q/K/V from current layer input tokens.
|
| 489 |
+
(
|
| 490 |
+
q,
|
| 491 |
+
k,
|
| 492 |
+
v,
|
| 493 |
+
q_den,
|
| 494 |
+
k_den,
|
| 495 |
+
residual_x,
|
| 496 |
+
gate_msa,
|
| 497 |
+
shift_mlp,
|
| 498 |
+
scale_mlp,
|
| 499 |
+
gate_mlp,
|
| 500 |
+
use_gradient_checkpointing,
|
| 501 |
+
) = self._build_expert_attention_io(
|
| 502 |
+
expert=expert,
|
| 503 |
+
block=block,
|
| 504 |
+
x=x,
|
| 505 |
+
freqs=video_freqs,
|
| 506 |
+
t_mod=video_t_mod,
|
| 507 |
+
)
|
| 508 |
+
# Video prefill uses only video self-attention mask.
|
| 509 |
+
mixed = self._mixed_attention(
|
| 510 |
+
q_cat=q,
|
| 511 |
+
k_cat=k,
|
| 512 |
+
v_cat=v,
|
| 513 |
+
attention_mask=video_attention_mask,
|
| 514 |
+
)
|
| 515 |
+
# Update video tokens for the next layer and persist current layer K/V.
|
| 516 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 517 |
+
block=block,
|
| 518 |
+
residual_x=residual_x,
|
| 519 |
+
gate_msa=gate_msa,
|
| 520 |
+
shift_mlp=shift_mlp,
|
| 521 |
+
scale_mlp=scale_mlp,
|
| 522 |
+
gate_mlp=gate_mlp,
|
| 523 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 524 |
+
mixed_slice=mixed,
|
| 525 |
+
context_payload=video_context_payload,
|
| 526 |
+
)
|
| 527 |
+
kv_cache.append({"k": k, "v": v})
|
| 528 |
+
return kv_cache
|
| 529 |
+
|
| 530 |
+
def forward_action_with_video_cache(
|
| 531 |
+
self,
|
| 532 |
+
action_tokens: torch.Tensor,
|
| 533 |
+
action_freqs: torch.Tensor,
|
| 534 |
+
action_t_mod: torch.Tensor,
|
| 535 |
+
action_context_payload: Optional[dict],
|
| 536 |
+
video_kv_cache: list[dict[str, torch.Tensor]],
|
| 537 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 538 |
+
video_seq_len: int,
|
| 539 |
+
) -> torch.Tensor:
|
| 540 |
+
"""Run action branch with cached video K/V instead of recomputing video tokens.
|
| 541 |
+
|
| 542 |
+
Args:
|
| 543 |
+
action_tokens: Action tokens before layer 0, shape [B, Sa, D].
|
| 544 |
+
action_freqs: Action RoPE frequencies, shape [Sa, 1, rope_dim].
|
| 545 |
+
action_t_mod: Action time modulation tensor.
|
| 546 |
+
action_context_payload: Optional dict for action cross-attention.
|
| 547 |
+
- `context`: encoder states [B, L, D]
|
| 548 |
+
- `mask`: attention mask [B, Sa, L] or [B, 1, Sa, L]
|
| 549 |
+
video_kv_cache: Layer-wise cached video K/V from `prefill_video_cache`.
|
| 550 |
+
attention_mask: Joint [video+action] mask, shape [Sv+Sa, Sv+Sa].
|
| 551 |
+
video_seq_len: Video token count `Sv` in the joint sequence prefix.
|
| 552 |
+
|
| 553 |
+
Returns:
|
| 554 |
+
Updated action tokens after all layers, shape [B, Sa, D].
|
| 555 |
+
"""
|
| 556 |
+
if "action" not in self.mixtures:
|
| 557 |
+
raise ValueError("MoT requires `action` expert for `forward_action_with_video_cache`.")
|
| 558 |
+
if self.mixed_attention_type == "linear":
|
| 559 |
+
raise NotImplementedError(
|
| 560 |
+
"linear mixed attention does not support the legacy video K/V cache; "
|
| 561 |
+
"use the full joint-sequence forward path"
|
| 562 |
+
)
|
| 563 |
+
if len(video_kv_cache) != self.num_layers:
|
| 564 |
+
raise ValueError(
|
| 565 |
+
f"`video_kv_cache` must contain {self.num_layers} layers, got {len(video_kv_cache)}."
|
| 566 |
+
)
|
| 567 |
+
|
| 568 |
+
action_seq_len = int(action_tokens.shape[1])
|
| 569 |
+
total_seq_len = int(video_seq_len) + action_seq_len
|
| 570 |
+
attention_masks = self._resolve_attention_masks(
|
| 571 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 572 |
+
)
|
| 573 |
+
|
| 574 |
+
expert = self.mixtures["action"]
|
| 575 |
+
x = action_tokens
|
| 576 |
+
for layer_idx in range(self.num_layers):
|
| 577 |
+
block = expert.blocks[layer_idx]
|
| 578 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 579 |
+
action_attention_mask = layer_attention_mask[
|
| 580 |
+
video_seq_len:total_seq_len, :total_seq_len
|
| 581 |
+
]
|
| 582 |
+
# Action query/key/value are still step-dependent and must be recomputed each step.
|
| 583 |
+
(
|
| 584 |
+
q_action,
|
| 585 |
+
k_action,
|
| 586 |
+
v_action,
|
| 587 |
+
q_action_den,
|
| 588 |
+
k_action_den,
|
| 589 |
+
residual_x,
|
| 590 |
+
gate_msa,
|
| 591 |
+
shift_mlp,
|
| 592 |
+
scale_mlp,
|
| 593 |
+
gate_mlp,
|
| 594 |
+
use_gradient_checkpointing,
|
| 595 |
+
) = self._build_expert_attention_io(
|
| 596 |
+
expert=expert,
|
| 597 |
+
block=block,
|
| 598 |
+
x=x,
|
| 599 |
+
freqs=action_freqs,
|
| 600 |
+
t_mod=action_t_mod,
|
| 601 |
+
)
|
| 602 |
+
layer_cache = video_kv_cache[layer_idx]
|
| 603 |
+
if "k" not in layer_cache or "v" not in layer_cache:
|
| 604 |
+
raise ValueError(f"`video_kv_cache[{layer_idx}]` must contain `k` and `v`.")
|
| 605 |
+
|
| 606 |
+
k_video = layer_cache["k"]
|
| 607 |
+
v_video = layer_cache["v"]
|
| 608 |
+
if k_video.shape[1] != video_seq_len or v_video.shape[1] != video_seq_len:
|
| 609 |
+
raise ValueError(
|
| 610 |
+
f"`video_kv_cache[{layer_idx}]` seq len mismatch, expected {video_seq_len}."
|
| 611 |
+
)
|
| 612 |
+
|
| 613 |
+
# Mixed attention: action queries attend to cached video K/V plus current action K/V.
|
| 614 |
+
k_cat = torch.cat([k_video, k_action], dim=1)
|
| 615 |
+
v_cat = torch.cat([v_video, v_action], dim=1)
|
| 616 |
+
mixed = self._mixed_attention(
|
| 617 |
+
q_cat=q_action,
|
| 618 |
+
k_cat=k_cat,
|
| 619 |
+
v_cat=v_cat,
|
| 620 |
+
attention_mask=action_attention_mask,
|
| 621 |
+
)
|
| 622 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 623 |
+
block=block,
|
| 624 |
+
residual_x=residual_x,
|
| 625 |
+
gate_msa=gate_msa,
|
| 626 |
+
shift_mlp=shift_mlp,
|
| 627 |
+
scale_mlp=scale_mlp,
|
| 628 |
+
gate_mlp=gate_mlp,
|
| 629 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 630 |
+
mixed_slice=mixed,
|
| 631 |
+
context_payload=action_context_payload,
|
| 632 |
+
)
|
| 633 |
+
return x
|
| 634 |
+
|
| 635 |
+
def forward(
|
| 636 |
+
self,
|
| 637 |
+
embeds_all: Dict[str, torch.Tensor],
|
| 638 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 639 |
+
freqs_all: Dict[str, torch.Tensor],
|
| 640 |
+
context_all: Dict[str, Optional[dict]],
|
| 641 |
+
t_mod_all: Dict[str, torch.Tensor],
|
| 642 |
+
linear_attention_groups: Optional[Dict[str, torch.Tensor]] = None,
|
| 643 |
+
):
|
| 644 |
+
missing = [k for k in self.expert_order if k not in embeds_all]
|
| 645 |
+
if missing:
|
| 646 |
+
raise ValueError(f"Missing expert tokens for {missing}")
|
| 647 |
+
missing = [k for k in self.expert_order if k not in freqs_all]
|
| 648 |
+
if missing:
|
| 649 |
+
raise ValueError(f"Missing expert freqs for {missing}")
|
| 650 |
+
missing = [k for k in self.expert_order if k not in t_mod_all]
|
| 651 |
+
if missing:
|
| 652 |
+
raise ValueError(f"Missing expert t_mod for {missing}")
|
| 653 |
+
|
| 654 |
+
tokens_all = {k: v for k, v in embeds_all.items()}
|
| 655 |
+
total_seq_len = sum(int(tokens_all[name].shape[1]) for name in self.expert_order)
|
| 656 |
+
attention_masks = self._resolve_attention_masks(
|
| 657 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 658 |
+
)
|
| 659 |
+
|
| 660 |
+
for layer_idx in range(self.num_layers):
|
| 661 |
+
q_chunks = []
|
| 662 |
+
k_chunks = []
|
| 663 |
+
v_chunks = []
|
| 664 |
+
q_den_chunks = []
|
| 665 |
+
k_den_chunks = []
|
| 666 |
+
cached = {}
|
| 667 |
+
seq_lens = []
|
| 668 |
+
|
| 669 |
+
for name in self.expert_order:
|
| 670 |
+
expert = self.mixtures[name]
|
| 671 |
+
block = expert.blocks[layer_idx]
|
| 672 |
+
x = tokens_all[name]
|
| 673 |
+
freqs = freqs_all[name]
|
| 674 |
+
t_mod = t_mod_all[name]
|
| 675 |
+
|
| 676 |
+
(
|
| 677 |
+
q,
|
| 678 |
+
k,
|
| 679 |
+
v,
|
| 680 |
+
q_den,
|
| 681 |
+
k_den,
|
| 682 |
+
residual_x,
|
| 683 |
+
gate_msa,
|
| 684 |
+
shift_mlp,
|
| 685 |
+
scale_mlp,
|
| 686 |
+
gate_mlp,
|
| 687 |
+
use_gradient_checkpointing,
|
| 688 |
+
) = self._build_expert_attention_io(
|
| 689 |
+
expert=expert,
|
| 690 |
+
block=block,
|
| 691 |
+
x=x,
|
| 692 |
+
freqs=freqs,
|
| 693 |
+
t_mod=t_mod,
|
| 694 |
+
)
|
| 695 |
+
|
| 696 |
+
q_chunks.append(q)
|
| 697 |
+
k_chunks.append(k)
|
| 698 |
+
v_chunks.append(v)
|
| 699 |
+
q_den_chunks.append(q_den)
|
| 700 |
+
k_den_chunks.append(k_den)
|
| 701 |
+
seq_lens.append(x.shape[1])
|
| 702 |
+
cached[name] = {
|
| 703 |
+
"block": block,
|
| 704 |
+
"residual_x": residual_x,
|
| 705 |
+
"gate_msa": gate_msa,
|
| 706 |
+
"shift_mlp": shift_mlp,
|
| 707 |
+
"scale_mlp": scale_mlp,
|
| 708 |
+
"gate_mlp": gate_mlp,
|
| 709 |
+
"use_gradient_checkpointing": use_gradient_checkpointing,
|
| 710 |
+
}
|
| 711 |
+
|
| 712 |
+
# 3. concat all tokens for mixed attention
|
| 713 |
+
q_cat = torch.cat(q_chunks, dim=1)
|
| 714 |
+
k_cat = torch.cat(k_chunks, dim=1)
|
| 715 |
+
v_cat = torch.cat(v_chunks, dim=1)
|
| 716 |
+
q_den_cat = torch.cat(q_den_chunks, dim=1)
|
| 717 |
+
k_den_cat = torch.cat(k_den_chunks, dim=1)
|
| 718 |
+
|
| 719 |
+
total_seq = q_cat.shape[1]
|
| 720 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 721 |
+
if layer_attention_mask.shape[-1] != total_seq:
|
| 722 |
+
raise ValueError(
|
| 723 |
+
"Attention mask seq length mismatch: "
|
| 724 |
+
f"mask={layer_attention_mask.shape[-1]} vs tokens={total_seq}"
|
| 725 |
+
)
|
| 726 |
+
|
| 727 |
+
mixed = self._mixed_attention(
|
| 728 |
+
q_cat=q_cat,
|
| 729 |
+
k_cat=k_cat,
|
| 730 |
+
v_cat=v_cat,
|
| 731 |
+
attention_mask=layer_attention_mask,
|
| 732 |
+
linear_attention_groups=linear_attention_groups,
|
| 733 |
+
linear_q_den=q_den_cat,
|
| 734 |
+
linear_k_den=k_den_cat,
|
| 735 |
+
)
|
| 736 |
+
|
| 737 |
+
start = 0
|
| 738 |
+
for name, seq_len in zip(self.expert_order, seq_lens):
|
| 739 |
+
# 4. split mixed attention output and apply post-attention blocks for each expert
|
| 740 |
+
end = start + seq_len
|
| 741 |
+
mixed_slice = mixed[:, start:end, :]
|
| 742 |
+
cached_expert = cached[name]
|
| 743 |
+
block = cached_expert["block"]
|
| 744 |
+
context_payload = context_all.get(name)
|
| 745 |
+
|
| 746 |
+
updated_tokens = self._apply_post_with_optional_checkpoint(
|
| 747 |
+
block=block,
|
| 748 |
+
residual_x=cached_expert["residual_x"],
|
| 749 |
+
gate_msa=cached_expert["gate_msa"],
|
| 750 |
+
shift_mlp=cached_expert["shift_mlp"],
|
| 751 |
+
scale_mlp=cached_expert["scale_mlp"],
|
| 752 |
+
gate_mlp=cached_expert["gate_mlp"],
|
| 753 |
+
use_gradient_checkpointing=cached_expert["use_gradient_checkpointing"],
|
| 754 |
+
mixed_slice=mixed_slice,
|
| 755 |
+
context_payload=context_payload,
|
| 756 |
+
)
|
| 757 |
+
|
| 758 |
+
tokens_all[name] = updated_tokens
|
| 759 |
+
start = end
|
| 760 |
+
|
| 761 |
+
return tokens_all
|
tools/model_code/recorded/coupling/wan22/schedulers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/coupling/wan22/schedulers/scheduler_continuous.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class WanContinuousFlowMatchScheduler:
|
| 5 |
+
"""Continuous-time Flow-Matching scheduler with shift-based sampling."""
|
| 6 |
+
|
| 7 |
+
def __init__(self, num_train_timesteps: int = 1000, shift: float = 5.0, eps: float = 1e-10):
|
| 8 |
+
if num_train_timesteps <= 0:
|
| 9 |
+
raise ValueError(f"`num_train_timesteps` must be positive, got {num_train_timesteps}")
|
| 10 |
+
if shift <= 0:
|
| 11 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 12 |
+
self.num_train_timesteps = int(num_train_timesteps)
|
| 13 |
+
self.shift = float(shift)
|
| 14 |
+
self.eps = float(eps)
|
| 15 |
+
self._y_min, self._weight_norm_const = self._precompute_training_weight_stats()
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def _phi(u: torch.Tensor, shift: float) -> torch.Tensor:
|
| 19 |
+
return shift * u / (1.0 + (shift - 1.0) * u)
|
| 20 |
+
|
| 21 |
+
def _precompute_training_weight_stats(self) -> tuple[float, float]:
|
| 22 |
+
steps = self.num_train_timesteps
|
| 23 |
+
u_grid = torch.linspace(1.0, 0.0, steps + 1, dtype=torch.float64)[:-1]
|
| 24 |
+
t_grid = self._phi(u_grid, self.shift) * float(steps)
|
| 25 |
+
y_grid = torch.exp(-2.0 * ((t_grid - (steps / 2.0)) / steps) ** 2)
|
| 26 |
+
y_min = float(y_grid.min().item())
|
| 27 |
+
y_shifted_grid = y_grid - y_min
|
| 28 |
+
norm_const = float(y_shifted_grid.mean().item())
|
| 29 |
+
return y_min, norm_const
|
| 30 |
+
|
| 31 |
+
def sample_training_t(
|
| 32 |
+
self, batch_size: int, device: torch.device, dtype: torch.dtype
|
| 33 |
+
) -> torch.Tensor:
|
| 34 |
+
if batch_size <= 0:
|
| 35 |
+
raise ValueError(f"`batch_size` must be positive, got {batch_size}")
|
| 36 |
+
u = torch.rand((batch_size,), device=device, dtype=torch.float32)
|
| 37 |
+
sigma = self._phi(u, self.shift)
|
| 38 |
+
timestep = sigma * float(self.num_train_timesteps)
|
| 39 |
+
return timestep.to(dtype=dtype)
|
| 40 |
+
|
| 41 |
+
def training_weight(self, timestep: torch.Tensor) -> torch.Tensor:
|
| 42 |
+
t = timestep.to(dtype=torch.float32)
|
| 43 |
+
steps = float(self.num_train_timesteps)
|
| 44 |
+
y = torch.exp(-2.0 * ((t - (steps / 2.0)) / steps) ** 2)
|
| 45 |
+
y_shifted = y - self._y_min
|
| 46 |
+
weight = y_shifted / (self._weight_norm_const + self.eps)
|
| 47 |
+
if weight.numel() == 1:
|
| 48 |
+
return weight.reshape(())
|
| 49 |
+
return weight
|
| 50 |
+
|
| 51 |
+
def add_noise(
|
| 52 |
+
self, original_samples: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 53 |
+
) -> torch.Tensor:
|
| 54 |
+
sigma = (timestep / float(self.num_train_timesteps)).to(
|
| 55 |
+
original_samples.device, dtype=original_samples.dtype
|
| 56 |
+
)
|
| 57 |
+
if sigma.ndim == 0:
|
| 58 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 59 |
+
sigma = sigma.view(-1, *([1] * (original_samples.ndim - 1)))
|
| 60 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def training_target(
|
| 64 |
+
sample: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 65 |
+
) -> torch.Tensor:
|
| 66 |
+
del timestep
|
| 67 |
+
return noise - sample
|
| 68 |
+
|
| 69 |
+
def build_inference_schedule(
|
| 70 |
+
self,
|
| 71 |
+
num_inference_steps: int,
|
| 72 |
+
device: torch.device,
|
| 73 |
+
dtype: torch.dtype,
|
| 74 |
+
shift_override: float | None = None,
|
| 75 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 76 |
+
if num_inference_steps <= 0:
|
| 77 |
+
raise ValueError(f"`num_inference_steps` must be positive, got {num_inference_steps}")
|
| 78 |
+
shift = self.shift if shift_override is None else float(shift_override)
|
| 79 |
+
if shift <= 0:
|
| 80 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 81 |
+
|
| 82 |
+
u_steps = torch.linspace(
|
| 83 |
+
1.0, 0.0, num_inference_steps + 1, device=device, dtype=torch.float32
|
| 84 |
+
)
|
| 85 |
+
sigma_steps = self._phi(u_steps, shift)
|
| 86 |
+
timesteps = sigma_steps[:-1] * float(self.num_train_timesteps)
|
| 87 |
+
deltas = sigma_steps[1:] - sigma_steps[:-1]
|
| 88 |
+
return timesteps.to(dtype=dtype), deltas.to(dtype=dtype)
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def step(model_output: torch.Tensor, delta: torch.Tensor, sample: torch.Tensor) -> torch.Tensor:
|
| 92 |
+
delta = delta.to(sample.device, dtype=sample.dtype)
|
| 93 |
+
if delta.ndim == 0:
|
| 94 |
+
return sample + model_output * delta
|
| 95 |
+
delta = delta.view(-1, *([1] * (sample.ndim - 1)))
|
| 96 |
+
return sample + model_output * delta
|
tools/model_code/recorded/coupling/wan22/wan_video_dit.py
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import math
|
| 5 |
+
from typing import Any, Dict, Tuple, Optional
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from .helpers.gradient import gradient_checkpoint_forward
|
| 8 |
+
|
| 9 |
+
from logging import getLogger as get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def flash_attention(
|
| 15 |
+
q: torch.Tensor,
|
| 16 |
+
k: torch.Tensor,
|
| 17 |
+
v: torch.Tensor,
|
| 18 |
+
num_heads: int,
|
| 19 |
+
ctx_mask: Optional[torch.Tensor] = None,
|
| 20 |
+
compatibility_mode=True,
|
| 21 |
+
):
|
| 22 |
+
if compatibility_mode:
|
| 23 |
+
q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
|
| 24 |
+
k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
|
| 25 |
+
v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
|
| 26 |
+
x = F.scaled_dot_product_attention(q, k, v, attn_mask=ctx_mask)
|
| 27 |
+
x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
|
| 28 |
+
return x
|
| 29 |
+
else:
|
| 30 |
+
raise NotImplementedError(
|
| 31 |
+
"Only compatibility mode is implemented for flash attention. Please set compatibility_mode=True."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor):
|
| 36 |
+
return x * (1 + scale) + shift
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def sinusoidal_embedding_1d(dim, position):
|
| 40 |
+
sinusoid = torch.outer(
|
| 41 |
+
position.type(torch.float64),
|
| 42 |
+
torch.pow(
|
| 43 |
+
10000,
|
| 44 |
+
-torch.arange(dim // 2, dtype=torch.float64, device=position.device).div(dim // 2),
|
| 45 |
+
),
|
| 46 |
+
)
|
| 47 |
+
x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
|
| 48 |
+
return x.to(position.dtype)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def precompute_freqs_cis_3d(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 52 |
+
# 3d rope precompute
|
| 53 |
+
f_freqs_cis = precompute_freqs_cis(dim - 2 * (dim // 3), end, theta)
|
| 54 |
+
h_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 55 |
+
w_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 56 |
+
return f_freqs_cis, h_freqs_cis, w_freqs_cis
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def precompute_freqs_cis(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 60 |
+
# 1d rope precompute
|
| 61 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].double() / dim))
|
| 62 |
+
freqs = torch.outer(torch.arange(end, device=freqs.device), freqs)
|
| 63 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
|
| 64 |
+
return freqs_cis
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def rope_apply(x, freqs, num_heads):
|
| 68 |
+
x = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
|
| 69 |
+
x_out = torch.view_as_complex(
|
| 70 |
+
x.to(torch.float64).reshape(x.shape[0], x.shape[1], x.shape[2], -1, 2)
|
| 71 |
+
)
|
| 72 |
+
freqs = freqs.to(torch.complex64) if freqs.device.type == "npu" else freqs
|
| 73 |
+
x_out = torch.view_as_real(x_out * freqs).flatten(2)
|
| 74 |
+
return x_out.to(x.dtype)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def create_group_causal_attn_mask(
|
| 78 |
+
num_temporal_groups: int, num_query_per_group: int, num_key_per_group: int, mode: str = "causal"
|
| 79 |
+
) -> torch.Tensor:
|
| 80 |
+
"""
|
| 81 |
+
Creates a group-based attention mask for scaled dot-product attention with two modes:
|
| 82 |
+
'causal' and 'group_diagonal'.
|
| 83 |
+
|
| 84 |
+
Parameters:
|
| 85 |
+
- num_temporal_groups (int): The number of temporal groups (e.g., frames in a video sequence).
|
| 86 |
+
- num_query_per_group (int): The number of query tokens per temporal group. (e.g., latent tokens in a frame, H x W).
|
| 87 |
+
- num_key_per_group (int): The number of key tokens per temporal group. (e.g., action tokens per frame).
|
| 88 |
+
- mode (str): The mode of the attention mask. Options are:
|
| 89 |
+
- 'causal': Query tokens can attend to key tokens from the same or previous temporal groups.
|
| 90 |
+
- 'group_diagonal': Query tokens can attend only to key tokens from the same temporal group.
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
- attn_mask (torch.Tensor): A boolean tensor of shape (L, S), where:
|
| 94 |
+
- L = num_temporal_groups * num_query_per_group (total number of query tokens)
|
| 95 |
+
- S = num_temporal_groups * num_key_per_group (total number of key tokens)
|
| 96 |
+
The mask indicates where attention is allowed (True) and disallowed (False).
|
| 97 |
+
|
| 98 |
+
Example:
|
| 99 |
+
Input:
|
| 100 |
+
num_temporal_groups = 3
|
| 101 |
+
num_query_per_group = 4
|
| 102 |
+
num_key_per_group = 2
|
| 103 |
+
Output:
|
| 104 |
+
Causal Mask Shape: torch.Size([12, 6])
|
| 105 |
+
Group Diagonal Mask Shape: torch.Size([12, 6])
|
| 106 |
+
if mode='causal':
|
| 107 |
+
tensor([[ True, True, False, False, False, False],
|
| 108 |
+
[ True, True, False, False, False, False],
|
| 109 |
+
[ True, True, False, False, False, False],
|
| 110 |
+
[ True, True, False, False, False, False],
|
| 111 |
+
[ True, True, True, True, False, False],
|
| 112 |
+
[ True, True, True, True, False, False],
|
| 113 |
+
[ True, True, True, True, False, False],
|
| 114 |
+
[ True, True, True, True, False, False],
|
| 115 |
+
[ True, True, True, True, True, True],
|
| 116 |
+
[ True, True, True, True, True, True],
|
| 117 |
+
[ True, True, True, True, True, True],
|
| 118 |
+
[ True, True, True, True, True, True]])
|
| 119 |
+
|
| 120 |
+
if mode='group_diagonal':
|
| 121 |
+
tensor([[ True, True, False, False, False, False],
|
| 122 |
+
[ True, True, False, False, False, False],
|
| 123 |
+
[ True, True, False, False, False, False],
|
| 124 |
+
[ True, True, False, False, False, False],
|
| 125 |
+
[False, False, True, True, False, False],
|
| 126 |
+
[False, False, True, True, False, False],
|
| 127 |
+
[False, False, True, True, False, False],
|
| 128 |
+
[False, False, True, True, False, False],
|
| 129 |
+
[False, False, False, False, True, True],
|
| 130 |
+
[False, False, False, False, True, True],
|
| 131 |
+
[False, False, False, False, True, True],
|
| 132 |
+
[False, False, False, False, True, True]])
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
assert mode in ["causal", "group_diagonal"], f"Mode {mode} must be 'causal' or 'group_diagonal'"
|
| 136 |
+
|
| 137 |
+
# Total number of query and key tokens
|
| 138 |
+
total_num_query_tokens = (
|
| 139 |
+
num_temporal_groups * num_query_per_group
|
| 140 |
+
) # Total number of query tokens (L)
|
| 141 |
+
total_num_key_tokens = num_temporal_groups * num_key_per_group # Total number of key tokens (S)
|
| 142 |
+
|
| 143 |
+
# Generate time indices for query and key tokens (shape: [L] and [S])
|
| 144 |
+
query_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 145 |
+
num_query_per_group
|
| 146 |
+
) # Shape: [L]
|
| 147 |
+
key_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 148 |
+
num_key_per_group
|
| 149 |
+
) # Shape: [S]
|
| 150 |
+
|
| 151 |
+
# Expand dimensions to compute outer comparison
|
| 152 |
+
query_time_indices = query_time_indices.unsqueeze(1) # Shape: [L, 1]
|
| 153 |
+
key_time_indices = key_time_indices.unsqueeze(0) # Shape: [1, S]
|
| 154 |
+
|
| 155 |
+
if mode == "causal":
|
| 156 |
+
# Causal Mode: Query can attend to keys where key_time <= query_time
|
| 157 |
+
attn_mask = query_time_indices >= key_time_indices # Shape: [L, S]
|
| 158 |
+
elif mode == "group_diagonal":
|
| 159 |
+
# Group Diagonal Mode: Query can attend only to keys where key_time == query_time
|
| 160 |
+
attn_mask = query_time_indices == key_time_indices # Shape: [L, S]
|
| 161 |
+
|
| 162 |
+
assert attn_mask.shape == (
|
| 163 |
+
total_num_query_tokens,
|
| 164 |
+
total_num_key_tokens,
|
| 165 |
+
), "Attention mask shape mismatch"
|
| 166 |
+
return attn_mask
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class RMSNorm(nn.Module):
|
| 170 |
+
def __init__(self, dim, eps=1e-5):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.eps = eps
|
| 173 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 174 |
+
|
| 175 |
+
def norm(self, x):
|
| 176 |
+
return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
|
| 177 |
+
|
| 178 |
+
def forward(self, x):
|
| 179 |
+
dtype = x.dtype
|
| 180 |
+
return self.norm(x.float()).to(dtype) * self.weight
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class AttentionModule(nn.Module):
|
| 184 |
+
def __init__(self, num_heads):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.num_heads = num_heads
|
| 187 |
+
|
| 188 |
+
def forward(self, q, k, v, ctx_mask=None):
|
| 189 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 190 |
+
return x
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SelfAttention(nn.Module):
|
| 194 |
+
def __init__(self, hidden_dim: int, attn_head_dim: int, num_heads: int, eps: float = 1e-6):
|
| 195 |
+
super().__init__()
|
| 196 |
+
self.hidden_dim = hidden_dim
|
| 197 |
+
self.num_heads = num_heads
|
| 198 |
+
self.attn_head_dim = attn_head_dim
|
| 199 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 200 |
+
|
| 201 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 202 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 203 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 204 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 205 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 206 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 207 |
+
|
| 208 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 209 |
+
|
| 210 |
+
def forward(self, x, freqs, self_attn_mask: Optional[torch.Tensor] = None):
|
| 211 |
+
q = self.norm_q(self.q(x))
|
| 212 |
+
k = self.norm_k(self.k(x))
|
| 213 |
+
v = self.v(x)
|
| 214 |
+
q = rope_apply(q, freqs, self.num_heads)
|
| 215 |
+
k = rope_apply(k, freqs, self.num_heads)
|
| 216 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=self_attn_mask)
|
| 217 |
+
return self.o(x)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class CrossAttention(nn.Module):
|
| 221 |
+
def __init__(
|
| 222 |
+
self,
|
| 223 |
+
hidden_dim: int,
|
| 224 |
+
attn_head_dim: int,
|
| 225 |
+
num_heads: int,
|
| 226 |
+
eps: float = 1e-6,
|
| 227 |
+
):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.hidden_dim = hidden_dim
|
| 230 |
+
self.num_heads = num_heads
|
| 231 |
+
self.attn_head_dim = attn_head_dim
|
| 232 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 233 |
+
|
| 234 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 235 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 236 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 237 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 238 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 239 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 240 |
+
|
| 241 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 242 |
+
|
| 243 |
+
def forward(self, x: torch.Tensor, ctx: torch.Tensor, ctx_mask: Optional[torch.Tensor] = None):
|
| 244 |
+
q = self.norm_q(self.q(x))
|
| 245 |
+
k = self.norm_k(self.k(ctx))
|
| 246 |
+
v = self.v(ctx)
|
| 247 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 248 |
+
return self.o(x)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class GateModule(nn.Module):
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
def forward(self, x, gate, residual):
|
| 258 |
+
return x + gate * residual
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class DiTBlock(nn.Module):
|
| 262 |
+
def __init__(
|
| 263 |
+
self, hidden_dim: int, attn_head_dim: int, num_heads: int, ffn_dim: int, eps: float = 1e-6
|
| 264 |
+
):
|
| 265 |
+
super().__init__()
|
| 266 |
+
self.hidden_dim = hidden_dim
|
| 267 |
+
self.attn_head_dim = attn_head_dim
|
| 268 |
+
self.num_heads = num_heads
|
| 269 |
+
self.ffn_dim = ffn_dim
|
| 270 |
+
|
| 271 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 272 |
+
self.cross_attn = CrossAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 273 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 274 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 275 |
+
self.norm3 = nn.LayerNorm(hidden_dim, eps=eps)
|
| 276 |
+
self.ffn = nn.Sequential(
|
| 277 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 278 |
+
nn.GELU(approximate="tanh"),
|
| 279 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 280 |
+
)
|
| 281 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 282 |
+
self.gate = GateModule()
|
| 283 |
+
|
| 284 |
+
def forward(
|
| 285 |
+
self,
|
| 286 |
+
x,
|
| 287 |
+
context,
|
| 288 |
+
t_mod,
|
| 289 |
+
freqs,
|
| 290 |
+
context_mask=None,
|
| 291 |
+
self_attn_mask: Optional[torch.Tensor] = None,
|
| 292 |
+
):
|
| 293 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 294 |
+
context_mask = context_mask.unsqueeze(1) # (B, 1, seq_len, context_len), 1 for heads
|
| 295 |
+
has_seq = len(t_mod.shape) == 4
|
| 296 |
+
chunk_dim = 2 if has_seq else 1
|
| 297 |
+
# msa: multi-head self-attention mlp: multi-layer perceptron
|
| 298 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 299 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 300 |
+
).chunk(6, dim=chunk_dim)
|
| 301 |
+
if has_seq:
|
| 302 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 303 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 304 |
+
shift_msa.squeeze(2),
|
| 305 |
+
scale_msa.squeeze(2),
|
| 306 |
+
gate_msa.squeeze(2),
|
| 307 |
+
shift_mlp.squeeze(2),
|
| 308 |
+
scale_mlp.squeeze(2),
|
| 309 |
+
gate_mlp.squeeze(2),
|
| 310 |
+
)
|
| 311 |
+
input_x = modulate(self.norm1(x), shift_msa, scale_msa)
|
| 312 |
+
x = self.gate(x, gate_msa, self.self_attn(input_x, freqs, self_attn_mask=self_attn_mask))
|
| 313 |
+
x = x + self.cross_attn(self.norm3(x), context, ctx_mask=context_mask)
|
| 314 |
+
input_x = modulate(self.norm2(x), shift_mlp, scale_mlp)
|
| 315 |
+
x = self.gate(x, gate_mlp, self.ffn(input_x))
|
| 316 |
+
return x
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class MLP(torch.nn.Module):
|
| 320 |
+
def __init__(self, in_dim, out_dim, has_pos_emb=False):
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.proj = torch.nn.Sequential(
|
| 323 |
+
nn.LayerNorm(in_dim),
|
| 324 |
+
nn.Linear(in_dim, in_dim),
|
| 325 |
+
nn.GELU(),
|
| 326 |
+
nn.Linear(in_dim, out_dim),
|
| 327 |
+
nn.LayerNorm(out_dim),
|
| 328 |
+
)
|
| 329 |
+
self.has_pos_emb = has_pos_emb
|
| 330 |
+
if has_pos_emb:
|
| 331 |
+
self.emb_pos = torch.nn.Parameter(torch.zeros((1, 514, 1280)))
|
| 332 |
+
|
| 333 |
+
def forward(self, x):
|
| 334 |
+
if self.has_pos_emb:
|
| 335 |
+
x = x + self.emb_pos.to(dtype=x.dtype, device=x.device)
|
| 336 |
+
return self.proj(x)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class Head(nn.Module):
|
| 340 |
+
def __init__(self, dim: int, out_dim: int, patch_size: Tuple[int, int, int], eps: float):
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.dim = dim
|
| 343 |
+
self.patch_size = patch_size
|
| 344 |
+
self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
|
| 345 |
+
self.head = nn.Linear(dim, out_dim * math.prod(patch_size))
|
| 346 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
|
| 347 |
+
|
| 348 |
+
def forward(self, x, t_mod):
|
| 349 |
+
if len(t_mod.shape) == 3:
|
| 350 |
+
shift, scale = (
|
| 351 |
+
self.modulation.unsqueeze(0).to(dtype=t_mod.dtype, device=t_mod.device)
|
| 352 |
+
+ t_mod.unsqueeze(2)
|
| 353 |
+
).chunk(2, dim=2)
|
| 354 |
+
x = self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 355 |
+
else:
|
| 356 |
+
shift, scale = (
|
| 357 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 358 |
+
).chunk(2, dim=1)
|
| 359 |
+
x = self.head(self.norm(x) * (1 + scale) + shift)
|
| 360 |
+
return x
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class WanVideoDiT(torch.nn.Module):
|
| 364 |
+
def __init__(
|
| 365 |
+
self,
|
| 366 |
+
hidden_dim: int,
|
| 367 |
+
in_dim: int,
|
| 368 |
+
ffn_dim: int,
|
| 369 |
+
out_dim: int,
|
| 370 |
+
text_dim: int,
|
| 371 |
+
freq_dim: int,
|
| 372 |
+
eps: float,
|
| 373 |
+
patch_size: Tuple[int, int, int],
|
| 374 |
+
num_heads: int,
|
| 375 |
+
attn_head_dim: int,
|
| 376 |
+
num_layers: int,
|
| 377 |
+
has_image_input: bool,
|
| 378 |
+
has_image_pos_emb: bool = False,
|
| 379 |
+
has_ref_conv: bool = False,
|
| 380 |
+
add_control_adapter: bool = False,
|
| 381 |
+
in_dim_control_adapter: int = 24,
|
| 382 |
+
seperated_timestep: bool = False,
|
| 383 |
+
require_vae_embedding: bool = False,
|
| 384 |
+
require_clip_embedding: bool = False,
|
| 385 |
+
fuse_vae_embedding_in_latents: bool = True,
|
| 386 |
+
action_conditioned: bool = False,
|
| 387 |
+
action_dim: int = 7,
|
| 388 |
+
action_group_causal_mask_mode="causal",
|
| 389 |
+
video_attention_mask_mode: str = "bidirectional",
|
| 390 |
+
use_gradient_checkpointing: bool = False,
|
| 391 |
+
):
|
| 392 |
+
super().__init__()
|
| 393 |
+
self.hidden_dim = hidden_dim
|
| 394 |
+
self.in_dim = in_dim
|
| 395 |
+
self.freq_dim = freq_dim
|
| 396 |
+
self.patch_size = patch_size
|
| 397 |
+
self.num_heads = num_heads
|
| 398 |
+
self.attn_head_dim = attn_head_dim
|
| 399 |
+
self.seperated_timestep = seperated_timestep
|
| 400 |
+
self.require_vae_embedding = require_vae_embedding
|
| 401 |
+
self.require_clip_embedding = require_clip_embedding
|
| 402 |
+
self.fuse_vae_embedding_in_latents = fuse_vae_embedding_in_latents
|
| 403 |
+
self.video_attention_mask_mode = str(video_attention_mask_mode)
|
| 404 |
+
|
| 405 |
+
if num_heads <= 0:
|
| 406 |
+
raise ValueError(f"`num_heads` must be > 0, got {num_heads}")
|
| 407 |
+
if attn_head_dim <= 0:
|
| 408 |
+
raise ValueError(f"`attn_head_dim` must be > 0, got {attn_head_dim}")
|
| 409 |
+
if attn_head_dim % 2 != 0:
|
| 410 |
+
raise ValueError(f"`attn_head_dim` must be even for RoPE, got {attn_head_dim}")
|
| 411 |
+
|
| 412 |
+
self.action_conditioned = action_conditioned
|
| 413 |
+
self.action_dim = action_dim
|
| 414 |
+
assert has_image_input == False
|
| 415 |
+
assert require_clip_embedding == False
|
| 416 |
+
assert (
|
| 417 |
+
require_vae_embedding == False and fuse_vae_embedding_in_latents == True
|
| 418 |
+
), "Only support fusing vae embedding in latents"
|
| 419 |
+
|
| 420 |
+
self.patch_embedding = nn.Conv3d(
|
| 421 |
+
in_dim, hidden_dim, kernel_size=patch_size, stride=patch_size
|
| 422 |
+
)
|
| 423 |
+
self.text_embedding = nn.Sequential(
|
| 424 |
+
nn.Linear(text_dim, hidden_dim),
|
| 425 |
+
nn.GELU(approximate="tanh"),
|
| 426 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 427 |
+
)
|
| 428 |
+
self.time_embedding = nn.Sequential(
|
| 429 |
+
nn.Linear(freq_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim)
|
| 430 |
+
)
|
| 431 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 432 |
+
self.blocks = nn.ModuleList(
|
| 433 |
+
[
|
| 434 |
+
DiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 435 |
+
for _ in range(num_layers)
|
| 436 |
+
]
|
| 437 |
+
)
|
| 438 |
+
self.head = Head(hidden_dim, out_dim, patch_size, eps)
|
| 439 |
+
self.freqs = precompute_freqs_cis_3d(attn_head_dim)
|
| 440 |
+
if has_ref_conv:
|
| 441 |
+
self.ref_conv = nn.Conv2d(16, hidden_dim, kernel_size=(2, 2), stride=(2, 2))
|
| 442 |
+
self.has_image_pos_emb = has_image_pos_emb
|
| 443 |
+
self.has_ref_conv = has_ref_conv
|
| 444 |
+
self.control_adapter = None
|
| 445 |
+
|
| 446 |
+
if self.action_conditioned:
|
| 447 |
+
self.action_embedding = nn.Linear(action_dim, hidden_dim)
|
| 448 |
+
self.action_group_causal_mask_mode = action_group_causal_mask_mode
|
| 449 |
+
|
| 450 |
+
self.use_gradient_checkpointing = use_gradient_checkpointing
|
| 451 |
+
if self.use_gradient_checkpointing:
|
| 452 |
+
logger.info(
|
| 453 |
+
"Using gradient checkpointing for DiT blocks. This will save memory but use more computation."
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
def patchify(
|
| 457 |
+
self, x: torch.Tensor, control_camera_latents_input: Optional[torch.Tensor] = None
|
| 458 |
+
):
|
| 459 |
+
x = self.patch_embedding(x)
|
| 460 |
+
if self.control_adapter is not None and control_camera_latents_input is not None:
|
| 461 |
+
y_camera = self.control_adapter(control_camera_latents_input)
|
| 462 |
+
x = [u + v for u, v in zip(x, y_camera)]
|
| 463 |
+
x = x[0].unsqueeze(0)
|
| 464 |
+
return x
|
| 465 |
+
|
| 466 |
+
def unpatchify(self, x: torch.Tensor, grid_size: torch.Tensor):
|
| 467 |
+
return rearrange(
|
| 468 |
+
x,
|
| 469 |
+
"b (f h w) (x y z c) -> b c (f x) (h y) (w z)",
|
| 470 |
+
f=grid_size[0],
|
| 471 |
+
h=grid_size[1],
|
| 472 |
+
w=grid_size[2],
|
| 473 |
+
x=self.patch_size[0],
|
| 474 |
+
y=self.patch_size[1],
|
| 475 |
+
z=self.patch_size[2],
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
def _validate_forward_inputs(
|
| 479 |
+
self,
|
| 480 |
+
x: torch.Tensor,
|
| 481 |
+
timestep: torch.Tensor,
|
| 482 |
+
context: torch.Tensor,
|
| 483 |
+
context_mask: Optional[torch.Tensor],
|
| 484 |
+
action: Optional[torch.Tensor],
|
| 485 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 486 |
+
if x.ndim != 5:
|
| 487 |
+
raise ValueError(f"`latents` must be 5D [B, C, T, H, W], got shape {tuple(x.shape)}")
|
| 488 |
+
num_latent_frames = x.shape[2]
|
| 489 |
+
if context.ndim != 3:
|
| 490 |
+
raise ValueError(f"`context` must be 3D [B, L, D], got shape {tuple(context.shape)}")
|
| 491 |
+
if timestep.ndim != 1:
|
| 492 |
+
raise ValueError(f"`timestep` must be 1D [B] or [1], got shape {tuple(timestep.shape)}")
|
| 493 |
+
if self.action_conditioned:
|
| 494 |
+
allow_text_only_single_frame = num_latent_frames == 1 and action is None
|
| 495 |
+
if not allow_text_only_single_frame:
|
| 496 |
+
assert action is not None, "Action input is required for action-conditioned model."
|
| 497 |
+
if action.ndim != 3:
|
| 498 |
+
raise ValueError(
|
| 499 |
+
f"`action` must be 3D [B, action_horizon, action_dim], got shape {tuple(action.shape)}"
|
| 500 |
+
)
|
| 501 |
+
if action.shape[2] != self.action_dim:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
f"`action` last dimension must be {self.action_dim}, got {action.shape[2]}"
|
| 504 |
+
)
|
| 505 |
+
if num_latent_frames <= 1:
|
| 506 |
+
raise ValueError(
|
| 507 |
+
f"video length must be > 1 for action-conditioned model, got {num_latent_frames}"
|
| 508 |
+
)
|
| 509 |
+
if action.shape[1] % (num_latent_frames - 1) != 0:
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"action horizon must be divisible by (num_latent_frames - 1), got action_horizon={action.shape[1]}"
|
| 512 |
+
)
|
| 513 |
+
if context_mask is None:
|
| 514 |
+
context_mask = torch.ones(
|
| 515 |
+
(context.shape[0], context.shape[1]), dtype=torch.bool, device=context.device
|
| 516 |
+
)
|
| 517 |
+
else:
|
| 518 |
+
if context_mask.ndim != 2:
|
| 519 |
+
raise ValueError(
|
| 520 |
+
f"`context_mask` must be 2D [B, L], got shape {tuple(context_mask.shape)}"
|
| 521 |
+
)
|
| 522 |
+
if (
|
| 523 |
+
context_mask.shape[0] != context.shape[0]
|
| 524 |
+
or context_mask.shape[1] != context.shape[1]
|
| 525 |
+
):
|
| 526 |
+
raise ValueError(
|
| 527 |
+
f"`context_mask` shape must match `context` shape [B, L], got {tuple(context_mask.shape)} vs {tuple(context.shape)}"
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
batch_size = x.shape[0]
|
| 531 |
+
if batch_size != context.shape[0]:
|
| 532 |
+
if not self.training and batch_size == 1:
|
| 533 |
+
x = x.expand(context.shape[0], -1, -1, -1, -1)
|
| 534 |
+
batch_size = context.shape[0]
|
| 535 |
+
else:
|
| 536 |
+
raise ValueError(
|
| 537 |
+
f"Batch mismatch between latents and context: {batch_size} vs {context.shape[0]}."
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
if timestep.shape[0] not in (1, batch_size):
|
| 541 |
+
raise ValueError(
|
| 542 |
+
f"`timestep` length must be 1 or batch_size({batch_size}), got {timestep.shape[0]}"
|
| 543 |
+
)
|
| 544 |
+
if timestep.shape[0] == 1 and batch_size > 1:
|
| 545 |
+
assert not self.training, "During training, timestep length must match batch_size."
|
| 546 |
+
timestep = timestep.expand(batch_size)
|
| 547 |
+
return x, timestep, context_mask
|
| 548 |
+
|
| 549 |
+
def build_video_to_video_mask(
|
| 550 |
+
self,
|
| 551 |
+
video_seq_len: int,
|
| 552 |
+
video_tokens_per_frame: int,
|
| 553 |
+
device: torch.device,
|
| 554 |
+
) -> torch.Tensor:
|
| 555 |
+
if video_seq_len <= 0:
|
| 556 |
+
raise ValueError(f"`video_seq_len` must be positive, got {video_seq_len}")
|
| 557 |
+
if video_tokens_per_frame <= 0:
|
| 558 |
+
raise ValueError(
|
| 559 |
+
f"`video_tokens_per_frame` must be positive, got {video_tokens_per_frame}"
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if self.video_attention_mask_mode == "bidirectional":
|
| 563 |
+
return torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 564 |
+
|
| 565 |
+
if self.video_attention_mask_mode == "per_frame_causal":
|
| 566 |
+
if video_seq_len % video_tokens_per_frame != 0:
|
| 567 |
+
raise ValueError(
|
| 568 |
+
"`video_seq_len` must be divisible by `video_tokens_per_frame` in `per_frame_causal` mode, "
|
| 569 |
+
f"got {video_seq_len} and {video_tokens_per_frame}"
|
| 570 |
+
)
|
| 571 |
+
num_video_frames = video_seq_len // video_tokens_per_frame
|
| 572 |
+
frame_causal = torch.tril(
|
| 573 |
+
torch.ones((num_video_frames, num_video_frames), dtype=torch.bool, device=device)
|
| 574 |
+
)
|
| 575 |
+
return frame_causal.repeat_interleave(video_tokens_per_frame, dim=0).repeat_interleave(
|
| 576 |
+
video_tokens_per_frame, dim=1
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
if self.video_attention_mask_mode == "first_frame_causal":
|
| 580 |
+
video_mask = torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 581 |
+
first_frame_tokens = min(video_tokens_per_frame, video_seq_len)
|
| 582 |
+
video_mask[:first_frame_tokens, first_frame_tokens:] = False
|
| 583 |
+
return video_mask
|
| 584 |
+
|
| 585 |
+
raise ValueError(f"Unsupported video attention mask mode: {self.video_attention_mask_mode}")
|
| 586 |
+
|
| 587 |
+
def pre_dit(
|
| 588 |
+
self,
|
| 589 |
+
x: torch.Tensor,
|
| 590 |
+
timestep: torch.Tensor,
|
| 591 |
+
context: torch.Tensor,
|
| 592 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 593 |
+
action: Optional[torch.Tensor] = None,
|
| 594 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 595 |
+
control_camera_latents_input: Optional[torch.Tensor] = None,
|
| 596 |
+
) -> Dict[str, Any]:
|
| 597 |
+
x, timestep, context_mask = self._validate_forward_inputs(
|
| 598 |
+
x=x,
|
| 599 |
+
timestep=timestep,
|
| 600 |
+
context=context,
|
| 601 |
+
context_mask=context_mask,
|
| 602 |
+
action=action,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
batch_size = x.shape[0]
|
| 606 |
+
patch_h = int(self.patch_size[1])
|
| 607 |
+
patch_w = int(self.patch_size[2])
|
| 608 |
+
if x.shape[3] % patch_h != 0 or x.shape[4] % patch_w != 0:
|
| 609 |
+
raise ValueError(
|
| 610 |
+
"Latent spatial shape must be divisible by DiT patch size, "
|
| 611 |
+
f"got HxW=({x.shape[3]}, {x.shape[4]}), patch=({patch_h}, {patch_w})"
|
| 612 |
+
)
|
| 613 |
+
tokens_per_frame = (x.shape[3] // patch_h) * (x.shape[4] // patch_w)
|
| 614 |
+
|
| 615 |
+
if self.seperated_timestep and fuse_vae_embedding_in_latents:
|
| 616 |
+
if not hasattr(self, "patch_size") or len(self.patch_size) < 3:
|
| 617 |
+
raise ValueError(f"Invalid dit.patch_size: {getattr(self, 'patch_size', None)}")
|
| 618 |
+
|
| 619 |
+
token_timesteps = torch.ones(
|
| 620 |
+
(batch_size, x.shape[2], tokens_per_frame),
|
| 621 |
+
dtype=timestep.dtype,
|
| 622 |
+
device=timestep.device,
|
| 623 |
+
) * timestep.view(batch_size, 1, 1)
|
| 624 |
+
token_timesteps[:, 0, :] = 0
|
| 625 |
+
token_timesteps = token_timesteps.reshape(batch_size, -1)
|
| 626 |
+
token_t_emb = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1))
|
| 627 |
+
t = self.time_embedding(token_t_emb).reshape(batch_size, -1, self.hidden_dim)
|
| 628 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 629 |
+
else:
|
| 630 |
+
raise NotImplementedError(
|
| 631 |
+
"Only support seperated_timestep with fuse_vae_embedding_in_latents for now."
|
| 632 |
+
)
|
| 633 |
+
t = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, timestep))
|
| 634 |
+
t_mod = self.time_projection(t).unflatten(1, (6, self.hidden_dim))
|
| 635 |
+
x = self.patchify(x, control_camera_latents_input=control_camera_latents_input)
|
| 636 |
+
f, h, w = x.shape[2:]
|
| 637 |
+
|
| 638 |
+
context = self.text_embedding(context) # (B, L, dim)
|
| 639 |
+
context_len = context.shape[1]
|
| 640 |
+
if self.action_conditioned and action is not None:
|
| 641 |
+
action_len = action.shape[1]
|
| 642 |
+
action_emb = self.action_embedding(action) # (B, action_len, dim)
|
| 643 |
+
action_pos_embed = sinusoidal_embedding_1d(
|
| 644 |
+
self.hidden_dim, torch.arange(action_len, device=action_emb.device)
|
| 645 |
+
) # (action_len, dim)
|
| 646 |
+
action_emb = action_emb + action_pos_embed.unsqueeze(0) # (B, action_len, dim)
|
| 647 |
+
context = torch.cat([context, action_emb], dim=1) # (B, context_len + action_len, dim)
|
| 648 |
+
|
| 649 |
+
# new mask
|
| 650 |
+
num_temporal_groups = f - 1 # first latent frame do not attend to actions
|
| 651 |
+
if num_temporal_groups <= 0:
|
| 652 |
+
raise ValueError(
|
| 653 |
+
"Action-conditioned context mask requires at least 2 latent frames when `action` is provided."
|
| 654 |
+
)
|
| 655 |
+
assert (
|
| 656 |
+
action_emb.shape[1] % num_temporal_groups == 0
|
| 657 |
+
), f"Action embedding length {action_emb.shape[1]} must be divisible by number of temporal groups {num_temporal_groups}"
|
| 658 |
+
# Each latent frame (from the 2nd one) attends to the corresponding group of action tokens
|
| 659 |
+
action_group_mask = create_group_causal_attn_mask(
|
| 660 |
+
num_temporal_groups=num_temporal_groups,
|
| 661 |
+
num_query_per_group=tokens_per_frame,
|
| 662 |
+
num_key_per_group=action_len // num_temporal_groups,
|
| 663 |
+
mode=self.action_group_causal_mask_mode,
|
| 664 |
+
).to(
|
| 665 |
+
context.device
|
| 666 |
+
) # ((f-1)*tokens_per_frame, action_len)
|
| 667 |
+
|
| 668 |
+
seq_len = f * h * w # query length
|
| 669 |
+
final_context_mask = torch.zeros(
|
| 670 |
+
(batch_size, seq_len, context.shape[1]), dtype=torch.bool, device=context.device
|
| 671 |
+
) # (B, seq_len, L + action_len)
|
| 672 |
+
# all latent frames attend to text tokens
|
| 673 |
+
final_context_mask[:, :, :context_len] = context_mask.unsqueeze(1).expand(
|
| 674 |
+
-1, seq_len, -1
|
| 675 |
+
) # (B, seq_len, L)
|
| 676 |
+
# latent frames from the 2nd one attend to action tokens
|
| 677 |
+
final_context_mask[:, tokens_per_frame:, context_len:] = action_group_mask.unsqueeze(
|
| 678 |
+
0
|
| 679 |
+
).expand(
|
| 680 |
+
batch_size, -1, -1
|
| 681 |
+
) # (B, seq_len, action_len)
|
| 682 |
+
context_mask = final_context_mask
|
| 683 |
+
elif self.action_conditioned and action is None:
|
| 684 |
+
if f != 1:
|
| 685 |
+
raise ValueError(
|
| 686 |
+
"Action-conditioned model requires `action` unless running single-frame text-only mode with num_latent_frames=1."
|
| 687 |
+
)
|
| 688 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 689 |
+
else:
|
| 690 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 691 |
+
|
| 692 |
+
x_tokens = rearrange(x, "b c f h w -> b (f h w) c").contiguous()
|
| 693 |
+
|
| 694 |
+
freqs = (
|
| 695 |
+
torch.cat(
|
| 696 |
+
[
|
| 697 |
+
self.freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
|
| 698 |
+
self.freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
|
| 699 |
+
self.freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1),
|
| 700 |
+
],
|
| 701 |
+
dim=-1,
|
| 702 |
+
)
|
| 703 |
+
.reshape(f * h * w, 1, -1)
|
| 704 |
+
.to(x_tokens.device)
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
return {
|
| 708 |
+
"tokens": x_tokens,
|
| 709 |
+
"freqs": freqs,
|
| 710 |
+
"t": t,
|
| 711 |
+
"t_mod": t_mod,
|
| 712 |
+
"context": context,
|
| 713 |
+
"context_mask": context_mask,
|
| 714 |
+
"meta": {
|
| 715 |
+
"grid_size": (f, h, w),
|
| 716 |
+
"tokens_per_frame": tokens_per_frame,
|
| 717 |
+
"batch_size": batch_size,
|
| 718 |
+
},
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
def post_dit(self, x_tokens: torch.Tensor, pre_state: Dict[str, Any]) -> torch.Tensor:
|
| 722 |
+
f, h, w = pre_state["meta"]["grid_size"]
|
| 723 |
+
x = self.head(x_tokens, pre_state["t"])
|
| 724 |
+
x = self.unpatchify(x, (f, h, w))
|
| 725 |
+
return x
|
| 726 |
+
|
| 727 |
+
def forward(
|
| 728 |
+
self,
|
| 729 |
+
x: torch.Tensor,
|
| 730 |
+
timestep: torch.Tensor,
|
| 731 |
+
context: torch.Tensor,
|
| 732 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 733 |
+
action: Optional[torch.Tensor] = None,
|
| 734 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 735 |
+
):
|
| 736 |
+
pre_state = self.pre_dit(
|
| 737 |
+
x=x,
|
| 738 |
+
timestep=timestep,
|
| 739 |
+
context=context,
|
| 740 |
+
context_mask=context_mask,
|
| 741 |
+
action=action,
|
| 742 |
+
fuse_vae_embedding_in_latents=fuse_vae_embedding_in_latents,
|
| 743 |
+
)
|
| 744 |
+
x_tokens = pre_state["tokens"]
|
| 745 |
+
context_emb = pre_state["context"]
|
| 746 |
+
t_mod = pre_state["t_mod"]
|
| 747 |
+
freqs = pre_state["freqs"]
|
| 748 |
+
context_attn_mask = pre_state["context_mask"]
|
| 749 |
+
self_attn_mask = (
|
| 750 |
+
self.build_video_to_video_mask(
|
| 751 |
+
video_seq_len=x_tokens.shape[1],
|
| 752 |
+
video_tokens_per_frame=int(pre_state["meta"]["tokens_per_frame"]),
|
| 753 |
+
device=x_tokens.device,
|
| 754 |
+
)
|
| 755 |
+
if self.video_attention_mask_mode != "bidirectional"
|
| 756 |
+
else None
|
| 757 |
+
) # special rule for faster speed
|
| 758 |
+
|
| 759 |
+
for block in self.blocks:
|
| 760 |
+
if self.use_gradient_checkpointing:
|
| 761 |
+
x_tokens = gradient_checkpoint_forward(
|
| 762 |
+
block,
|
| 763 |
+
self.use_gradient_checkpointing,
|
| 764 |
+
x_tokens,
|
| 765 |
+
context_emb,
|
| 766 |
+
t_mod,
|
| 767 |
+
freqs,
|
| 768 |
+
context_mask=context_attn_mask,
|
| 769 |
+
self_attn_mask=self_attn_mask,
|
| 770 |
+
)
|
| 771 |
+
else:
|
| 772 |
+
x_tokens = block(
|
| 773 |
+
x_tokens,
|
| 774 |
+
context_emb,
|
| 775 |
+
t_mod,
|
| 776 |
+
freqs,
|
| 777 |
+
context_mask=context_attn_mask,
|
| 778 |
+
self_attn_mask=self_attn_mask,
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
return self.post_dit(x_tokens, pre_state)
|
tools/model_code/recorded/language/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/language/hr_mot.py
ADDED
|
@@ -0,0 +1,1401 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""H&R Mixture-of-Transformers flow model: ~0.6B, FastWAM-style, trained from scratch.
|
| 2 |
+
|
| 3 |
+
Architecture follows FastWAM and departs from it in exactly one place.
|
| 4 |
+
|
| 5 |
+
Same as FastWAM:
|
| 6 |
+
* The whole ordered segment goes through the frozen Wan2.2 48-channel VAE in
|
| 7 |
+
one pass, so its causal 3D convolutions apply both compressions: 16x spatial
|
| 8 |
+
and 4:1 temporal. [B,3,T,H,W] -> [B,48,1+(T-1)/4,h,w], with z0<-f0,
|
| 9 |
+
z1<-f1..4, z2<-f5..8. The DiT never sees RGB.
|
| 10 |
+
* Latents are patchified (1, 2, 2) into spatial tokens that survive all the way
|
| 11 |
+
through the transformer -- there is no per-frame bottleneck.
|
| 12 |
+
* Video and action are two separate experts (Mixture of Transformers): each owns
|
| 13 |
+
its own weights, and they are joined by one mixed self-attention per layer.
|
| 14 |
+
* Per-block AdaLN-Zero style modulation from a per-token timestep, plus RoPE
|
| 15 |
+
(3D over frame/height/width for video, 1D over horizon for action).
|
| 16 |
+
* Rectified-flow / flow-matching objective with the shift-based continuous
|
| 17 |
+
scheduler: x_t = (1-s) x_0 + s eps, target eps - x_0.
|
| 18 |
+
* Generation is the same joint iterative flow integration in latent + action
|
| 19 |
+
space. `HRMoTFlowModel.generate` is the latent-space core; the VAE decode and
|
| 20 |
+
state un-normalization live in `hr_inference.generate_rollout`, because the
|
| 21 |
+
VAE is deliberately kept outside this module.
|
| 22 |
+
|
| 23 |
+
Different from FastWAM:
|
| 24 |
+
* FastWAM passes human context through cross-attention. Here the ground-truth
|
| 25 |
+
human frames are VAE-encoded and placed *in the self-attention sequence* as
|
| 26 |
+
clean condition tokens, so the robot-future video and action tokens attend to
|
| 27 |
+
them directly. There is no text encoder and no cross-attention at all.
|
| 28 |
+
|
| 29 |
+
Token layout for T=9 RGB frames per stream (3 latent steps, 2 predicted):
|
| 30 |
+
|
| 31 |
+
video expert covers RGB
|
| 32 |
+
[0] robot z0 clean, t=0 condition f0
|
| 33 |
+
[1..3] human z0.. clean, t=0 condition f0 / f1-4 / f5-8
|
| 34 |
+
[4..5] robot z1.. NOISY, t=s prediction f1-4 / f5-8
|
| 35 |
+
action expert
|
| 36 |
+
[0] robot state t0 clean condition
|
| 37 |
+
[1..32] human hand motion t1..t32 clean condition
|
| 38 |
+
[33..64] robot states t1..t32 NOISY prediction
|
| 39 |
+
|
| 40 |
+
Only the robot's future latent steps and states are denoised; the robot z0 latent
|
| 41 |
+
step is restored as clean condition, exactly as FastWAM does.
|
| 42 |
+
|
| 43 |
+
Attention visibility: condition tokens see condition tokens only; prediction
|
| 44 |
+
tokens (robot-future video and robot-future action) see everything.
|
| 45 |
+
|
| 46 |
+
Human-condition availability is an extra mask layer on top of that structure,
|
| 47 |
+
not a change to it. Robot z0 is always present; by default all three human
|
| 48 |
+
latent steps, including human z0, are maskable, giving 2^Tz patterns (8 for
|
| 49 |
+
Tz=3). Masking is whole-step: all `tokens_per_frame` tokens of a human latent
|
| 50 |
+
step are dropped together,
|
| 51 |
+
never a scattered subset of patches. A missing frame is excluded as a key/value
|
| 52 |
+
so nothing reads it, its own query row is diagonal-only and discarded, and its
|
| 53 |
+
RoPE position is *not* renumbered -- the step covering f5-8 stays at position 32
|
| 54 |
+
even when the f1-4 step is absent. Supplied frames additionally carry a 0/1 availability embedding.
|
| 55 |
+
Training and inference build the mask through the same function, so at inference
|
| 56 |
+
any number of human frames can be supplied.
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
from __future__ import annotations
|
| 60 |
+
|
| 61 |
+
from dataclasses import asdict, dataclass, field
|
| 62 |
+
import math
|
| 63 |
+
from typing import Optional, Sequence
|
| 64 |
+
|
| 65 |
+
import torch
|
| 66 |
+
from einops import rearrange
|
| 67 |
+
from torch import nn
|
| 68 |
+
from torch.nn import functional as F
|
| 69 |
+
|
| 70 |
+
from .wan22.mot import MoT
|
| 71 |
+
from .wan22.schedulers.scheduler_continuous import WanContinuousFlowMatchScheduler
|
| 72 |
+
from .wan22.wan_video_dit import (
|
| 73 |
+
GateModule,
|
| 74 |
+
SelfAttention,
|
| 75 |
+
precompute_freqs_cis,
|
| 76 |
+
precompute_freqs_cis_3d,
|
| 77 |
+
sinusoidal_embedding_1d,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
ROLE_ROBOT_CURRENT = 0
|
| 81 |
+
ROLE_HUMAN_CONTEXT = 1
|
| 82 |
+
ROLE_ROBOT_FUTURE = 2
|
| 83 |
+
NUM_ROLES = 3
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass(frozen=True)
|
| 87 |
+
class HRMoTConfig:
|
| 88 |
+
"""Shapes for the ~0.6B H&R MoT. Only trainable modules are counted."""
|
| 89 |
+
|
| 90 |
+
# Latent geometry, fixed by the frozen Wan2.2 VAE and the chosen image size.
|
| 91 |
+
latent_channels: int = 48
|
| 92 |
+
latent_height: int = 14
|
| 93 |
+
latent_width: int = 24
|
| 94 |
+
patch_height: int = 2
|
| 95 |
+
patch_width: int = 2
|
| 96 |
+
|
| 97 |
+
# Ordered RGB segment length handed to the VAE, per stream. The Wan2.2 VAE
|
| 98 |
+
# folds each run of 4 frames into one latent step, so T=9 -> 3 latent steps:
|
| 99 |
+
# z0 <- f0, z1 <- f1..4, z2 <- f5..8. The robot's z0 is the clean current
|
| 100 |
+
# condition; z1.. are what gets denoised.
|
| 101 |
+
num_rgb_frames: int = 9
|
| 102 |
+
vae_temporal_factor: int = 4
|
| 103 |
+
|
| 104 |
+
# Control steps between consecutive video frames. FastWAM keeps every 4th of
|
| 105 |
+
# 33 control steps as a video frame, so 9 frames span 32 steps (1.09 s at the
|
| 106 |
+
# data's 29.4 fps). Reading 9 contiguous frames instead spans 8 steps = 0.27 s,
|
| 107 |
+
# in which almost nothing happens: the gripper changes in 6.4% of 8-step
|
| 108 |
+
# windows versus 25.4% of 32-step ones.
|
| 109 |
+
frame_stride: int = 4
|
| 110 |
+
|
| 111 |
+
# Contiguous robot action steps predicted per sample, covering the video span.
|
| 112 |
+
action_horizon: int = 32
|
| 113 |
+
|
| 114 |
+
action_dim: int = 7
|
| 115 |
+
|
| 116 |
+
# Clean anchors for the action expert. Without them it predicts an absolute
|
| 117 |
+
# end-effector pose (x spans 103..346 mm) with no idea where the arm is now
|
| 118 |
+
# and no aligned human counterpart, having to infer both from pixels through
|
| 119 |
+
# the shared attention. Measured on the anchorless baseline, removing the
|
| 120 |
+
# human cost the action branch +362% -- far more than it cost video, the
|
| 121 |
+
# signature of an unanchored pathway.
|
| 122 |
+
# robot_state_f0 [7] where the arm is at t0
|
| 123 |
+
# human_action t1..tH [action_horizon, 84] raw wrist frame + hand coords
|
| 124 |
+
# False reproduces the anchorless baseline.
|
| 125 |
+
use_state_context: bool = True
|
| 126 |
+
# These two switches preserve the action-condition slots and every module,
|
| 127 |
+
# but hard-mask the corresponding sources. They are therefore suitable for
|
| 128 |
+
# same-size carrier ablations, unlike `use_state_context=False`.
|
| 129 |
+
use_robot_state_context: bool = True
|
| 130 |
+
# Keep the action-side robot-current anchor while hard-masking every mapped
|
| 131 |
+
# human-motion token. This defines the same-size human-video-only control:
|
| 132 |
+
# all modules and parameters remain present, but no 84-D human signal is a
|
| 133 |
+
# readable key/value for any prediction query.
|
| 134 |
+
use_human_motion_context: bool = True
|
| 135 |
+
# Hard-mask every human video latent while retaining the slots, projections,
|
| 136 |
+
# role parameters and sequence length for a strict robot-video-only control.
|
| 137 |
+
use_human_video_context: bool = True
|
| 138 |
+
human_action_dim: int = 84
|
| 139 |
+
# Isolated public-data adapter. Default preserves the original H&R schema.
|
| 140 |
+
# Bridge uses measured robot EE state, not hand motion or control commands.
|
| 141 |
+
source_motion_kind: str = "human_hand84"
|
| 142 |
+
include_source_current: bool = False
|
| 143 |
+
# Optional clean word-token prefix in the state expert. These modules/slots
|
| 144 |
+
# are retained in every matched Bridge variant, including no-language runs.
|
| 145 |
+
num_text_tokens: int = 0
|
| 146 |
+
text_vocab_size: int = 0
|
| 147 |
+
use_language_context: bool = True
|
| 148 |
+
text_hidden_dim: int = 128
|
| 149 |
+
|
| 150 |
+
# Whether the human z0 latent step may also be dropped. With it pinned on, the
|
| 151 |
+
# "no human context at all" path is never trained, its availability embedding
|
| 152 |
+
# row never receives gradient, and any measurement of that condition is out of
|
| 153 |
+
# distribution. Pinning it also lets the model lean entirely on the
|
| 154 |
+
# same-moment cross-embodiment correspondence instead of reading the
|
| 155 |
+
# demonstration. Droppable by default, as part of the same 10% regularizer.
|
| 156 |
+
droppable_human_current: bool = True
|
| 157 |
+
|
| 158 |
+
# Shared across experts -- MoT mixes attention, so head geometry must match.
|
| 159 |
+
num_layers: int = 22
|
| 160 |
+
num_heads: int = 10
|
| 161 |
+
attn_head_dim: int = 128
|
| 162 |
+
|
| 163 |
+
video_hidden_dim: int = 1280
|
| 164 |
+
video_ffn_dim: int = 5120
|
| 165 |
+
action_hidden_dim: int = 640
|
| 166 |
+
action_ffn_dim: int = 2560
|
| 167 |
+
|
| 168 |
+
freq_dim: int = 256
|
| 169 |
+
max_rope_position: int = 1024
|
| 170 |
+
eps: float = 1e-6
|
| 171 |
+
|
| 172 |
+
gradient_checkpointing: bool = True
|
| 173 |
+
|
| 174 |
+
# Human-condition availability. Robot z0 is never masked. Human z0 is
|
| 175 |
+
# droppable by default together with both human-future latent steps, yielding
|
| 176 |
+
# 2^3 = 8 patterns; --pin-human-current restores the legacy 4-pattern contract.
|
| 177 |
+
#
|
| 178 |
+
# This is a *regularizer*, not a curriculum: the point is that the model can
|
| 179 |
+
# still be asked for fewer human steps at inference, not that it should train
|
| 180 |
+
# mostly on degraded context. Dropping context on half the samples actively
|
| 181 |
+
# weakens the human pathway, which is the pathway under study. Default is 0.9
|
| 182 |
+
# full context, i.e. a 10% dropout rate.
|
| 183 |
+
full_human_context_prob: float = 0.9
|
| 184 |
+
|
| 185 |
+
# Flow-matching schedule (FastWAM defaults).
|
| 186 |
+
video_train_shift: float = 5.0
|
| 187 |
+
video_infer_shift: float = 5.0
|
| 188 |
+
action_train_shift: float = 5.0
|
| 189 |
+
action_infer_shift: float = 5.0
|
| 190 |
+
num_train_timesteps: int = 1000
|
| 191 |
+
|
| 192 |
+
# The video loss averages over ~250k scalars per sample and the action loss
|
| 193 |
+
# over ~21. Summing the two raw means gives the video term a far smaller and
|
| 194 |
+
# noisier per-element gradient, which is one of the failures the previous run
|
| 195 |
+
# hit. These weights are the knob for that balance.
|
| 196 |
+
loss_lambda_video: float = 1.0
|
| 197 |
+
loss_lambda_action: float = 1.0
|
| 198 |
+
|
| 199 |
+
def validate(self) -> None:
|
| 200 |
+
expected_source_dim = {"human_hand84": 84, "bridge_measured_state7": 7}.get(
|
| 201 |
+
self.source_motion_kind
|
| 202 |
+
)
|
| 203 |
+
if expected_source_dim is None:
|
| 204 |
+
raise ValueError(f"Unknown source motion schema: {self.source_motion_kind}")
|
| 205 |
+
if self.num_text_tokens:
|
| 206 |
+
if not self.use_state_context or self.text_vocab_size < 3:
|
| 207 |
+
raise ValueError("Text requires clean state context and a real word vocabulary")
|
| 208 |
+
if self.text_hidden_dim % 4:
|
| 209 |
+
raise ValueError("Text hidden dimension must divide four heads")
|
| 210 |
+
if self.use_state_context and self.human_action_dim != expected_source_dim:
|
| 211 |
+
raise ValueError(
|
| 212 |
+
f"{self.source_motion_kind} requires {expected_source_dim} dimensions; "
|
| 213 |
+
f"got {self.human_action_dim}"
|
| 214 |
+
)
|
| 215 |
+
if self.frame_stride < 1:
|
| 216 |
+
raise ValueError(f"frame_stride must be >= 1, got {self.frame_stride}")
|
| 217 |
+
if self.action_horizon != self.video_span:
|
| 218 |
+
raise ValueError(
|
| 219 |
+
"action_horizon must equal the video span "
|
| 220 |
+
f"(num_rgb_frames-1)*frame_stride = {self.video_span}, "
|
| 221 |
+
f"got {self.action_horizon}"
|
| 222 |
+
)
|
| 223 |
+
if self.latent_height % self.patch_height or self.latent_width % self.patch_width:
|
| 224 |
+
raise ValueError(
|
| 225 |
+
f"latent size ({self.latent_height}, {self.latent_width}) must be divisible "
|
| 226 |
+
f"by DiT patch ({self.patch_height}, {self.patch_width})"
|
| 227 |
+
)
|
| 228 |
+
if self.num_rgb_frames < 5 or (self.num_rgb_frames - 1) % self.vae_temporal_factor:
|
| 229 |
+
raise ValueError(
|
| 230 |
+
"num_rgb_frames must be >=5 with (T-1) % "
|
| 231 |
+
f"{self.vae_temporal_factor} == 0, got {self.num_rgb_frames}"
|
| 232 |
+
)
|
| 233 |
+
# Guard the indices actually used, not the frame count: the video stream
|
| 234 |
+
# indexes `frame_rope_positions` and the action stream indexes up to
|
| 235 |
+
# num_action_tokens, either of which can exceed num_rgb_frames.
|
| 236 |
+
highest = max((*self.frame_rope_positions, self.num_action_tokens))
|
| 237 |
+
if highest >= self.max_rope_position:
|
| 238 |
+
raise ValueError(
|
| 239 |
+
f"RoPE position {highest} exceeds the precomputed table "
|
| 240 |
+
f"({self.max_rope_position})"
|
| 241 |
+
)
|
| 242 |
+
# rope_apply consumes head_dim/2 complex frequencies; the 3D split must
|
| 243 |
+
# add back up to exactly that or the rotation silently misaligns.
|
| 244 |
+
head_dim = self.attn_head_dim
|
| 245 |
+
f_dim = head_dim - 2 * (head_dim // 3)
|
| 246 |
+
complex_total = (f_dim // 2) + 2 * ((head_dim // 3) // 2)
|
| 247 |
+
if complex_total != head_dim // 2:
|
| 248 |
+
raise ValueError(
|
| 249 |
+
f"attn_head_dim={head_dim} does not split evenly into 3D RoPE "
|
| 250 |
+
f"({complex_total} complex frequencies, need {head_dim // 2}); "
|
| 251 |
+
"use a value such as 96 or 128"
|
| 252 |
+
)
|
| 253 |
+
for name, dim in (
|
| 254 |
+
("video_hidden_dim", self.video_hidden_dim),
|
| 255 |
+
("action_hidden_dim", self.action_hidden_dim),
|
| 256 |
+
):
|
| 257 |
+
if dim <= 0:
|
| 258 |
+
raise ValueError(f"{name} must be positive")
|
| 259 |
+
if self.num_layers <= 0 or self.num_heads <= 0:
|
| 260 |
+
raise ValueError("num_layers and num_heads must be positive")
|
| 261 |
+
|
| 262 |
+
@property
|
| 263 |
+
def num_latent_steps(self) -> int:
|
| 264 |
+
"""1 + (T-1)/4 per stream."""
|
| 265 |
+
return 1 + (self.num_rgb_frames - 1) // self.vae_temporal_factor
|
| 266 |
+
|
| 267 |
+
@property
|
| 268 |
+
def num_horizons(self) -> int:
|
| 269 |
+
"""Predicted robot latent steps: everything after the clean z0."""
|
| 270 |
+
return self.num_latent_steps - 1
|
| 271 |
+
|
| 272 |
+
@property
|
| 273 |
+
def video_span(self) -> int:
|
| 274 |
+
"""Control steps covered by the video window."""
|
| 275 |
+
return (self.num_rgb_frames - 1) * self.frame_stride
|
| 276 |
+
|
| 277 |
+
@property
|
| 278 |
+
def num_action_tokens(self) -> int:
|
| 279 |
+
"""One robot state per predicted control step."""
|
| 280 |
+
return self.action_horizon
|
| 281 |
+
|
| 282 |
+
@property
|
| 283 |
+
def latent_step_frames(self) -> tuple[int, ...]:
|
| 284 |
+
"""Last CONTROL STEP each latent step covers.
|
| 285 |
+
|
| 286 |
+
The VAE folds 4 video frames into one latent step and each video frame is
|
| 287 |
+
`frame_stride` control steps apart, so a latent step spans
|
| 288 |
+
`4 * frame_stride` control steps: with stride 4 that is 0 / 16 / 32.
|
| 289 |
+
Expressing this in control steps rather than video-frame index is what
|
| 290 |
+
lets a predicted robot latent step share a RoPE position with the human
|
| 291 |
+
latent step covering the same real time.
|
| 292 |
+
"""
|
| 293 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 294 |
+
return (0, *((index + 1) * span for index in range(self.num_latent_steps - 1)))
|
| 295 |
+
|
| 296 |
+
@property
|
| 297 |
+
def tokens_per_frame(self) -> int:
|
| 298 |
+
return (self.latent_height // self.patch_height) * (self.latent_width // self.patch_width)
|
| 299 |
+
|
| 300 |
+
@property
|
| 301 |
+
def num_action_condition_tokens(self) -> int:
|
| 302 |
+
"""Robot state at t0 plus one human-motion token per control step."""
|
| 303 |
+
return (
|
| 304 |
+
(1 + self.num_source_motion_tokens + self.num_text_tokens)
|
| 305 |
+
if self.use_state_context
|
| 306 |
+
else 0
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
@property
|
| 310 |
+
def num_source_motion_tokens(self) -> int:
|
| 311 |
+
return self.num_action_tokens + int(self.include_source_current)
|
| 312 |
+
|
| 313 |
+
@property
|
| 314 |
+
def num_action_sequence(self) -> int:
|
| 315 |
+
return self.num_action_condition_tokens + self.num_action_tokens
|
| 316 |
+
|
| 317 |
+
@property
|
| 318 |
+
def action_rope_positions(self) -> tuple[int, ...]:
|
| 319 |
+
"""Control-step index per action token, condition block first.
|
| 320 |
+
|
| 321 |
+
A predicted state at step i shares its RoPE position with the human motion
|
| 322 |
+
at step i, mirroring how a predicted robot latent step shares a position
|
| 323 |
+
with the human latent step covering the same real time.
|
| 324 |
+
"""
|
| 325 |
+
future = tuple(range(1, self.num_action_tokens + 1))
|
| 326 |
+
if not self.use_state_context:
|
| 327 |
+
return future
|
| 328 |
+
source = (0, *future) if self.include_source_current else future
|
| 329 |
+
return (0, *source, *range(self.num_text_tokens), *future)
|
| 330 |
+
|
| 331 |
+
def human_action_latent_step(self) -> tuple[int, ...]:
|
| 332 |
+
"""Which human latent step each human-motion token follows for availability.
|
| 333 |
+
|
| 334 |
+
Control steps 1..16 fall inside latent step 1, 17..32 inside step 2, so a
|
| 335 |
+
masked human latent step masks the action tokens covering the same real
|
| 336 |
+
time. Clamped in case the horizon ever overruns the video span.
|
| 337 |
+
"""
|
| 338 |
+
span = self.vae_temporal_factor * self.frame_stride
|
| 339 |
+
last = self.num_latent_steps - 1
|
| 340 |
+
future = tuple(min(1 + (index // span), last) for index in range(self.num_action_tokens))
|
| 341 |
+
return (0, *future) if self.include_source_current else future
|
| 342 |
+
|
| 343 |
+
@property
|
| 344 |
+
def num_condition_frames(self) -> int:
|
| 345 |
+
"""robot z0 + every human latent step."""
|
| 346 |
+
return 1 + self.num_latent_steps
|
| 347 |
+
|
| 348 |
+
@property
|
| 349 |
+
def num_video_frames(self) -> int:
|
| 350 |
+
"""condition slots + predicted robot latent steps."""
|
| 351 |
+
return self.num_condition_frames + self.num_horizons
|
| 352 |
+
|
| 353 |
+
@property
|
| 354 |
+
def num_condition_tokens(self) -> int:
|
| 355 |
+
return self.num_condition_frames * self.tokens_per_frame
|
| 356 |
+
|
| 357 |
+
@property
|
| 358 |
+
def num_video_tokens(self) -> int:
|
| 359 |
+
return self.num_video_frames * self.tokens_per_frame
|
| 360 |
+
|
| 361 |
+
@property
|
| 362 |
+
def frame_rope_positions(self) -> tuple[int, ...]:
|
| 363 |
+
"""Temporal RoPE index per latent-step slot, in RGB-frame units.
|
| 364 |
+
|
| 365 |
+
A predicted robot latent step shares its temporal position with the human
|
| 366 |
+
latent step covering the same frames; the role embedding is what separates
|
| 367 |
+
them. That alignment is the point.
|
| 368 |
+
"""
|
| 369 |
+
steps = self.latent_step_frames
|
| 370 |
+
return (steps[0], *steps, *steps[1:])
|
| 371 |
+
|
| 372 |
+
@property
|
| 373 |
+
def frame_roles(self) -> tuple[int, ...]:
|
| 374 |
+
return (
|
| 375 |
+
ROLE_ROBOT_CURRENT,
|
| 376 |
+
*([ROLE_HUMAN_CONTEXT] * self.num_latent_steps),
|
| 377 |
+
*([ROLE_ROBOT_FUTURE] * self.num_horizons),
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
def to_dict(self) -> dict[str, object]:
|
| 381 |
+
return asdict(self)
|
| 382 |
+
|
| 383 |
+
|
| 384 |
+
def build_condition_prediction_mask(
|
| 385 |
+
*,
|
| 386 |
+
num_condition_tokens: int,
|
| 387 |
+
num_video_tokens: int,
|
| 388 |
+
num_action_tokens: int,
|
| 389 |
+
device: torch.device | None = None,
|
| 390 |
+
) -> torch.Tensor:
|
| 391 |
+
"""Visibility over the concatenated [video, action] MoT sequence.
|
| 392 |
+
|
| 393 |
+
Condition queries (robot current + human ground truth) see condition keys
|
| 394 |
+
only, so the clean context never leaks information from the noisy targets.
|
| 395 |
+
Prediction queries (robot future video + robot future action) see everything.
|
| 396 |
+
"""
|
| 397 |
+
|
| 398 |
+
if not 0 < num_condition_tokens <= num_video_tokens:
|
| 399 |
+
raise ValueError(
|
| 400 |
+
f"num_condition_tokens={num_condition_tokens} must be in (0, {num_video_tokens}]"
|
| 401 |
+
)
|
| 402 |
+
if num_action_tokens <= 0:
|
| 403 |
+
raise ValueError("num_action_tokens must be positive")
|
| 404 |
+
total = num_video_tokens + num_action_tokens
|
| 405 |
+
mask = torch.zeros((total, total), dtype=torch.bool, device=device)
|
| 406 |
+
mask[:num_condition_tokens, :num_condition_tokens] = True
|
| 407 |
+
mask[num_condition_tokens:, :] = True
|
| 408 |
+
return mask
|
| 409 |
+
|
| 410 |
+
|
| 411 |
+
def build_availability_attention_mask(
|
| 412 |
+
config: "HRMoTConfig",
|
| 413 |
+
human_mask: torch.Tensor,
|
| 414 |
+
*,
|
| 415 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 416 |
+
text_valid: torch.Tensor | None = None,
|
| 417 |
+
device: torch.device | None = None,
|
| 418 |
+
) -> torch.Tensor:
|
| 419 |
+
"""Per-sample [B, 1, S, S] visibility over the concatenated [video, action] sequence.
|
| 420 |
+
|
| 421 |
+
`human_mask` is [B, 1+K] with True = that human video step was
|
| 422 |
+
supplied. `human_motion_mask` has the same shape and controls the mapped
|
| 423 |
+
84-D motion tokens. It defaults to `human_mask`, preserving the joint-mask
|
| 424 |
+
training contract and every existing caller.
|
| 425 |
+
|
| 426 |
+
Rows follow the group-level contract:
|
| 427 |
+
|
| 428 |
+
valid condition (R0, H0, available H*) -> valid condition only
|
| 429 |
+
missing condition (masked-out H*) -> itself only, output discarded
|
| 430 |
+
prediction (robot future + state) -> valid condition + prediction
|
| 431 |
+
|
| 432 |
+
Missing frames are excluded as keys entirely, so no query ever reads them.
|
| 433 |
+
Their own rows are diagonal-only purely to keep the softmax well defined; a
|
| 434 |
+
fully-False row would produce NaN.
|
| 435 |
+
"""
|
| 436 |
+
|
| 437 |
+
tokens_per_frame = config.tokens_per_frame
|
| 438 |
+
human_slots = config.num_latent_steps
|
| 439 |
+
batch = human_mask.shape[0]
|
| 440 |
+
if human_mask.shape != (batch, human_slots):
|
| 441 |
+
raise ValueError(f"human_mask must be [B, {human_slots}], got {tuple(human_mask.shape)}")
|
| 442 |
+
device = device if device is not None else human_mask.device
|
| 443 |
+
human_mask = human_mask.to(device=device, dtype=torch.bool)
|
| 444 |
+
if human_motion_mask is None:
|
| 445 |
+
human_motion_mask = human_mask
|
| 446 |
+
if human_motion_mask.shape != (batch, human_slots):
|
| 447 |
+
raise ValueError(
|
| 448 |
+
f"human_motion_mask must be [B, {human_slots}], got "
|
| 449 |
+
f"{tuple(human_motion_mask.shape)}"
|
| 450 |
+
)
|
| 451 |
+
human_motion_mask = human_motion_mask.to(device=device, dtype=torch.bool)
|
| 452 |
+
if not config.use_human_video_context:
|
| 453 |
+
human_mask = torch.zeros_like(human_mask)
|
| 454 |
+
if not config.use_human_motion_context:
|
| 455 |
+
human_motion_mask = torch.zeros_like(human_motion_mask)
|
| 456 |
+
|
| 457 |
+
# --- video side: robot z0, human z0.., then the predicted robot steps ------
|
| 458 |
+
frame_available = torch.ones((batch, config.num_video_frames), dtype=torch.bool, device=device)
|
| 459 |
+
frame_available[:, 1 : 1 + human_slots] = human_mask
|
| 460 |
+
is_condition_frame = torch.zeros(config.num_video_frames, dtype=torch.bool, device=device)
|
| 461 |
+
is_condition_frame[: config.num_condition_frames] = True
|
| 462 |
+
|
| 463 |
+
valid = (frame_available & is_condition_frame[None, :]).repeat_interleave(
|
| 464 |
+
tokens_per_frame, dim=1
|
| 465 |
+
)
|
| 466 |
+
missing = ((~frame_available) & is_condition_frame[None, :]).repeat_interleave(
|
| 467 |
+
tokens_per_frame, dim=1
|
| 468 |
+
)
|
| 469 |
+
prediction = (
|
| 470 |
+
(~is_condition_frame)[None, :].expand(batch, -1).repeat_interleave(tokens_per_frame, dim=1)
|
| 471 |
+
)
|
| 472 |
+
|
| 473 |
+
# --- action side: optional clean anchors, then the predicted states --------
|
| 474 |
+
if config.use_state_context:
|
| 475 |
+
# The robot anchor slot is retained in same-size ablations, but can be
|
| 476 |
+
# made a missing (diagonal-only) key/value.
|
| 477 |
+
robot_now = torch.full(
|
| 478 |
+
(batch, 1),
|
| 479 |
+
bool(config.use_robot_state_context),
|
| 480 |
+
dtype=torch.bool,
|
| 481 |
+
device=device,
|
| 482 |
+
)
|
| 483 |
+
# A human-motion token inherits the availability of the latent step whose
|
| 484 |
+
# control steps it covers, so masking a human step masks its motion too.
|
| 485 |
+
steps = torch.tensor(config.human_action_latent_step(), dtype=torch.long, device=device)
|
| 486 |
+
human_now = human_motion_mask[:, steps]
|
| 487 |
+
action_valid = torch.cat((robot_now, human_now), dim=1)
|
| 488 |
+
action_missing = torch.cat((~robot_now, ~human_now), dim=1)
|
| 489 |
+
if config.num_text_tokens:
|
| 490 |
+
if text_valid is None or not config.use_language_context:
|
| 491 |
+
text_valid = torch.zeros(
|
| 492 |
+
batch, config.num_text_tokens, device=device, dtype=torch.bool
|
| 493 |
+
)
|
| 494 |
+
if text_valid.shape != (batch, config.num_text_tokens):
|
| 495 |
+
raise ValueError("Incorrect clean text validity shape")
|
| 496 |
+
text_valid = text_valid.to(device=device, dtype=torch.bool)
|
| 497 |
+
action_valid = torch.cat((action_valid, text_valid), dim=1)
|
| 498 |
+
action_missing = torch.cat((action_missing, ~text_valid), dim=1)
|
| 499 |
+
else:
|
| 500 |
+
action_valid = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 501 |
+
action_missing = torch.zeros((batch, 0), dtype=torch.bool, device=device)
|
| 502 |
+
action_prediction = torch.ones(
|
| 503 |
+
(batch, config.num_action_tokens), dtype=torch.bool, device=device
|
| 504 |
+
)
|
| 505 |
+
zeros_pred = torch.zeros_like(action_prediction)
|
| 506 |
+
|
| 507 |
+
valid = torch.cat((valid, action_valid, zeros_pred), dim=1)
|
| 508 |
+
missing = torch.cat((missing, action_missing, zeros_pred), dim=1)
|
| 509 |
+
prediction = torch.cat((prediction, torch.zeros_like(action_valid), action_prediction), dim=1)
|
| 510 |
+
|
| 511 |
+
total = valid.shape[1]
|
| 512 |
+
mask = valid[:, :, None] & valid[:, None, :]
|
| 513 |
+
mask |= prediction[:, :, None] & (valid | prediction)[:, None, :]
|
| 514 |
+
mask |= missing[:, :, None] & torch.eye(total, dtype=torch.bool, device=device)[None]
|
| 515 |
+
return mask.unsqueeze(1)
|
| 516 |
+
|
| 517 |
+
|
| 518 |
+
class HRDiTBlock(nn.Module):
|
| 519 |
+
"""FastWAM's DiT block minus cross-attention: all conditioning is in-sequence."""
|
| 520 |
+
|
| 521 |
+
def __init__(
|
| 522 |
+
self,
|
| 523 |
+
hidden_dim: int,
|
| 524 |
+
attn_head_dim: int,
|
| 525 |
+
num_heads: int,
|
| 526 |
+
ffn_dim: int,
|
| 527 |
+
eps: float = 1e-6,
|
| 528 |
+
) -> None:
|
| 529 |
+
super().__init__()
|
| 530 |
+
self.hidden_dim = hidden_dim
|
| 531 |
+
self.attn_head_dim = attn_head_dim
|
| 532 |
+
self.num_heads = num_heads
|
| 533 |
+
self.ffn_dim = ffn_dim
|
| 534 |
+
|
| 535 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 536 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 537 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 538 |
+
self.ffn = nn.Sequential(
|
| 539 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 540 |
+
nn.GELU(approximate="tanh"),
|
| 541 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 542 |
+
)
|
| 543 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 544 |
+
self.gate = GateModule()
|
| 545 |
+
|
| 546 |
+
|
| 547 |
+
class HRHead(nn.Module):
|
| 548 |
+
"""Final AdaLN-modulated projection, driven by the same per-token timestep."""
|
| 549 |
+
|
| 550 |
+
def __init__(self, hidden_dim: int, out_dim: int, eps: float = 1e-6) -> None:
|
| 551 |
+
super().__init__()
|
| 552 |
+
self.norm = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 553 |
+
self.head = nn.Linear(hidden_dim, out_dim)
|
| 554 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, hidden_dim) / hidden_dim**0.5)
|
| 555 |
+
|
| 556 |
+
def forward(self, x: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 557 |
+
# x, t: [B, S, hidden]
|
| 558 |
+
modulation = self.modulation.unsqueeze(0).to(dtype=t.dtype, device=t.device)
|
| 559 |
+
shift, scale = (modulation + t.unsqueeze(2)).chunk(2, dim=2)
|
| 560 |
+
return self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 561 |
+
|
| 562 |
+
|
| 563 |
+
class _ExpertBase(nn.Module):
|
| 564 |
+
"""Shared timestep-modulation plumbing and the MoT-required attributes."""
|
| 565 |
+
|
| 566 |
+
def __init__(
|
| 567 |
+
self,
|
| 568 |
+
*,
|
| 569 |
+
hidden_dim: int,
|
| 570 |
+
ffn_dim: int,
|
| 571 |
+
num_layers: int,
|
| 572 |
+
num_heads: int,
|
| 573 |
+
attn_head_dim: int,
|
| 574 |
+
freq_dim: int,
|
| 575 |
+
eps: float,
|
| 576 |
+
gradient_checkpointing: bool,
|
| 577 |
+
) -> None:
|
| 578 |
+
super().__init__()
|
| 579 |
+
self.hidden_dim = hidden_dim
|
| 580 |
+
self.num_heads = num_heads
|
| 581 |
+
self.attn_head_dim = attn_head_dim
|
| 582 |
+
self.freq_dim = freq_dim
|
| 583 |
+
self.use_gradient_checkpointing = bool(gradient_checkpointing)
|
| 584 |
+
|
| 585 |
+
self.blocks = nn.ModuleList(
|
| 586 |
+
HRDiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 587 |
+
for _ in range(num_layers)
|
| 588 |
+
)
|
| 589 |
+
self.time_embedding = nn.Sequential(
|
| 590 |
+
nn.Linear(freq_dim, hidden_dim),
|
| 591 |
+
nn.SiLU(),
|
| 592 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 593 |
+
)
|
| 594 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 595 |
+
self._rope_cache: dict[tuple[torch.device, int], torch.Tensor] = {}
|
| 596 |
+
|
| 597 |
+
def embed_timesteps(self, token_timesteps: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
|
| 598 |
+
"""[B, S] per-token flow time -> (t [B, S, D], t_mod [B, S, 6, D])."""
|
| 599 |
+
|
| 600 |
+
batch, seq_len = token_timesteps.shape
|
| 601 |
+
embedded = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1).float())
|
| 602 |
+
t = self.time_embedding(embedded).reshape(batch, seq_len, self.hidden_dim)
|
| 603 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 604 |
+
return t, t_mod
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
class HRVideoExpert(_ExpertBase):
|
| 608 |
+
"""Video expert over per-frame Wan2.2 latents with 3D RoPE and role embeddings."""
|
| 609 |
+
|
| 610 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 611 |
+
super().__init__(
|
| 612 |
+
hidden_dim=config.video_hidden_dim,
|
| 613 |
+
ffn_dim=config.video_ffn_dim,
|
| 614 |
+
num_layers=config.num_layers,
|
| 615 |
+
num_heads=config.num_heads,
|
| 616 |
+
attn_head_dim=config.attn_head_dim,
|
| 617 |
+
freq_dim=config.freq_dim,
|
| 618 |
+
eps=config.eps,
|
| 619 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 620 |
+
)
|
| 621 |
+
self.config = config
|
| 622 |
+
patch = (1, config.patch_height, config.patch_width)
|
| 623 |
+
self.patch_size = patch
|
| 624 |
+
self.patch_embedding = nn.Conv3d(
|
| 625 |
+
config.latent_channels, config.video_hidden_dim, kernel_size=patch, stride=patch
|
| 626 |
+
)
|
| 627 |
+
self.role_embedding = nn.Parameter(torch.zeros(NUM_ROLES, config.video_hidden_dim))
|
| 628 |
+
# Availability code read by the *prediction* tokens. It has to live here,
|
| 629 |
+
# not on the human slots: under the hard mask nothing can read a missing
|
| 630 |
+
# frame, so a marker placed on it would be permanently unreachable and
|
| 631 |
+
# carry zero gradient. One embedding per (human slot, available?) pair,
|
| 632 |
+
# summed, tells the predictor exactly which human frames were supplied.
|
| 633 |
+
self.availability_embedding = nn.Parameter(
|
| 634 |
+
torch.zeros(config.num_latent_steps, 2, config.video_hidden_dim)
|
| 635 |
+
)
|
| 636 |
+
self.head = HRHead(
|
| 637 |
+
config.video_hidden_dim,
|
| 638 |
+
config.latent_channels * config.patch_height * config.patch_width,
|
| 639 |
+
config.eps,
|
| 640 |
+
)
|
| 641 |
+
# Kept off the module buffer registry: complex tensors do not survive DDP
|
| 642 |
+
# buffer broadcast cleanly, and these are deterministic constants anyway.
|
| 643 |
+
self._freqs_3d = precompute_freqs_cis_3d(config.attn_head_dim, end=config.max_rope_position)
|
| 644 |
+
|
| 645 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 646 |
+
"""[num_video_tokens, 1, head_dim/2] complex, in frame-major token order."""
|
| 647 |
+
|
| 648 |
+
key = (device, 0)
|
| 649 |
+
cached = self._rope_cache.get(key)
|
| 650 |
+
if cached is not None:
|
| 651 |
+
return cached
|
| 652 |
+
config = self.config
|
| 653 |
+
grid_h = config.latent_height // config.patch_height
|
| 654 |
+
grid_w = config.latent_width // config.patch_width
|
| 655 |
+
f_freqs, h_freqs, w_freqs = (x.to(device) for x in self._freqs_3d)
|
| 656 |
+
positions = torch.tensor(config.frame_rope_positions, dtype=torch.long, device=device)
|
| 657 |
+
num_frames = positions.numel()
|
| 658 |
+
freqs = torch.cat(
|
| 659 |
+
(
|
| 660 |
+
f_freqs[positions]
|
| 661 |
+
.view(num_frames, 1, 1, -1)
|
| 662 |
+
.expand(num_frames, grid_h, grid_w, -1),
|
| 663 |
+
h_freqs[:grid_h].view(1, grid_h, 1, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 664 |
+
w_freqs[:grid_w].view(1, 1, grid_w, -1).expand(num_frames, grid_h, grid_w, -1),
|
| 665 |
+
),
|
| 666 |
+
dim=-1,
|
| 667 |
+
).reshape(num_frames * grid_h * grid_w, 1, -1)
|
| 668 |
+
self._rope_cache[key] = freqs
|
| 669 |
+
return freqs
|
| 670 |
+
|
| 671 |
+
def embed(self, latents: torch.Tensor, human_mask: torch.Tensor | None = None) -> torch.Tensor:
|
| 672 |
+
"""[B, N, C, h, w] latents -> [B, N*tokens_per_frame, D] tokens.
|
| 673 |
+
|
| 674 |
+
`human_mask` is [B, 1+K] with True = this human frame is provided. Frames
|
| 675 |
+
marked False are replaced by `absent_human_embedding`, so they keep their
|
| 676 |
+
slot, role and RoPE position but carry no information from any episode.
|
| 677 |
+
"""
|
| 678 |
+
|
| 679 |
+
config = self.config
|
| 680 |
+
if latents.ndim != 5:
|
| 681 |
+
raise ValueError(f"latents must be [B, N, C, h, w], got {tuple(latents.shape)}")
|
| 682 |
+
if latents.shape[1] != config.num_video_frames:
|
| 683 |
+
raise ValueError(
|
| 684 |
+
f"expected {config.num_video_frames} video frames, got {latents.shape[1]}"
|
| 685 |
+
)
|
| 686 |
+
if latents.shape[2:] != (
|
| 687 |
+
config.latent_channels,
|
| 688 |
+
config.latent_height,
|
| 689 |
+
config.latent_width,
|
| 690 |
+
):
|
| 691 |
+
raise ValueError(
|
| 692 |
+
f"latent shape {tuple(latents.shape[2:])} does not match config "
|
| 693 |
+
f"({config.latent_channels}, {config.latent_height}, {config.latent_width})"
|
| 694 |
+
)
|
| 695 |
+
# patch_size[0] == 1, so the conv never mixes two frames together.
|
| 696 |
+
x = self.patch_embedding(latents.permute(0, 2, 1, 3, 4))
|
| 697 |
+
tokens = rearrange(x, "b d n h w -> b n (h w) d")
|
| 698 |
+
if human_mask is not None:
|
| 699 |
+
start = 1 # human latent steps occupy [1, 1 + num_latent_steps)
|
| 700 |
+
end = 1 + config.num_latent_steps
|
| 701 |
+
if human_mask.shape != (tokens.shape[0], end - start):
|
| 702 |
+
raise ValueError(
|
| 703 |
+
f"human_mask must be [B, {end - start}], got {tuple(human_mask.shape)}"
|
| 704 |
+
)
|
| 705 |
+
keep = human_mask[:, :, None, None].to(torch.bool).to(tokens.device)
|
| 706 |
+
# Whole-frame masking: every token of a human frame is dropped
|
| 707 |
+
# together, never a scattered subset of patches. The hard attention
|
| 708 |
+
# mask already makes these unreadable; zeroing also removes the data.
|
| 709 |
+
human = tokens[:, start:end] * keep.to(tokens.dtype)
|
| 710 |
+
# Availability code onto the robot-future (prediction) frames.
|
| 711 |
+
slots = torch.arange(end - start, device=tokens.device)
|
| 712 |
+
if config.use_human_video_context:
|
| 713 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 714 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 715 |
+
].sum(dim=1)[:, None, None, :]
|
| 716 |
+
else:
|
| 717 |
+
# A fixed "all absent" code would not carry episode data, but it
|
| 718 |
+
# would create a side channel absent from the robot-z0-only claim.
|
| 719 |
+
# Keep a zero-valued autograd edge so DDP still reduces this
|
| 720 |
+
# retained same-size parameter instead of flagging it unused.
|
| 721 |
+
code = self.availability_embedding.sum().to(tokens.dtype) * 0.0
|
| 722 |
+
future = tokens[:, end:] + code
|
| 723 |
+
tokens = torch.cat((tokens[:, :start], human, future), dim=1)
|
| 724 |
+
roles = torch.tensor(config.frame_roles, dtype=torch.long, device=latents.device)
|
| 725 |
+
tokens = tokens + self.role_embedding[roles][None, :, None, :].to(tokens.dtype)
|
| 726 |
+
if not config.use_human_video_context:
|
| 727 |
+
tokens[:, 1 : 1 + config.num_latent_steps] = 0
|
| 728 |
+
return rearrange(tokens, "b n s d -> b (n s) d")
|
| 729 |
+
|
| 730 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor, num_frames: int) -> torch.Tensor:
|
| 731 |
+
"""[B, N*tokens_per_frame, D] -> [B, N, C, h, w] velocity in latent space."""
|
| 732 |
+
|
| 733 |
+
config = self.config
|
| 734 |
+
grid_h = config.latent_height // config.patch_height
|
| 735 |
+
grid_w = config.latent_width // config.patch_width
|
| 736 |
+
x = self.head(tokens, t)
|
| 737 |
+
return rearrange(
|
| 738 |
+
x,
|
| 739 |
+
"b (n h w) (c ph pw) -> b n c (h ph) (w pw)",
|
| 740 |
+
n=num_frames,
|
| 741 |
+
h=grid_h,
|
| 742 |
+
w=grid_w,
|
| 743 |
+
ph=config.patch_height,
|
| 744 |
+
pw=config.patch_width,
|
| 745 |
+
)
|
| 746 |
+
|
| 747 |
+
|
| 748 |
+
class HRActionExpert(_ExpertBase):
|
| 749 |
+
"""Action expert over one token per future horizon, with 1D RoPE on the horizon."""
|
| 750 |
+
|
| 751 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 752 |
+
super().__init__(
|
| 753 |
+
hidden_dim=config.action_hidden_dim,
|
| 754 |
+
ffn_dim=config.action_ffn_dim,
|
| 755 |
+
num_layers=config.num_layers,
|
| 756 |
+
num_heads=config.num_heads,
|
| 757 |
+
attn_head_dim=config.attn_head_dim,
|
| 758 |
+
freq_dim=config.freq_dim,
|
| 759 |
+
eps=config.eps,
|
| 760 |
+
gradient_checkpointing=config.gradient_checkpointing,
|
| 761 |
+
)
|
| 762 |
+
self.config = config
|
| 763 |
+
if config.num_text_tokens:
|
| 764 |
+
self.text_embedding = nn.Embedding(
|
| 765 |
+
config.text_vocab_size, config.text_hidden_dim, padding_idx=0
|
| 766 |
+
)
|
| 767 |
+
self.text_position = nn.Parameter(
|
| 768 |
+
torch.randn(config.num_text_tokens, config.text_hidden_dim) * 0.02
|
| 769 |
+
)
|
| 770 |
+
self.text_encoder = nn.TransformerEncoder(
|
| 771 |
+
nn.TransformerEncoderLayer(
|
| 772 |
+
config.text_hidden_dim,
|
| 773 |
+
4,
|
| 774 |
+
config.text_hidden_dim * 4,
|
| 775 |
+
dropout=0.0,
|
| 776 |
+
batch_first=True,
|
| 777 |
+
norm_first=True,
|
| 778 |
+
),
|
| 779 |
+
2,
|
| 780 |
+
enable_nested_tensor=False,
|
| 781 |
+
)
|
| 782 |
+
self.text_projection = nn.Linear(config.text_hidden_dim, config.action_hidden_dim)
|
| 783 |
+
self.text_role = nn.Parameter(torch.zeros(config.action_hidden_dim))
|
| 784 |
+
self.action_embedding = nn.Linear(config.action_dim, config.action_hidden_dim)
|
| 785 |
+
self.availability_embedding = nn.Parameter(
|
| 786 |
+
torch.zeros(config.num_latent_steps, 2, config.action_hidden_dim)
|
| 787 |
+
)
|
| 788 |
+
if config.use_state_context:
|
| 789 |
+
# The robot anchor reuses action_embedding: it is the same 7-D
|
| 790 |
+
# quantity, so the same projection is the right one. Human hand
|
| 791 |
+
# motion is a different 84-D modality and gets its own projection.
|
| 792 |
+
self.human_action_embedding = nn.Linear(
|
| 793 |
+
config.human_action_dim, config.action_hidden_dim
|
| 794 |
+
)
|
| 795 |
+
self.action_role_embedding = nn.Parameter(
|
| 796 |
+
torch.zeros(NUM_ROLES, config.action_hidden_dim)
|
| 797 |
+
)
|
| 798 |
+
self.head = HRHead(config.action_hidden_dim, config.action_dim, config.eps)
|
| 799 |
+
self._freqs_1d = precompute_freqs_cis(config.attn_head_dim, end=config.max_rope_position)
|
| 800 |
+
|
| 801 |
+
def rope_freqs(self, device: torch.device) -> torch.Tensor:
|
| 802 |
+
key = (device, 0)
|
| 803 |
+
cached = self._rope_cache.get(key)
|
| 804 |
+
if cached is not None:
|
| 805 |
+
return cached
|
| 806 |
+
positions = torch.tensor(self.config.action_rope_positions, dtype=torch.long, device=device)
|
| 807 |
+
freqs = self._freqs_1d.to(device)[positions].view(positions.numel(), 1, -1)
|
| 808 |
+
self._rope_cache[key] = freqs
|
| 809 |
+
return freqs
|
| 810 |
+
|
| 811 |
+
def embed(
|
| 812 |
+
self,
|
| 813 |
+
actions: torch.Tensor,
|
| 814 |
+
human_mask: torch.Tensor | None = None,
|
| 815 |
+
robot_current_state: torch.Tensor | None = None,
|
| 816 |
+
human_future_action: torch.Tensor | None = None,
|
| 817 |
+
text_token_ids: torch.Tensor | None = None,
|
| 818 |
+
text_valid: torch.Tensor | None = None,
|
| 819 |
+
) -> torch.Tensor:
|
| 820 |
+
"""-> [B, num_action_sequence, D], condition block first when enabled."""
|
| 821 |
+
|
| 822 |
+
config = self.config
|
| 823 |
+
if actions.ndim != 3 or actions.shape[1:] != (
|
| 824 |
+
config.num_action_tokens,
|
| 825 |
+
config.action_dim,
|
| 826 |
+
):
|
| 827 |
+
raise ValueError(
|
| 828 |
+
f"actions must be [B, {config.num_action_tokens}, {config.action_dim}], "
|
| 829 |
+
f"got {tuple(actions.shape)}"
|
| 830 |
+
)
|
| 831 |
+
predicted = self.action_embedding(actions)
|
| 832 |
+
if config.use_state_context:
|
| 833 |
+
if robot_current_state is None or human_future_action is None:
|
| 834 |
+
raise ValueError("use_state_context requires query current state and source motion")
|
| 835 |
+
if robot_current_state.shape[1:] != (config.action_dim,):
|
| 836 |
+
raise ValueError(
|
| 837 |
+
f"robot_current_state must be [B, {config.action_dim}], "
|
| 838 |
+
f"got {tuple(robot_current_state.shape)}"
|
| 839 |
+
)
|
| 840 |
+
if human_future_action.shape[1:] != (
|
| 841 |
+
config.num_source_motion_tokens,
|
| 842 |
+
config.human_action_dim,
|
| 843 |
+
):
|
| 844 |
+
raise ValueError(
|
| 845 |
+
f"human_future_action must be [B, {config.num_source_motion_tokens}, "
|
| 846 |
+
f"{config.human_action_dim}], got {tuple(human_future_action.shape)}"
|
| 847 |
+
)
|
| 848 |
+
role = self.action_role_embedding.to(predicted.dtype)
|
| 849 |
+
anchor = self.action_embedding(robot_current_state)[:, None, :]
|
| 850 |
+
anchor = anchor + role[ROLE_ROBOT_CURRENT]
|
| 851 |
+
if not config.use_robot_state_context:
|
| 852 |
+
anchor = torch.zeros_like(anchor)
|
| 853 |
+
human = self.human_action_embedding(human_future_action) + role[ROLE_HUMAN_CONTEXT]
|
| 854 |
+
if human_mask is not None:
|
| 855 |
+
# Zero a masked step's human-motion tokens as well; the hard attention
|
| 856 |
+
# mask already makes them unreadable, this also drops the data.
|
| 857 |
+
steps = torch.tensor(config.human_action_latent_step(), device=human.device)
|
| 858 |
+
keep = human_mask.to(human.device)[:, steps][:, :, None]
|
| 859 |
+
human = human * keep.to(human.dtype)
|
| 860 |
+
predicted = predicted + role[ROLE_ROBOT_FUTURE]
|
| 861 |
+
clean = [anchor, human]
|
| 862 |
+
if config.num_text_tokens:
|
| 863 |
+
batch = actions.shape[0]
|
| 864 |
+
if text_token_ids is None:
|
| 865 |
+
text_token_ids = torch.zeros(
|
| 866 |
+
batch, config.num_text_tokens, dtype=torch.long, device=actions.device
|
| 867 |
+
)
|
| 868 |
+
if text_valid is None or not config.use_language_context:
|
| 869 |
+
text_valid = torch.zeros(
|
| 870 |
+
batch, config.num_text_tokens, dtype=torch.bool, device=actions.device
|
| 871 |
+
)
|
| 872 |
+
if (
|
| 873 |
+
text_token_ids.shape != (batch, config.num_text_tokens)
|
| 874 |
+
or text_valid.shape != text_token_ids.shape
|
| 875 |
+
):
|
| 876 |
+
raise ValueError("Invalid word-token IDs/validity")
|
| 877 |
+
# Zero hidden input IDs before embedding. Even arbitrary IDs in
|
| 878 |
+
# missing positions must not be looked up or affect attention.
|
| 879 |
+
text_token_ids = text_token_ids.masked_fill(~text_valid, 0)
|
| 880 |
+
safe_valid = text_valid.clone()
|
| 881 |
+
safe_valid[:, 0] = True
|
| 882 |
+
text = self.text_embedding(text_token_ids) + self.text_position[None]
|
| 883 |
+
text = self.text_encoder(text, src_key_padding_mask=~safe_valid)
|
| 884 |
+
text = (self.text_projection(text) + self.text_role).masked_fill(
|
| 885 |
+
~text_valid[..., None], 0.0
|
| 886 |
+
)
|
| 887 |
+
clean.append(text)
|
| 888 |
+
tokens = torch.cat((*clean, predicted), dim=1)
|
| 889 |
+
else:
|
| 890 |
+
tokens = predicted
|
| 891 |
+
if human_mask is not None:
|
| 892 |
+
if config.use_human_motion_context:
|
| 893 |
+
slots = torch.arange(human_mask.shape[1], device=tokens.device)
|
| 894 |
+
code = self.availability_embedding.to(tokens.dtype)[
|
| 895 |
+
slots[None, :], human_mask.to(torch.long).to(tokens.device)
|
| 896 |
+
].sum(dim=1)[:, None, :]
|
| 897 |
+
else:
|
| 898 |
+
# Same zero-edge contract as the video expert: no information or
|
| 899 |
+
# numerical effect, while every retained parameter participates.
|
| 900 |
+
code = self.availability_embedding.sum().to(tokens.dtype) * 0.0
|
| 901 |
+
tokens = tokens + code
|
| 902 |
+
return tokens
|
| 903 |
+
|
| 904 |
+
def unembed(self, tokens: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
|
| 905 |
+
return self.head(tokens, t)
|
| 906 |
+
|
| 907 |
+
|
| 908 |
+
class HRMoTFlowModel(nn.Module):
|
| 909 |
+
"""The trainable ~0.6B model. VAE encoding happens outside, in the trainer."""
|
| 910 |
+
|
| 911 |
+
def __init__(self, config: HRMoTConfig) -> None:
|
| 912 |
+
super().__init__()
|
| 913 |
+
config.validate()
|
| 914 |
+
self.config = config
|
| 915 |
+
# MoT owns the experts. Registering them a second time on this module
|
| 916 |
+
# would duplicate every tensor in state_dict, so they are reached through
|
| 917 |
+
# properties instead of attributes.
|
| 918 |
+
self.mot = MoT(
|
| 919 |
+
mixtures={"video": HRVideoExpert(config), "action": HRActionExpert(config)},
|
| 920 |
+
mot_checkpoint_mixed_attn=config.gradient_checkpointing,
|
| 921 |
+
)
|
| 922 |
+
self.train_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 923 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_train_shift
|
| 924 |
+
)
|
| 925 |
+
self.infer_video_scheduler = WanContinuousFlowMatchScheduler(
|
| 926 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.video_infer_shift
|
| 927 |
+
)
|
| 928 |
+
self.train_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 929 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_train_shift
|
| 930 |
+
)
|
| 931 |
+
self.infer_action_scheduler = WanContinuousFlowMatchScheduler(
|
| 932 |
+
num_train_timesteps=config.num_train_timesteps, shift=config.action_infer_shift
|
| 933 |
+
)
|
| 934 |
+
self.reset_parameters()
|
| 935 |
+
|
| 936 |
+
@property
|
| 937 |
+
def video_expert(self) -> HRVideoExpert:
|
| 938 |
+
return self.mot.mixtures["video"]
|
| 939 |
+
|
| 940 |
+
@property
|
| 941 |
+
def action_expert(self) -> HRActionExpert:
|
| 942 |
+
return self.mot.mixtures["action"]
|
| 943 |
+
|
| 944 |
+
def reset_parameters(self) -> None:
|
| 945 |
+
"""Random init only. No pretrained weights enter the trainable model."""
|
| 946 |
+
|
| 947 |
+
def init_linear(module: nn.Module) -> None:
|
| 948 |
+
if isinstance(module, (nn.Linear, nn.Conv3d)):
|
| 949 |
+
nn.init.normal_(module.weight, mean=0.0, std=0.02)
|
| 950 |
+
if module.bias is not None:
|
| 951 |
+
nn.init.zeros_(module.bias)
|
| 952 |
+
|
| 953 |
+
self.apply(init_linear)
|
| 954 |
+
nn.init.normal_(self.video_expert.role_embedding, mean=0.0, std=0.02)
|
| 955 |
+
for expert in (self.video_expert, self.action_expert):
|
| 956 |
+
nn.init.normal_(expert.availability_embedding, mean=0.0, std=0.02)
|
| 957 |
+
if self.config.use_state_context:
|
| 958 |
+
nn.init.normal_(self.action_expert.action_role_embedding, mean=0.0, std=0.02)
|
| 959 |
+
# Wan/DiT init: `modulation` keeps its randn/sqrt(dim) scale (set in the
|
| 960 |
+
# block) and residual output projections are down-scaled by depth so a
|
| 961 |
+
# 22-layer stack does not blow up at step 0.
|
| 962 |
+
residual_std = 0.02 / math.sqrt(2.0 * self.config.num_layers)
|
| 963 |
+
# The final head is initialized *near* zero rather than at zero. Exactly
|
| 964 |
+
# zero makes the model emit zero velocity, which is stable, but it also
|
| 965 |
+
# makes d(loss)/d(head input) identically zero: on the first step only the
|
| 966 |
+
# two head tensors per expert receive gradient and the other 679 do not.
|
| 967 |
+
# A tiny nonzero scale keeps the near-zero start and lets gradient reach
|
| 968 |
+
# every parameter from step 1.
|
| 969 |
+
head_std = 1e-4
|
| 970 |
+
for expert in (self.video_expert, self.action_expert):
|
| 971 |
+
for block in expert.blocks:
|
| 972 |
+
nn.init.normal_(block.self_attn.o.weight, mean=0.0, std=residual_std)
|
| 973 |
+
nn.init.normal_(block.ffn[-1].weight, mean=0.0, std=residual_std)
|
| 974 |
+
nn.init.normal_(expert.head.head.weight, mean=0.0, std=head_std)
|
| 975 |
+
nn.init.zeros_(expert.head.head.bias)
|
| 976 |
+
|
| 977 |
+
def attention_mask(
|
| 978 |
+
self,
|
| 979 |
+
human_mask: torch.Tensor,
|
| 980 |
+
*,
|
| 981 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 982 |
+
text_valid: torch.Tensor | None = None,
|
| 983 |
+
device: torch.device,
|
| 984 |
+
) -> torch.Tensor:
|
| 985 |
+
return build_availability_attention_mask(
|
| 986 |
+
self.config,
|
| 987 |
+
human_mask,
|
| 988 |
+
human_motion_mask=human_motion_mask,
|
| 989 |
+
text_valid=text_valid,
|
| 990 |
+
device=device,
|
| 991 |
+
)
|
| 992 |
+
|
| 993 |
+
def human_availability_patterns(self, device: torch.device) -> torch.Tensor:
|
| 994 |
+
"""Every availability pattern over the maskable human latent steps.
|
| 995 |
+
|
| 996 |
+
All 2^Tz patterns when the human current step is droppable, otherwise the
|
| 997 |
+
2^(Tz-1) patterns that keep it.
|
| 998 |
+
"""
|
| 999 |
+
|
| 1000 |
+
slots = self.config.num_latent_steps
|
| 1001 |
+
if not self.config.droppable_human_current:
|
| 1002 |
+
slots -= 1
|
| 1003 |
+
codes = torch.arange(2**slots, device=device)
|
| 1004 |
+
bits = torch.arange(slots, device=device)
|
| 1005 |
+
return ((codes[:, None] >> bits[None, :]) & 1).bool()
|
| 1006 |
+
|
| 1007 |
+
def sample_human_mask(
|
| 1008 |
+
self,
|
| 1009 |
+
batch: int,
|
| 1010 |
+
*,
|
| 1011 |
+
device: torch.device,
|
| 1012 |
+
generator: Optional[torch.Generator] = None,
|
| 1013 |
+
) -> torch.Tensor:
|
| 1014 |
+
"""[B, Tz] bool. True = that human latent step is supplied.
|
| 1015 |
+
|
| 1016 |
+
`full_human_context_prob` of the batch gets the complete context so
|
| 1017 |
+
full-context quality does not regress; the rest are drawn *uniformly* over
|
| 1018 |
+
every other pattern. This is a regularizer, not a curriculum.
|
| 1019 |
+
|
| 1020 |
+
When `droppable_human_current` is set, the human z0 step is included in
|
| 1021 |
+
the draw, so "no human context at all" is a trained condition rather than
|
| 1022 |
+
an out-of-distribution query, and the model cannot lean entirely on the
|
| 1023 |
+
same-moment cross-embodiment correspondence.
|
| 1024 |
+
"""
|
| 1025 |
+
|
| 1026 |
+
config = self.config
|
| 1027 |
+
patterns = self.human_availability_patterns(device)
|
| 1028 |
+
# The last row is the all-ones pattern; draw the others uniformly.
|
| 1029 |
+
choice = torch.randint(
|
| 1030 |
+
0, patterns.shape[0] - 1, (batch,), device=device, generator=generator
|
| 1031 |
+
)
|
| 1032 |
+
drawn = patterns[choice]
|
| 1033 |
+
use_full = torch.rand(batch, device=device, generator=generator) < float(
|
| 1034 |
+
config.full_human_context_prob
|
| 1035 |
+
)
|
| 1036 |
+
drawn = torch.where(use_full[:, None], torch.ones_like(drawn), drawn)
|
| 1037 |
+
if config.droppable_human_current:
|
| 1038 |
+
return drawn
|
| 1039 |
+
current = torch.ones((batch, 1), dtype=torch.bool, device=device)
|
| 1040 |
+
return torch.cat((current, drawn), dim=1)
|
| 1041 |
+
|
| 1042 |
+
def _token_timesteps(
|
| 1043 |
+
self, timestep: torch.Tensor, *, num_frames: int, noisy_frames: int
|
| 1044 |
+
) -> torch.Tensor:
|
| 1045 |
+
"""Clean condition frames get t=0; only the robot future frames carry t=s."""
|
| 1046 |
+
|
| 1047 |
+
config = self.config
|
| 1048 |
+
batch = timestep.shape[0]
|
| 1049 |
+
per_frame = torch.zeros((batch, num_frames), dtype=torch.float32, device=timestep.device)
|
| 1050 |
+
per_frame[:, num_frames - noisy_frames :] = timestep.float()[:, None]
|
| 1051 |
+
return per_frame.repeat_interleave(config.tokens_per_frame, dim=1)
|
| 1052 |
+
|
| 1053 |
+
def forward_tokens(
|
| 1054 |
+
self,
|
| 1055 |
+
*,
|
| 1056 |
+
robot_current_latent: torch.Tensor,
|
| 1057 |
+
human_latents: torch.Tensor,
|
| 1058 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 1059 |
+
noisy_robot_future_action: torch.Tensor,
|
| 1060 |
+
timestep_video: torch.Tensor,
|
| 1061 |
+
timestep_action: torch.Tensor,
|
| 1062 |
+
human_mask: torch.Tensor | None = None,
|
| 1063 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 1064 |
+
robot_current_state: torch.Tensor | None = None,
|
| 1065 |
+
human_future_action: torch.Tensor | None = None,
|
| 1066 |
+
text_token_ids: torch.Tensor | None = None,
|
| 1067 |
+
text_valid: torch.Tensor | None = None,
|
| 1068 |
+
) -> tuple[dict[str, torch.Tensor], torch.Tensor, torch.Tensor]:
|
| 1069 |
+
"""Run the MoT and return (tokens_out, video_t, action_t).
|
| 1070 |
+
|
| 1071 |
+
`tokens_out["video"]` still holds the condition positions, which
|
| 1072 |
+
`predict_velocity` drops. Tests use them to prove the attention mask
|
| 1073 |
+
really isolates condition tokens from the noisy prediction tokens.
|
| 1074 |
+
"""
|
| 1075 |
+
|
| 1076 |
+
config = self.config
|
| 1077 |
+
if robot_current_latent.ndim != 5 or robot_current_latent.shape[1] != 1:
|
| 1078 |
+
raise ValueError(
|
| 1079 |
+
f"robot_current_latent must be [B, 1, C, h, w], got "
|
| 1080 |
+
f"{tuple(robot_current_latent.shape)}"
|
| 1081 |
+
)
|
| 1082 |
+
if human_latents.shape[1] != config.num_latent_steps:
|
| 1083 |
+
raise ValueError(
|
| 1084 |
+
f"human_latents must carry {config.num_latent_steps} latent steps, "
|
| 1085 |
+
f"got {human_latents.shape[1]}"
|
| 1086 |
+
)
|
| 1087 |
+
if noisy_robot_future_latents.shape[1] != config.num_horizons:
|
| 1088 |
+
raise ValueError(
|
| 1089 |
+
f"noisy_robot_future_latents must carry {config.num_horizons} horizons, "
|
| 1090 |
+
f"got {noisy_robot_future_latents.shape[1]}"
|
| 1091 |
+
)
|
| 1092 |
+
|
| 1093 |
+
latents = torch.cat(
|
| 1094 |
+
(robot_current_latent, human_latents, noisy_robot_future_latents), dim=1
|
| 1095 |
+
)
|
| 1096 |
+
device = latents.device
|
| 1097 |
+
|
| 1098 |
+
if human_mask is None:
|
| 1099 |
+
supplied_human_mask = torch.ones(
|
| 1100 |
+
(latents.shape[0], config.num_latent_steps),
|
| 1101 |
+
dtype=torch.bool,
|
| 1102 |
+
device=device,
|
| 1103 |
+
)
|
| 1104 |
+
else:
|
| 1105 |
+
supplied_human_mask = human_mask.to(device=device, dtype=torch.bool)
|
| 1106 |
+
if human_motion_mask is None:
|
| 1107 |
+
human_motion_mask = supplied_human_mask
|
| 1108 |
+
else:
|
| 1109 |
+
human_motion_mask = human_motion_mask.to(device=device, dtype=torch.bool)
|
| 1110 |
+
# Configuration-level ablations fail closed: callers cannot accidentally
|
| 1111 |
+
# re-enable a source by passing an all-True runtime mask.
|
| 1112 |
+
human_mask = (
|
| 1113 |
+
supplied_human_mask
|
| 1114 |
+
if config.use_human_video_context
|
| 1115 |
+
else torch.zeros_like(supplied_human_mask)
|
| 1116 |
+
)
|
| 1117 |
+
if not config.use_human_motion_context:
|
| 1118 |
+
human_motion_mask = torch.zeros_like(human_motion_mask)
|
| 1119 |
+
video_tokens = self.video_expert.embed(latents, human_mask=human_mask)
|
| 1120 |
+
action_tokens = self.action_expert.embed(
|
| 1121 |
+
noisy_robot_future_action,
|
| 1122 |
+
human_mask=human_motion_mask,
|
| 1123 |
+
robot_current_state=robot_current_state,
|
| 1124 |
+
human_future_action=human_future_action,
|
| 1125 |
+
text_token_ids=text_token_ids,
|
| 1126 |
+
text_valid=text_valid,
|
| 1127 |
+
)
|
| 1128 |
+
|
| 1129 |
+
video_token_t = self._token_timesteps(
|
| 1130 |
+
timestep_video,
|
| 1131 |
+
num_frames=config.num_video_frames,
|
| 1132 |
+
noisy_frames=config.num_horizons,
|
| 1133 |
+
)
|
| 1134 |
+
# Condition tokens are clean (t=0); only the predicted states carry t=s.
|
| 1135 |
+
action_token_t = torch.zeros(
|
| 1136 |
+
(latents.shape[0], config.num_action_sequence),
|
| 1137 |
+
dtype=torch.float32,
|
| 1138 |
+
device=device,
|
| 1139 |
+
)
|
| 1140 |
+
action_token_t[:, config.num_action_condition_tokens :] = timestep_action.float()[:, None]
|
| 1141 |
+
|
| 1142 |
+
video_t, video_t_mod = self.video_expert.embed_timesteps(video_token_t)
|
| 1143 |
+
action_t, action_t_mod = self.action_expert.embed_timesteps(action_token_t)
|
| 1144 |
+
|
| 1145 |
+
mask = self.attention_mask(
|
| 1146 |
+
human_mask, human_motion_mask=human_motion_mask, text_valid=text_valid, device=device
|
| 1147 |
+
)
|
| 1148 |
+
tokens_out = self.mot(
|
| 1149 |
+
embeds_all={"video": video_tokens, "action": action_tokens},
|
| 1150 |
+
attention_mask=mask,
|
| 1151 |
+
freqs_all={
|
| 1152 |
+
"video": self.video_expert.rope_freqs(device),
|
| 1153 |
+
"action": self.action_expert.rope_freqs(device),
|
| 1154 |
+
},
|
| 1155 |
+
# No cross-attention: human context lives in the self-attention sequence.
|
| 1156 |
+
context_all={"video": None, "action": None},
|
| 1157 |
+
t_mod_all={"video": video_t_mod, "action": action_t_mod},
|
| 1158 |
+
)
|
| 1159 |
+
return tokens_out, video_t, action_t
|
| 1160 |
+
|
| 1161 |
+
def predict_velocity(
|
| 1162 |
+
self,
|
| 1163 |
+
*,
|
| 1164 |
+
robot_current_latent: torch.Tensor,
|
| 1165 |
+
human_latents: torch.Tensor,
|
| 1166 |
+
noisy_robot_future_latents: torch.Tensor,
|
| 1167 |
+
noisy_robot_future_action: torch.Tensor,
|
| 1168 |
+
timestep_video: torch.Tensor,
|
| 1169 |
+
timestep_action: torch.Tensor,
|
| 1170 |
+
human_mask: torch.Tensor | None = None,
|
| 1171 |
+
human_motion_mask: torch.Tensor | None = None,
|
| 1172 |
+
robot_current_state: torch.Tensor | None = None,
|
| 1173 |
+
human_future_action: torch.Tensor | None = None,
|
| 1174 |
+
text_token_ids: torch.Tensor | None = None,
|
| 1175 |
+
text_valid: torch.Tensor | None = None,
|
| 1176 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1177 |
+
"""Return flow velocity for the robot future latents and actions."""
|
| 1178 |
+
|
| 1179 |
+
config = self.config
|
| 1180 |
+
tokens_out, video_t, action_t = self.forward_tokens(
|
| 1181 |
+
robot_current_latent=robot_current_latent,
|
| 1182 |
+
human_latents=human_latents,
|
| 1183 |
+
noisy_robot_future_latents=noisy_robot_future_latents,
|
| 1184 |
+
noisy_robot_future_action=noisy_robot_future_action,
|
| 1185 |
+
timestep_video=timestep_video,
|
| 1186 |
+
timestep_action=timestep_action,
|
| 1187 |
+
human_mask=human_mask,
|
| 1188 |
+
human_motion_mask=human_motion_mask,
|
| 1189 |
+
robot_current_state=robot_current_state,
|
| 1190 |
+
human_future_action=human_future_action,
|
| 1191 |
+
text_token_ids=text_token_ids,
|
| 1192 |
+
text_valid=text_valid,
|
| 1193 |
+
)
|
| 1194 |
+
# Only the robot-future slice is a prediction; drop the condition tokens.
|
| 1195 |
+
start = config.num_condition_tokens
|
| 1196 |
+
pred_video = self.video_expert.unembed(
|
| 1197 |
+
tokens_out["video"][:, start:, :],
|
| 1198 |
+
video_t[:, start:, :],
|
| 1199 |
+
num_frames=config.num_horizons,
|
| 1200 |
+
)
|
| 1201 |
+
start_action = config.num_action_condition_tokens
|
| 1202 |
+
pred_action = self.action_expert.unembed(
|
| 1203 |
+
tokens_out["action"][:, start_action:, :], action_t[:, start_action:, :]
|
| 1204 |
+
)
|
| 1205 |
+
return pred_video, pred_action
|
| 1206 |
+
|
| 1207 |
+
def training_loss(
|
| 1208 |
+
self,
|
| 1209 |
+
*,
|
| 1210 |
+
robot_current_latent: torch.Tensor,
|
| 1211 |
+
human_latents: torch.Tensor,
|
| 1212 |
+
robot_future_latents: torch.Tensor,
|
| 1213 |
+
robot_future_action: torch.Tensor,
|
| 1214 |
+
generator: Optional[torch.Generator] = None,
|
| 1215 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1216 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1217 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1218 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1219 |
+
text_token_ids: torch.Tensor | None = None,
|
| 1220 |
+
text_valid: torch.Tensor | None = None,
|
| 1221 |
+
) -> tuple[torch.Tensor, dict[str, torch.Tensor]]:
|
| 1222 |
+
config = self.config
|
| 1223 |
+
batch = robot_future_latents.shape[0]
|
| 1224 |
+
device = robot_future_latents.device
|
| 1225 |
+
dtype = robot_future_latents.dtype
|
| 1226 |
+
|
| 1227 |
+
timestep_video = self.train_video_scheduler.sample_training_t(batch, device, dtype)
|
| 1228 |
+
timestep_action = self.train_action_scheduler.sample_training_t(batch, device, dtype)
|
| 1229 |
+
|
| 1230 |
+
noise_video = torch.randn(
|
| 1231 |
+
robot_future_latents.shape, device=device, dtype=dtype, generator=generator
|
| 1232 |
+
)
|
| 1233 |
+
noise_action = torch.randn(
|
| 1234 |
+
robot_future_action.shape, device=device, dtype=dtype, generator=generator
|
| 1235 |
+
)
|
| 1236 |
+
noisy_video = self.train_video_scheduler.add_noise(
|
| 1237 |
+
robot_future_latents, noise_video, timestep_video
|
| 1238 |
+
)
|
| 1239 |
+
noisy_action = self.train_action_scheduler.add_noise(
|
| 1240 |
+
robot_future_action, noise_action, timestep_action
|
| 1241 |
+
)
|
| 1242 |
+
target_video = self.train_video_scheduler.training_target(
|
| 1243 |
+
robot_future_latents, noise_video, timestep_video
|
| 1244 |
+
)
|
| 1245 |
+
target_action = self.train_action_scheduler.training_target(
|
| 1246 |
+
robot_future_action, noise_action, timestep_action
|
| 1247 |
+
)
|
| 1248 |
+
|
| 1249 |
+
if human_mask is None:
|
| 1250 |
+
human_mask = self.sample_human_mask(batch, device=device, generator=generator)
|
| 1251 |
+
|
| 1252 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1253 |
+
robot_current_latent=robot_current_latent,
|
| 1254 |
+
human_latents=human_latents,
|
| 1255 |
+
noisy_robot_future_latents=noisy_video,
|
| 1256 |
+
noisy_robot_future_action=noisy_action,
|
| 1257 |
+
timestep_video=timestep_video,
|
| 1258 |
+
timestep_action=timestep_action,
|
| 1259 |
+
human_mask=human_mask,
|
| 1260 |
+
human_motion_mask=human_motion_mask,
|
| 1261 |
+
robot_current_state=robot_current_state,
|
| 1262 |
+
human_future_action=human_future_action,
|
| 1263 |
+
text_token_ids=text_token_ids,
|
| 1264 |
+
text_valid=text_valid,
|
| 1265 |
+
)
|
| 1266 |
+
|
| 1267 |
+
# Per-sample means, then the scheduler's timestep weighting -- matching
|
| 1268 |
+
# FastWAM rather than averaging a single scalar over the whole batch.
|
| 1269 |
+
video_per_sample = (pred_video.float() - target_video.float()).pow(2).flatten(1).mean(dim=1)
|
| 1270 |
+
action_per_sample = (
|
| 1271 |
+
(pred_action.float() - target_action.float()).pow(2).flatten(1).mean(dim=1)
|
| 1272 |
+
)
|
| 1273 |
+
video_weight = self.train_video_scheduler.training_weight(timestep_video).to(
|
| 1274 |
+
video_per_sample.device, video_per_sample.dtype
|
| 1275 |
+
)
|
| 1276 |
+
action_weight = self.train_action_scheduler.training_weight(timestep_action).to(
|
| 1277 |
+
action_per_sample.device, action_per_sample.dtype
|
| 1278 |
+
)
|
| 1279 |
+
loss_video = (video_per_sample * video_weight).mean()
|
| 1280 |
+
loss_action = (action_per_sample * action_weight).mean()
|
| 1281 |
+
total = config.loss_lambda_video * loss_video + config.loss_lambda_action * loss_action
|
| 1282 |
+
return total, {
|
| 1283 |
+
"loss_video": loss_video.detach(),
|
| 1284 |
+
"loss_action": loss_action.detach(),
|
| 1285 |
+
"loss_video_unweighted": video_per_sample.mean().detach(),
|
| 1286 |
+
"loss_action_unweighted": action_per_sample.mean().detach(),
|
| 1287 |
+
"human_frames_kept": (
|
| 1288 |
+
human_mask.sum(dim=1).float().mean().detach()
|
| 1289 |
+
if config.use_human_video_context
|
| 1290 |
+
else torch.zeros((), device=device)
|
| 1291 |
+
),
|
| 1292 |
+
}
|
| 1293 |
+
|
| 1294 |
+
@torch.no_grad()
|
| 1295 |
+
def generate(
|
| 1296 |
+
self,
|
| 1297 |
+
*,
|
| 1298 |
+
robot_current_latent: torch.Tensor,
|
| 1299 |
+
human_latents: torch.Tensor,
|
| 1300 |
+
num_inference_steps: int = 20,
|
| 1301 |
+
sigma_shift: Optional[float] = None,
|
| 1302 |
+
generator: Optional[torch.Generator] = None,
|
| 1303 |
+
human_mask: Optional[torch.Tensor] = None,
|
| 1304 |
+
human_motion_mask: Optional[torch.Tensor] = None,
|
| 1305 |
+
robot_current_state: Optional[torch.Tensor] = None,
|
| 1306 |
+
human_future_action: Optional[torch.Tensor] = None,
|
| 1307 |
+
text_token_ids: torch.Tensor | None = None,
|
| 1308 |
+
text_valid: torch.Tensor | None = None,
|
| 1309 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 1310 |
+
"""FastWAM-style joint flow integration in latent + action space.
|
| 1311 |
+
|
| 1312 |
+
This is the latent-space core and returns
|
| 1313 |
+
(robot_future_latents, normalized robot_future_state). It does not touch
|
| 1314 |
+
the VAE, which lives outside the model so DDP never syncs its 705M frozen
|
| 1315 |
+
parameters. For RGB frames and un-normalized state use
|
| 1316 |
+
`fasterwam.models.hr_inference.generate_rollout`.
|
| 1317 |
+
|
| 1318 |
+
`human_mask` is [B, 1+K] and controls human video steps.
|
| 1319 |
+
`human_motion_mask` controls the 84-D motion tokens mapped to those
|
| 1320 |
+
steps. It defaults to `human_mask` for the standard model and to an
|
| 1321 |
+
all-False mask for a configured human-video-only model.
|
| 1322 |
+
"""
|
| 1323 |
+
|
| 1324 |
+
config = self.config
|
| 1325 |
+
batch = robot_current_latent.shape[0]
|
| 1326 |
+
device = robot_current_latent.device
|
| 1327 |
+
dtype = robot_current_latent.dtype
|
| 1328 |
+
|
| 1329 |
+
latents_video = torch.randn(
|
| 1330 |
+
(
|
| 1331 |
+
batch,
|
| 1332 |
+
config.num_horizons,
|
| 1333 |
+
config.latent_channels,
|
| 1334 |
+
config.latent_height,
|
| 1335 |
+
config.latent_width,
|
| 1336 |
+
),
|
| 1337 |
+
device=device,
|
| 1338 |
+
dtype=dtype,
|
| 1339 |
+
generator=generator,
|
| 1340 |
+
)
|
| 1341 |
+
latents_action = torch.randn(
|
| 1342 |
+
(batch, config.num_action_tokens, config.action_dim),
|
| 1343 |
+
device=device,
|
| 1344 |
+
dtype=dtype,
|
| 1345 |
+
generator=generator,
|
| 1346 |
+
)
|
| 1347 |
+
|
| 1348 |
+
timesteps_video, deltas_video = self.infer_video_scheduler.build_inference_schedule(
|
| 1349 |
+
num_inference_steps=num_inference_steps,
|
| 1350 |
+
device=device,
|
| 1351 |
+
dtype=dtype,
|
| 1352 |
+
shift_override=sigma_shift,
|
| 1353 |
+
)
|
| 1354 |
+
timesteps_action, deltas_action = self.infer_action_scheduler.build_inference_schedule(
|
| 1355 |
+
num_inference_steps=num_inference_steps,
|
| 1356 |
+
device=device,
|
| 1357 |
+
dtype=dtype,
|
| 1358 |
+
shift_override=sigma_shift,
|
| 1359 |
+
)
|
| 1360 |
+
|
| 1361 |
+
for step in range(num_inference_steps):
|
| 1362 |
+
step_t_video = timesteps_video[step].expand(batch)
|
| 1363 |
+
step_t_action = timesteps_action[step].expand(batch)
|
| 1364 |
+
pred_video, pred_action = self.predict_velocity(
|
| 1365 |
+
robot_current_latent=robot_current_latent,
|
| 1366 |
+
human_latents=human_latents,
|
| 1367 |
+
noisy_robot_future_latents=latents_video,
|
| 1368 |
+
noisy_robot_future_action=latents_action,
|
| 1369 |
+
timestep_video=step_t_video,
|
| 1370 |
+
timestep_action=step_t_action,
|
| 1371 |
+
human_mask=human_mask,
|
| 1372 |
+
human_motion_mask=human_motion_mask,
|
| 1373 |
+
robot_current_state=robot_current_state,
|
| 1374 |
+
human_future_action=human_future_action,
|
| 1375 |
+
text_token_ids=text_token_ids,
|
| 1376 |
+
text_valid=text_valid,
|
| 1377 |
+
)
|
| 1378 |
+
latents_video = self.infer_video_scheduler.step(
|
| 1379 |
+
pred_video, deltas_video[step], latents_video
|
| 1380 |
+
)
|
| 1381 |
+
latents_action = self.infer_action_scheduler.step(
|
| 1382 |
+
pred_action, deltas_action[step], latents_action
|
| 1383 |
+
)
|
| 1384 |
+
return latents_video, latents_action
|
| 1385 |
+
|
| 1386 |
+
def forward(self, *args, **kwargs):
|
| 1387 |
+
return self.training_loss(*args, **kwargs)
|
| 1388 |
+
|
| 1389 |
+
|
| 1390 |
+
def count_parameters(model: nn.Module) -> int:
|
| 1391 |
+
return sum(parameter.numel() for parameter in model.parameters())
|
| 1392 |
+
|
| 1393 |
+
|
| 1394 |
+
def parameter_breakdown(model: HRMoTFlowModel) -> dict[str, int]:
|
| 1395 |
+
return {
|
| 1396 |
+
"total": count_parameters(model),
|
| 1397 |
+
"video_expert": count_parameters(model.video_expert),
|
| 1398 |
+
"action_expert": count_parameters(model.action_expert),
|
| 1399 |
+
"video_blocks": sum(count_parameters(b) for b in model.video_expert.blocks),
|
| 1400 |
+
"action_blocks": sum(count_parameters(b) for b in model.action_expert.blocks),
|
| 1401 |
+
}
|
tools/model_code/recorded/language/wan22/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/language/wan22/helpers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/language/wan22/helpers/gradient.py
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
def create_custom_forward(module):
|
| 5 |
+
def custom_forward(*inputs, **kwargs):
|
| 6 |
+
return module(*inputs, **kwargs)
|
| 7 |
+
|
| 8 |
+
return custom_forward
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def gradient_checkpoint_forward(
|
| 12 |
+
model,
|
| 13 |
+
use_gradient_checkpointing,
|
| 14 |
+
*args,
|
| 15 |
+
**kwargs,
|
| 16 |
+
):
|
| 17 |
+
if use_gradient_checkpointing:
|
| 18 |
+
model_output = torch.utils.checkpoint.checkpoint(
|
| 19 |
+
create_custom_forward(model),
|
| 20 |
+
*args,
|
| 21 |
+
**kwargs,
|
| 22 |
+
use_reentrant=False,
|
| 23 |
+
)
|
| 24 |
+
else:
|
| 25 |
+
model_output = model(*args, **kwargs)
|
| 26 |
+
return model_output
|
tools/model_code/recorded/language/wan22/mot.py
ADDED
|
@@ -0,0 +1,606 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from typing import Dict, Optional, Sequence
|
| 4 |
+
|
| 5 |
+
import torch
|
| 6 |
+
import torch.nn as nn
|
| 7 |
+
|
| 8 |
+
from .wan_video_dit import flash_attention, modulate, rope_apply
|
| 9 |
+
from logging import getLogger as get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class MoT(nn.Module):
|
| 15 |
+
def __init__(
|
| 16 |
+
self,
|
| 17 |
+
mixtures: Dict[str, nn.Module],
|
| 18 |
+
mot_checkpoint_mixed_attn: bool = True,
|
| 19 |
+
):
|
| 20 |
+
super().__init__()
|
| 21 |
+
if not mixtures:
|
| 22 |
+
raise ValueError("`mixtures` cannot be empty.")
|
| 23 |
+
if "video" not in mixtures or "action" not in mixtures:
|
| 24 |
+
raise ValueError("`mixtures` must include both 'video' and 'action' experts.")
|
| 25 |
+
|
| 26 |
+
self.mixtures = nn.ModuleDict(mixtures)
|
| 27 |
+
self.expert_order = list(self.mixtures.keys())
|
| 28 |
+
self.mot_checkpoint_mixed_attn = mot_checkpoint_mixed_attn
|
| 29 |
+
if mot_checkpoint_mixed_attn:
|
| 30 |
+
logger.info(
|
| 31 |
+
"Using gradient checkpointing for mixture attention. This will save memory but use more computation."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
first_expert = self.mixtures[self.expert_order[0]]
|
| 35 |
+
self.num_layers = len(first_expert.blocks)
|
| 36 |
+
self.num_heads = first_expert.num_heads
|
| 37 |
+
self.attn_head_dim = first_expert.attn_head_dim
|
| 38 |
+
|
| 39 |
+
for name in self.expert_order[1:]:
|
| 40 |
+
expert = self.mixtures[name]
|
| 41 |
+
if len(expert.blocks) != self.num_layers:
|
| 42 |
+
raise ValueError(
|
| 43 |
+
f"All experts must have same number of layers; got {self.num_layers} and {len(expert.blocks)}"
|
| 44 |
+
)
|
| 45 |
+
if expert.num_heads != self.num_heads:
|
| 46 |
+
raise ValueError(
|
| 47 |
+
f"All experts must have same num_heads; got {self.num_heads} and {expert.num_heads}"
|
| 48 |
+
)
|
| 49 |
+
if expert.attn_head_dim != self.attn_head_dim:
|
| 50 |
+
raise ValueError(
|
| 51 |
+
"All experts must have same attn_head_dim; "
|
| 52 |
+
f"got {self.attn_head_dim} and {expert.attn_head_dim}"
|
| 53 |
+
)
|
| 54 |
+
|
| 55 |
+
logger.info(
|
| 56 |
+
f"Initialized MoT with experts: {self.expert_order}, num_layers={self.num_layers}"
|
| 57 |
+
)
|
| 58 |
+
for name in self.expert_order:
|
| 59 |
+
expert = self.mixtures[name]
|
| 60 |
+
logger.info(
|
| 61 |
+
f" Expert '{name}': num_params={sum(p.numel() for p in expert.parameters()) / 1e9:.2f} B"
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
@staticmethod
|
| 65 |
+
def _split_modulation(block, t_mod: torch.Tensor):
|
| 66 |
+
has_seq = len(t_mod.shape) == 4
|
| 67 |
+
chunk_dim = 2 if has_seq else 1
|
| 68 |
+
|
| 69 |
+
base_mod = block.modulation.to(dtype=t_mod.dtype, device=t_mod.device)
|
| 70 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (base_mod + t_mod).chunk(
|
| 71 |
+
6, dim=chunk_dim
|
| 72 |
+
)
|
| 73 |
+
if has_seq:
|
| 74 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 75 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 76 |
+
shift_msa.squeeze(2),
|
| 77 |
+
scale_msa.squeeze(2),
|
| 78 |
+
gate_msa.squeeze(2),
|
| 79 |
+
shift_mlp.squeeze(2),
|
| 80 |
+
scale_mlp.squeeze(2),
|
| 81 |
+
gate_mlp.squeeze(2),
|
| 82 |
+
)
|
| 83 |
+
return shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp
|
| 84 |
+
|
| 85 |
+
def _mixed_attention(
|
| 86 |
+
self,
|
| 87 |
+
q_cat: torch.Tensor,
|
| 88 |
+
k_cat: torch.Tensor,
|
| 89 |
+
v_cat: torch.Tensor,
|
| 90 |
+
attention_mask: torch.Tensor,
|
| 91 |
+
) -> torch.Tensor:
|
| 92 |
+
attn_mask = attention_mask.to(device=q_cat.device)
|
| 93 |
+
|
| 94 |
+
def _forward(q: torch.Tensor, k: torch.Tensor, v: torch.Tensor) -> torch.Tensor:
|
| 95 |
+
return flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=attn_mask)
|
| 96 |
+
|
| 97 |
+
if self.mot_checkpoint_mixed_attn and self.training:
|
| 98 |
+
return torch.utils.checkpoint.checkpoint(
|
| 99 |
+
_forward,
|
| 100 |
+
q_cat,
|
| 101 |
+
k_cat,
|
| 102 |
+
v_cat,
|
| 103 |
+
use_reentrant=False,
|
| 104 |
+
)
|
| 105 |
+
return _forward(q_cat, k_cat, v_cat)
|
| 106 |
+
|
| 107 |
+
def _resolve_attention_masks(
|
| 108 |
+
self,
|
| 109 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 110 |
+
expected_seq_len: int,
|
| 111 |
+
) -> list[torch.Tensor]:
|
| 112 |
+
if isinstance(attention_mask, torch.Tensor):
|
| 113 |
+
attention_masks = [attention_mask] * self.num_layers
|
| 114 |
+
else:
|
| 115 |
+
attention_masks = list(attention_mask)
|
| 116 |
+
if len(attention_masks) != self.num_layers:
|
| 117 |
+
raise ValueError(
|
| 118 |
+
f"`attention_mask` must contain {self.num_layers} layers, got {len(attention_masks)}."
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
for layer_idx, layer_mask in enumerate(attention_masks):
|
| 122 |
+
if not isinstance(layer_mask, torch.Tensor):
|
| 123 |
+
raise ValueError(
|
| 124 |
+
f"`attention_mask[{layer_idx}]` must be torch.Tensor, got {type(layer_mask)}."
|
| 125 |
+
)
|
| 126 |
+
# [S,S] shares one mask across the batch; [B,S,S] and [B,1,S,S] give a
|
| 127 |
+
# per-sample mask, which is what a per-sample condition-availability
|
| 128 |
+
# pattern needs. All three broadcast correctly in
|
| 129 |
+
# scaled_dot_product_attention against q of shape [B,heads,S,D].
|
| 130 |
+
if layer_mask.ndim not in (2, 3, 4):
|
| 131 |
+
raise ValueError(
|
| 132 |
+
f"`attention_mask[{layer_idx}]` must be [S,S], [B,S,S] or [B,1,S,S], "
|
| 133 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 134 |
+
)
|
| 135 |
+
if layer_mask.shape[-1] != layer_mask.shape[-2]:
|
| 136 |
+
raise ValueError(
|
| 137 |
+
f"`attention_mask[{layer_idx}]` must be square in its last two dims, "
|
| 138 |
+
f"got shape {tuple(layer_mask.shape)}"
|
| 139 |
+
)
|
| 140 |
+
if layer_mask.shape[-1] != expected_seq_len:
|
| 141 |
+
raise ValueError(
|
| 142 |
+
f"`attention_mask[{layer_idx}]` seq length mismatch: "
|
| 143 |
+
f"mask={layer_mask.shape[-1]} vs expected_total={expected_seq_len}"
|
| 144 |
+
)
|
| 145 |
+
return attention_masks
|
| 146 |
+
|
| 147 |
+
@staticmethod
|
| 148 |
+
def _apply_expert_post_block(
|
| 149 |
+
block,
|
| 150 |
+
residual_x: torch.Tensor,
|
| 151 |
+
mixed_attn_out: torch.Tensor,
|
| 152 |
+
gate_msa: torch.Tensor,
|
| 153 |
+
shift_mlp: torch.Tensor,
|
| 154 |
+
scale_mlp: torch.Tensor,
|
| 155 |
+
gate_mlp: torch.Tensor,
|
| 156 |
+
context_payload: Optional[dict],
|
| 157 |
+
) -> torch.Tensor:
|
| 158 |
+
x = block.gate(residual_x, gate_msa, block.self_attn.o(mixed_attn_out))
|
| 159 |
+
|
| 160 |
+
if context_payload is not None:
|
| 161 |
+
context = context_payload.get("context")
|
| 162 |
+
if context is not None:
|
| 163 |
+
context_mask = context_payload.get("mask")
|
| 164 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 165 |
+
context_mask = context_mask.unsqueeze(1)
|
| 166 |
+
x = x + block.cross_attn(block.norm3(x), context, ctx_mask=context_mask)
|
| 167 |
+
|
| 168 |
+
mlp_input = modulate(block.norm2(x), shift_mlp, scale_mlp)
|
| 169 |
+
x = block.gate(x, gate_mlp, block.ffn(mlp_input))
|
| 170 |
+
return x
|
| 171 |
+
|
| 172 |
+
def _build_expert_attention_io(
|
| 173 |
+
self,
|
| 174 |
+
expert,
|
| 175 |
+
block,
|
| 176 |
+
x: torch.Tensor,
|
| 177 |
+
freqs: torch.Tensor,
|
| 178 |
+
t_mod: torch.Tensor,
|
| 179 |
+
) -> tuple[
|
| 180 |
+
torch.Tensor,
|
| 181 |
+
torch.Tensor,
|
| 182 |
+
torch.Tensor,
|
| 183 |
+
torch.Tensor,
|
| 184 |
+
torch.Tensor,
|
| 185 |
+
torch.Tensor,
|
| 186 |
+
torch.Tensor,
|
| 187 |
+
torch.Tensor,
|
| 188 |
+
bool,
|
| 189 |
+
]:
|
| 190 |
+
"""Build per-expert attention tensors and post-block states.
|
| 191 |
+
|
| 192 |
+
Args:
|
| 193 |
+
expert: Expert module that owns this `block`; only used to read
|
| 194 |
+
`use_gradient_checkpointing`.
|
| 195 |
+
block: Transformer block for current layer (`expert.blocks[layer_idx]`).
|
| 196 |
+
x: Current expert tokens, shape [B, S, D].
|
| 197 |
+
freqs: RoPE frequencies aligned with token sequence, shape [S, 1, rope_dim].
|
| 198 |
+
t_mod: Time modulation tensor for this expert/layer.
|
| 199 |
+
|
| 200 |
+
Returns:
|
| 201 |
+
q: Query after q-proj, RMSNorm, and RoPE, shape [B, S, H*Dh].
|
| 202 |
+
k: Key after k-proj, RMSNorm, and RoPE, shape [B, S, H*Dh].
|
| 203 |
+
v: Value after v-proj, shape [B, S, H*Dh].
|
| 204 |
+
residual_x: Original input `x` for residual path in post block.
|
| 205 |
+
gate_msa: Gating tensor for self-attention residual branch.
|
| 206 |
+
shift_mlp: Shift tensor for MLP modulation.
|
| 207 |
+
scale_mlp: Scale tensor for MLP modulation.
|
| 208 |
+
gate_mlp: Gating tensor for MLP residual branch.
|
| 209 |
+
use_gradient_checkpointing: Whether this expert enables checkpointing.
|
| 210 |
+
"""
|
| 211 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = self._split_modulation(
|
| 212 |
+
block, t_mod
|
| 213 |
+
)
|
| 214 |
+
attn_input = modulate(block.norm1(x), shift_msa, scale_msa)
|
| 215 |
+
|
| 216 |
+
q = block.self_attn.norm_q(block.self_attn.q(attn_input))
|
| 217 |
+
k = block.self_attn.norm_k(block.self_attn.k(attn_input))
|
| 218 |
+
v = block.self_attn.v(attn_input)
|
| 219 |
+
|
| 220 |
+
q = rope_apply(q, freqs, block.num_heads)
|
| 221 |
+
k = rope_apply(k, freqs, block.num_heads)
|
| 222 |
+
|
| 223 |
+
use_gradient_checkpointing = bool(getattr(expert, "use_gradient_checkpointing", False))
|
| 224 |
+
return (
|
| 225 |
+
q,
|
| 226 |
+
k,
|
| 227 |
+
v,
|
| 228 |
+
x,
|
| 229 |
+
gate_msa,
|
| 230 |
+
shift_mlp,
|
| 231 |
+
scale_mlp,
|
| 232 |
+
gate_mlp,
|
| 233 |
+
use_gradient_checkpointing,
|
| 234 |
+
)
|
| 235 |
+
|
| 236 |
+
def _apply_post_with_optional_checkpoint(
|
| 237 |
+
self,
|
| 238 |
+
block,
|
| 239 |
+
residual_x: torch.Tensor,
|
| 240 |
+
gate_msa: torch.Tensor,
|
| 241 |
+
shift_mlp: torch.Tensor,
|
| 242 |
+
scale_mlp: torch.Tensor,
|
| 243 |
+
gate_mlp: torch.Tensor,
|
| 244 |
+
use_gradient_checkpointing: bool,
|
| 245 |
+
mixed_slice: torch.Tensor,
|
| 246 |
+
context_payload: Optional[dict],
|
| 247 |
+
) -> torch.Tensor:
|
| 248 |
+
"""Apply post-attention computations, with optional checkpointing.
|
| 249 |
+
|
| 250 |
+
Args:
|
| 251 |
+
block: Transformer block for current layer.
|
| 252 |
+
residual_x: Residual input tokens before attention update, shape [B, S, D].
|
| 253 |
+
gate_msa: Gating tensor used after mixed self-attention.
|
| 254 |
+
shift_mlp: Shift tensor for MLP input modulation.
|
| 255 |
+
scale_mlp: Scale tensor for MLP input modulation.
|
| 256 |
+
gate_mlp: Gating tensor used after MLP.
|
| 257 |
+
use_gradient_checkpointing: If True and training, checkpoint this post block.
|
| 258 |
+
mixed_slice: Mixed-attention output for this expert, shape [B, S, H*Dh].
|
| 259 |
+
context_payload: Optional dict for cross-attention.
|
| 260 |
+
- `context`: encoder states [B, L, D]
|
| 261 |
+
- `mask`: attention mask [B, S, L] or [B, 1, S, L]
|
| 262 |
+
|
| 263 |
+
Returns:
|
| 264 |
+
Updated expert tokens after self-attn residual, optional cross-attn, and MLP.
|
| 265 |
+
"""
|
| 266 |
+
|
| 267 |
+
def _post_fn(
|
| 268 |
+
_mixed_slice: torch.Tensor,
|
| 269 |
+
_x: torch.Tensor,
|
| 270 |
+
_gate_msa: torch.Tensor,
|
| 271 |
+
_shift_mlp: torch.Tensor,
|
| 272 |
+
_scale_mlp: torch.Tensor,
|
| 273 |
+
_gate_mlp: torch.Tensor,
|
| 274 |
+
_block=block,
|
| 275 |
+
_context_payload=context_payload,
|
| 276 |
+
) -> torch.Tensor:
|
| 277 |
+
return self._apply_expert_post_block(
|
| 278 |
+
block=_block,
|
| 279 |
+
residual_x=_x,
|
| 280 |
+
mixed_attn_out=_mixed_slice,
|
| 281 |
+
gate_msa=_gate_msa,
|
| 282 |
+
shift_mlp=_shift_mlp,
|
| 283 |
+
scale_mlp=_scale_mlp,
|
| 284 |
+
gate_mlp=_gate_mlp,
|
| 285 |
+
context_payload=_context_payload,
|
| 286 |
+
)
|
| 287 |
+
|
| 288 |
+
if use_gradient_checkpointing and self.training:
|
| 289 |
+
return torch.utils.checkpoint.checkpoint(
|
| 290 |
+
_post_fn,
|
| 291 |
+
mixed_slice,
|
| 292 |
+
residual_x,
|
| 293 |
+
gate_msa,
|
| 294 |
+
shift_mlp,
|
| 295 |
+
scale_mlp,
|
| 296 |
+
gate_mlp,
|
| 297 |
+
use_reentrant=False,
|
| 298 |
+
)
|
| 299 |
+
return _post_fn(
|
| 300 |
+
mixed_slice,
|
| 301 |
+
residual_x,
|
| 302 |
+
gate_msa,
|
| 303 |
+
shift_mlp,
|
| 304 |
+
scale_mlp,
|
| 305 |
+
gate_mlp,
|
| 306 |
+
)
|
| 307 |
+
|
| 308 |
+
def prefill_video_cache(
|
| 309 |
+
self,
|
| 310 |
+
video_tokens: torch.Tensor,
|
| 311 |
+
video_freqs: torch.Tensor,
|
| 312 |
+
video_t_mod: torch.Tensor,
|
| 313 |
+
video_context_payload: Optional[dict],
|
| 314 |
+
video_attention_mask: torch.Tensor,
|
| 315 |
+
) -> list[dict[str, torch.Tensor]]:
|
| 316 |
+
"""Prefill video branch once and cache per-layer K/V for action denoising.
|
| 317 |
+
|
| 318 |
+
Args:
|
| 319 |
+
video_tokens: Video tokens before layer 0, shape [B, Sv, D].
|
| 320 |
+
video_freqs: Video RoPE frequencies, shape [Sv, 1, rope_dim].
|
| 321 |
+
video_t_mod: Video time modulation tensor.
|
| 322 |
+
video_context_payload: Optional dict for video cross-attention.
|
| 323 |
+
- `context`: encoder states [B, L, D]
|
| 324 |
+
- `mask`: attention mask [B, Sv, L] or [B, 1, Sv, L]
|
| 325 |
+
video_attention_mask: Video self-attention mask, shape [Sv, Sv].
|
| 326 |
+
|
| 327 |
+
Returns:
|
| 328 |
+
Layer-wise cache list with length `num_layers`.
|
| 329 |
+
Each entry contains:
|
| 330 |
+
- `k`: video key tensor [B, Sv, H*Dh]
|
| 331 |
+
- `v`: video value tensor [B, Sv, H*Dh]
|
| 332 |
+
"""
|
| 333 |
+
if "video" not in self.mixtures:
|
| 334 |
+
raise ValueError("MoT requires `video` expert for `prefill_video_cache`.")
|
| 335 |
+
if video_attention_mask.ndim != 2:
|
| 336 |
+
raise ValueError(
|
| 337 |
+
f"`video_attention_mask` must be 2D [S,S], got shape {tuple(video_attention_mask.shape)}"
|
| 338 |
+
)
|
| 339 |
+
if video_attention_mask.shape[0] != video_attention_mask.shape[1]:
|
| 340 |
+
raise ValueError(
|
| 341 |
+
f"`video_attention_mask` must be square, got shape {tuple(video_attention_mask.shape)}"
|
| 342 |
+
)
|
| 343 |
+
if video_attention_mask.shape[0] != video_tokens.shape[1]:
|
| 344 |
+
raise ValueError(
|
| 345 |
+
"`video_attention_mask` seq length mismatch: "
|
| 346 |
+
f"mask={video_attention_mask.shape[0]} vs tokens={video_tokens.shape[1]}"
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
expert = self.mixtures["video"]
|
| 350 |
+
x = video_tokens
|
| 351 |
+
kv_cache: list[dict[str, torch.Tensor]] = []
|
| 352 |
+
for layer_idx in range(self.num_layers):
|
| 353 |
+
block = expert.blocks[layer_idx]
|
| 354 |
+
# Build video Q/K/V from current layer input tokens.
|
| 355 |
+
(
|
| 356 |
+
q,
|
| 357 |
+
k,
|
| 358 |
+
v,
|
| 359 |
+
residual_x,
|
| 360 |
+
gate_msa,
|
| 361 |
+
shift_mlp,
|
| 362 |
+
scale_mlp,
|
| 363 |
+
gate_mlp,
|
| 364 |
+
use_gradient_checkpointing,
|
| 365 |
+
) = self._build_expert_attention_io(
|
| 366 |
+
expert=expert,
|
| 367 |
+
block=block,
|
| 368 |
+
x=x,
|
| 369 |
+
freqs=video_freqs,
|
| 370 |
+
t_mod=video_t_mod,
|
| 371 |
+
)
|
| 372 |
+
# Video prefill uses only video self-attention mask.
|
| 373 |
+
mixed = self._mixed_attention(
|
| 374 |
+
q_cat=q,
|
| 375 |
+
k_cat=k,
|
| 376 |
+
v_cat=v,
|
| 377 |
+
attention_mask=video_attention_mask,
|
| 378 |
+
)
|
| 379 |
+
# Update video tokens for the next layer and persist current layer K/V.
|
| 380 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 381 |
+
block=block,
|
| 382 |
+
residual_x=residual_x,
|
| 383 |
+
gate_msa=gate_msa,
|
| 384 |
+
shift_mlp=shift_mlp,
|
| 385 |
+
scale_mlp=scale_mlp,
|
| 386 |
+
gate_mlp=gate_mlp,
|
| 387 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 388 |
+
mixed_slice=mixed,
|
| 389 |
+
context_payload=video_context_payload,
|
| 390 |
+
)
|
| 391 |
+
kv_cache.append({"k": k, "v": v})
|
| 392 |
+
return kv_cache
|
| 393 |
+
|
| 394 |
+
def forward_action_with_video_cache(
|
| 395 |
+
self,
|
| 396 |
+
action_tokens: torch.Tensor,
|
| 397 |
+
action_freqs: torch.Tensor,
|
| 398 |
+
action_t_mod: torch.Tensor,
|
| 399 |
+
action_context_payload: Optional[dict],
|
| 400 |
+
video_kv_cache: list[dict[str, torch.Tensor]],
|
| 401 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 402 |
+
video_seq_len: int,
|
| 403 |
+
) -> torch.Tensor:
|
| 404 |
+
"""Run action branch with cached video K/V instead of recomputing video tokens.
|
| 405 |
+
|
| 406 |
+
Args:
|
| 407 |
+
action_tokens: Action tokens before layer 0, shape [B, Sa, D].
|
| 408 |
+
action_freqs: Action RoPE frequencies, shape [Sa, 1, rope_dim].
|
| 409 |
+
action_t_mod: Action time modulation tensor.
|
| 410 |
+
action_context_payload: Optional dict for action cross-attention.
|
| 411 |
+
- `context`: encoder states [B, L, D]
|
| 412 |
+
- `mask`: attention mask [B, Sa, L] or [B, 1, Sa, L]
|
| 413 |
+
video_kv_cache: Layer-wise cached video K/V from `prefill_video_cache`.
|
| 414 |
+
attention_mask: Joint [video+action] mask, shape [Sv+Sa, Sv+Sa].
|
| 415 |
+
video_seq_len: Video token count `Sv` in the joint sequence prefix.
|
| 416 |
+
|
| 417 |
+
Returns:
|
| 418 |
+
Updated action tokens after all layers, shape [B, Sa, D].
|
| 419 |
+
"""
|
| 420 |
+
if "action" not in self.mixtures:
|
| 421 |
+
raise ValueError("MoT requires `action` expert for `forward_action_with_video_cache`.")
|
| 422 |
+
if len(video_kv_cache) != self.num_layers:
|
| 423 |
+
raise ValueError(
|
| 424 |
+
f"`video_kv_cache` must contain {self.num_layers} layers, got {len(video_kv_cache)}."
|
| 425 |
+
)
|
| 426 |
+
|
| 427 |
+
action_seq_len = int(action_tokens.shape[1])
|
| 428 |
+
total_seq_len = int(video_seq_len) + action_seq_len
|
| 429 |
+
attention_masks = self._resolve_attention_masks(
|
| 430 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 431 |
+
)
|
| 432 |
+
|
| 433 |
+
expert = self.mixtures["action"]
|
| 434 |
+
x = action_tokens
|
| 435 |
+
for layer_idx in range(self.num_layers):
|
| 436 |
+
block = expert.blocks[layer_idx]
|
| 437 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 438 |
+
action_attention_mask = layer_attention_mask[
|
| 439 |
+
video_seq_len:total_seq_len, :total_seq_len
|
| 440 |
+
]
|
| 441 |
+
# Action query/key/value are still step-dependent and must be recomputed each step.
|
| 442 |
+
(
|
| 443 |
+
q_action,
|
| 444 |
+
k_action,
|
| 445 |
+
v_action,
|
| 446 |
+
residual_x,
|
| 447 |
+
gate_msa,
|
| 448 |
+
shift_mlp,
|
| 449 |
+
scale_mlp,
|
| 450 |
+
gate_mlp,
|
| 451 |
+
use_gradient_checkpointing,
|
| 452 |
+
) = self._build_expert_attention_io(
|
| 453 |
+
expert=expert,
|
| 454 |
+
block=block,
|
| 455 |
+
x=x,
|
| 456 |
+
freqs=action_freqs,
|
| 457 |
+
t_mod=action_t_mod,
|
| 458 |
+
)
|
| 459 |
+
layer_cache = video_kv_cache[layer_idx]
|
| 460 |
+
if "k" not in layer_cache or "v" not in layer_cache:
|
| 461 |
+
raise ValueError(f"`video_kv_cache[{layer_idx}]` must contain `k` and `v`.")
|
| 462 |
+
|
| 463 |
+
k_video = layer_cache["k"]
|
| 464 |
+
v_video = layer_cache["v"]
|
| 465 |
+
if k_video.shape[1] != video_seq_len or v_video.shape[1] != video_seq_len:
|
| 466 |
+
raise ValueError(
|
| 467 |
+
f"`video_kv_cache[{layer_idx}]` seq len mismatch, expected {video_seq_len}."
|
| 468 |
+
)
|
| 469 |
+
|
| 470 |
+
# Mixed attention: action queries attend to cached video K/V plus current action K/V.
|
| 471 |
+
k_cat = torch.cat([k_video, k_action], dim=1)
|
| 472 |
+
v_cat = torch.cat([v_video, v_action], dim=1)
|
| 473 |
+
mixed = self._mixed_attention(
|
| 474 |
+
q_cat=q_action,
|
| 475 |
+
k_cat=k_cat,
|
| 476 |
+
v_cat=v_cat,
|
| 477 |
+
attention_mask=action_attention_mask,
|
| 478 |
+
)
|
| 479 |
+
x = self._apply_post_with_optional_checkpoint(
|
| 480 |
+
block=block,
|
| 481 |
+
residual_x=residual_x,
|
| 482 |
+
gate_msa=gate_msa,
|
| 483 |
+
shift_mlp=shift_mlp,
|
| 484 |
+
scale_mlp=scale_mlp,
|
| 485 |
+
gate_mlp=gate_mlp,
|
| 486 |
+
use_gradient_checkpointing=use_gradient_checkpointing,
|
| 487 |
+
mixed_slice=mixed,
|
| 488 |
+
context_payload=action_context_payload,
|
| 489 |
+
)
|
| 490 |
+
return x
|
| 491 |
+
|
| 492 |
+
def forward(
|
| 493 |
+
self,
|
| 494 |
+
embeds_all: Dict[str, torch.Tensor],
|
| 495 |
+
attention_mask: torch.Tensor | Sequence[torch.Tensor],
|
| 496 |
+
freqs_all: Dict[str, torch.Tensor],
|
| 497 |
+
context_all: Dict[str, Optional[dict]],
|
| 498 |
+
t_mod_all: Dict[str, torch.Tensor],
|
| 499 |
+
):
|
| 500 |
+
missing = [k for k in self.expert_order if k not in embeds_all]
|
| 501 |
+
if missing:
|
| 502 |
+
raise ValueError(f"Missing expert tokens for {missing}")
|
| 503 |
+
missing = [k for k in self.expert_order if k not in freqs_all]
|
| 504 |
+
if missing:
|
| 505 |
+
raise ValueError(f"Missing expert freqs for {missing}")
|
| 506 |
+
missing = [k for k in self.expert_order if k not in t_mod_all]
|
| 507 |
+
if missing:
|
| 508 |
+
raise ValueError(f"Missing expert t_mod for {missing}")
|
| 509 |
+
|
| 510 |
+
tokens_all = {k: v for k, v in embeds_all.items()}
|
| 511 |
+
total_seq_len = sum(int(tokens_all[name].shape[1]) for name in self.expert_order)
|
| 512 |
+
attention_masks = self._resolve_attention_masks(
|
| 513 |
+
attention_mask, expected_seq_len=total_seq_len
|
| 514 |
+
)
|
| 515 |
+
|
| 516 |
+
for layer_idx in range(self.num_layers):
|
| 517 |
+
q_chunks = []
|
| 518 |
+
k_chunks = []
|
| 519 |
+
v_chunks = []
|
| 520 |
+
cached = {}
|
| 521 |
+
seq_lens = []
|
| 522 |
+
|
| 523 |
+
for name in self.expert_order:
|
| 524 |
+
expert = self.mixtures[name]
|
| 525 |
+
block = expert.blocks[layer_idx]
|
| 526 |
+
x = tokens_all[name]
|
| 527 |
+
freqs = freqs_all[name]
|
| 528 |
+
t_mod = t_mod_all[name]
|
| 529 |
+
|
| 530 |
+
(
|
| 531 |
+
q,
|
| 532 |
+
k,
|
| 533 |
+
v,
|
| 534 |
+
residual_x,
|
| 535 |
+
gate_msa,
|
| 536 |
+
shift_mlp,
|
| 537 |
+
scale_mlp,
|
| 538 |
+
gate_mlp,
|
| 539 |
+
use_gradient_checkpointing,
|
| 540 |
+
) = self._build_expert_attention_io(
|
| 541 |
+
expert=expert,
|
| 542 |
+
block=block,
|
| 543 |
+
x=x,
|
| 544 |
+
freqs=freqs,
|
| 545 |
+
t_mod=t_mod,
|
| 546 |
+
)
|
| 547 |
+
|
| 548 |
+
q_chunks.append(q)
|
| 549 |
+
k_chunks.append(k)
|
| 550 |
+
v_chunks.append(v)
|
| 551 |
+
seq_lens.append(x.shape[1])
|
| 552 |
+
cached[name] = {
|
| 553 |
+
"block": block,
|
| 554 |
+
"residual_x": residual_x,
|
| 555 |
+
"gate_msa": gate_msa,
|
| 556 |
+
"shift_mlp": shift_mlp,
|
| 557 |
+
"scale_mlp": scale_mlp,
|
| 558 |
+
"gate_mlp": gate_mlp,
|
| 559 |
+
"use_gradient_checkpointing": use_gradient_checkpointing,
|
| 560 |
+
}
|
| 561 |
+
|
| 562 |
+
# 3. concat all tokens for mixed attention
|
| 563 |
+
q_cat = torch.cat(q_chunks, dim=1)
|
| 564 |
+
k_cat = torch.cat(k_chunks, dim=1)
|
| 565 |
+
v_cat = torch.cat(v_chunks, dim=1)
|
| 566 |
+
|
| 567 |
+
total_seq = q_cat.shape[1]
|
| 568 |
+
layer_attention_mask = attention_masks[layer_idx]
|
| 569 |
+
if layer_attention_mask.shape[-1] != total_seq:
|
| 570 |
+
raise ValueError(
|
| 571 |
+
"Attention mask seq length mismatch: "
|
| 572 |
+
f"mask={layer_attention_mask.shape[-1]} vs tokens={total_seq}"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
mixed = self._mixed_attention(
|
| 576 |
+
q_cat=q_cat,
|
| 577 |
+
k_cat=k_cat,
|
| 578 |
+
v_cat=v_cat,
|
| 579 |
+
attention_mask=layer_attention_mask,
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
start = 0
|
| 583 |
+
for name, seq_len in zip(self.expert_order, seq_lens):
|
| 584 |
+
# 4. split mixed attention output and apply post-attention blocks for each expert
|
| 585 |
+
end = start + seq_len
|
| 586 |
+
mixed_slice = mixed[:, start:end, :]
|
| 587 |
+
cached_expert = cached[name]
|
| 588 |
+
block = cached_expert["block"]
|
| 589 |
+
context_payload = context_all.get(name)
|
| 590 |
+
|
| 591 |
+
updated_tokens = self._apply_post_with_optional_checkpoint(
|
| 592 |
+
block=block,
|
| 593 |
+
residual_x=cached_expert["residual_x"],
|
| 594 |
+
gate_msa=cached_expert["gate_msa"],
|
| 595 |
+
shift_mlp=cached_expert["shift_mlp"],
|
| 596 |
+
scale_mlp=cached_expert["scale_mlp"],
|
| 597 |
+
gate_mlp=cached_expert["gate_mlp"],
|
| 598 |
+
use_gradient_checkpointing=cached_expert["use_gradient_checkpointing"],
|
| 599 |
+
mixed_slice=mixed_slice,
|
| 600 |
+
context_payload=context_payload,
|
| 601 |
+
)
|
| 602 |
+
|
| 603 |
+
tokens_all[name] = updated_tokens
|
| 604 |
+
start = end
|
| 605 |
+
|
| 606 |
+
return tokens_all
|
tools/model_code/recorded/language/wan22/schedulers/__init__.py
ADDED
|
File without changes
|
tools/model_code/recorded/language/wan22/schedulers/scheduler_continuous.py
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class WanContinuousFlowMatchScheduler:
|
| 5 |
+
"""Continuous-time Flow-Matching scheduler with shift-based sampling."""
|
| 6 |
+
|
| 7 |
+
def __init__(self, num_train_timesteps: int = 1000, shift: float = 5.0, eps: float = 1e-10):
|
| 8 |
+
if num_train_timesteps <= 0:
|
| 9 |
+
raise ValueError(f"`num_train_timesteps` must be positive, got {num_train_timesteps}")
|
| 10 |
+
if shift <= 0:
|
| 11 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 12 |
+
self.num_train_timesteps = int(num_train_timesteps)
|
| 13 |
+
self.shift = float(shift)
|
| 14 |
+
self.eps = float(eps)
|
| 15 |
+
self._y_min, self._weight_norm_const = self._precompute_training_weight_stats()
|
| 16 |
+
|
| 17 |
+
@staticmethod
|
| 18 |
+
def _phi(u: torch.Tensor, shift: float) -> torch.Tensor:
|
| 19 |
+
return shift * u / (1.0 + (shift - 1.0) * u)
|
| 20 |
+
|
| 21 |
+
def _precompute_training_weight_stats(self) -> tuple[float, float]:
|
| 22 |
+
steps = self.num_train_timesteps
|
| 23 |
+
u_grid = torch.linspace(1.0, 0.0, steps + 1, dtype=torch.float64)[:-1]
|
| 24 |
+
t_grid = self._phi(u_grid, self.shift) * float(steps)
|
| 25 |
+
y_grid = torch.exp(-2.0 * ((t_grid - (steps / 2.0)) / steps) ** 2)
|
| 26 |
+
y_min = float(y_grid.min().item())
|
| 27 |
+
y_shifted_grid = y_grid - y_min
|
| 28 |
+
norm_const = float(y_shifted_grid.mean().item())
|
| 29 |
+
return y_min, norm_const
|
| 30 |
+
|
| 31 |
+
def sample_training_t(
|
| 32 |
+
self, batch_size: int, device: torch.device, dtype: torch.dtype
|
| 33 |
+
) -> torch.Tensor:
|
| 34 |
+
if batch_size <= 0:
|
| 35 |
+
raise ValueError(f"`batch_size` must be positive, got {batch_size}")
|
| 36 |
+
u = torch.rand((batch_size,), device=device, dtype=torch.float32)
|
| 37 |
+
sigma = self._phi(u, self.shift)
|
| 38 |
+
timestep = sigma * float(self.num_train_timesteps)
|
| 39 |
+
return timestep.to(dtype=dtype)
|
| 40 |
+
|
| 41 |
+
def training_weight(self, timestep: torch.Tensor) -> torch.Tensor:
|
| 42 |
+
t = timestep.to(dtype=torch.float32)
|
| 43 |
+
steps = float(self.num_train_timesteps)
|
| 44 |
+
y = torch.exp(-2.0 * ((t - (steps / 2.0)) / steps) ** 2)
|
| 45 |
+
y_shifted = y - self._y_min
|
| 46 |
+
weight = y_shifted / (self._weight_norm_const + self.eps)
|
| 47 |
+
if weight.numel() == 1:
|
| 48 |
+
return weight.reshape(())
|
| 49 |
+
return weight
|
| 50 |
+
|
| 51 |
+
def add_noise(
|
| 52 |
+
self, original_samples: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 53 |
+
) -> torch.Tensor:
|
| 54 |
+
sigma = (timestep / float(self.num_train_timesteps)).to(
|
| 55 |
+
original_samples.device, dtype=original_samples.dtype
|
| 56 |
+
)
|
| 57 |
+
if sigma.ndim == 0:
|
| 58 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 59 |
+
sigma = sigma.view(-1, *([1] * (original_samples.ndim - 1)))
|
| 60 |
+
return (1 - sigma) * original_samples + sigma * noise
|
| 61 |
+
|
| 62 |
+
@staticmethod
|
| 63 |
+
def training_target(
|
| 64 |
+
sample: torch.Tensor, noise: torch.Tensor, timestep: torch.Tensor
|
| 65 |
+
) -> torch.Tensor:
|
| 66 |
+
del timestep
|
| 67 |
+
return noise - sample
|
| 68 |
+
|
| 69 |
+
def build_inference_schedule(
|
| 70 |
+
self,
|
| 71 |
+
num_inference_steps: int,
|
| 72 |
+
device: torch.device,
|
| 73 |
+
dtype: torch.dtype,
|
| 74 |
+
shift_override: float | None = None,
|
| 75 |
+
) -> tuple[torch.Tensor, torch.Tensor]:
|
| 76 |
+
if num_inference_steps <= 0:
|
| 77 |
+
raise ValueError(f"`num_inference_steps` must be positive, got {num_inference_steps}")
|
| 78 |
+
shift = self.shift if shift_override is None else float(shift_override)
|
| 79 |
+
if shift <= 0:
|
| 80 |
+
raise ValueError(f"`shift` must be positive, got {shift}")
|
| 81 |
+
|
| 82 |
+
u_steps = torch.linspace(
|
| 83 |
+
1.0, 0.0, num_inference_steps + 1, device=device, dtype=torch.float32
|
| 84 |
+
)
|
| 85 |
+
sigma_steps = self._phi(u_steps, shift)
|
| 86 |
+
timesteps = sigma_steps[:-1] * float(self.num_train_timesteps)
|
| 87 |
+
deltas = sigma_steps[1:] - sigma_steps[:-1]
|
| 88 |
+
return timesteps.to(dtype=dtype), deltas.to(dtype=dtype)
|
| 89 |
+
|
| 90 |
+
@staticmethod
|
| 91 |
+
def step(model_output: torch.Tensor, delta: torch.Tensor, sample: torch.Tensor) -> torch.Tensor:
|
| 92 |
+
delta = delta.to(sample.device, dtype=sample.dtype)
|
| 93 |
+
if delta.ndim == 0:
|
| 94 |
+
return sample + model_output * delta
|
| 95 |
+
delta = delta.view(-1, *([1] * (sample.ndim - 1)))
|
| 96 |
+
return sample + model_output * delta
|
tools/model_code/recorded/language/wan22/wan_video_dit.py
ADDED
|
@@ -0,0 +1,781 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
import torch.nn as nn
|
| 3 |
+
import torch.nn.functional as F
|
| 4 |
+
import math
|
| 5 |
+
from typing import Any, Dict, Tuple, Optional
|
| 6 |
+
from einops import rearrange
|
| 7 |
+
from .helpers.gradient import gradient_checkpoint_forward
|
| 8 |
+
|
| 9 |
+
from logging import getLogger as get_logger
|
| 10 |
+
|
| 11 |
+
logger = get_logger(__name__)
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
def flash_attention(
|
| 15 |
+
q: torch.Tensor,
|
| 16 |
+
k: torch.Tensor,
|
| 17 |
+
v: torch.Tensor,
|
| 18 |
+
num_heads: int,
|
| 19 |
+
ctx_mask: Optional[torch.Tensor] = None,
|
| 20 |
+
compatibility_mode=True,
|
| 21 |
+
):
|
| 22 |
+
if compatibility_mode:
|
| 23 |
+
q = rearrange(q, "b s (n d) -> b n s d", n=num_heads)
|
| 24 |
+
k = rearrange(k, "b s (n d) -> b n s d", n=num_heads)
|
| 25 |
+
v = rearrange(v, "b s (n d) -> b n s d", n=num_heads)
|
| 26 |
+
x = F.scaled_dot_product_attention(q, k, v, attn_mask=ctx_mask)
|
| 27 |
+
x = rearrange(x, "b n s d -> b s (n d)", n=num_heads)
|
| 28 |
+
return x
|
| 29 |
+
else:
|
| 30 |
+
raise NotImplementedError(
|
| 31 |
+
"Only compatibility mode is implemented for flash attention. Please set compatibility_mode=True."
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def modulate(x: torch.Tensor, shift: torch.Tensor, scale: torch.Tensor):
|
| 36 |
+
return x * (1 + scale) + shift
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def sinusoidal_embedding_1d(dim, position):
|
| 40 |
+
sinusoid = torch.outer(
|
| 41 |
+
position.type(torch.float64),
|
| 42 |
+
torch.pow(
|
| 43 |
+
10000,
|
| 44 |
+
-torch.arange(dim // 2, dtype=torch.float64, device=position.device).div(dim // 2),
|
| 45 |
+
),
|
| 46 |
+
)
|
| 47 |
+
x = torch.cat([torch.cos(sinusoid), torch.sin(sinusoid)], dim=1)
|
| 48 |
+
return x.to(position.dtype)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def precompute_freqs_cis_3d(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 52 |
+
# 3d rope precompute
|
| 53 |
+
f_freqs_cis = precompute_freqs_cis(dim - 2 * (dim // 3), end, theta)
|
| 54 |
+
h_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 55 |
+
w_freqs_cis = precompute_freqs_cis(dim // 3, end, theta)
|
| 56 |
+
return f_freqs_cis, h_freqs_cis, w_freqs_cis
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def precompute_freqs_cis(dim: int, end: int = 1024, theta: float = 10000.0):
|
| 60 |
+
# 1d rope precompute
|
| 61 |
+
freqs = 1.0 / (theta ** (torch.arange(0, dim, 2)[: (dim // 2)].double() / dim))
|
| 62 |
+
freqs = torch.outer(torch.arange(end, device=freqs.device), freqs)
|
| 63 |
+
freqs_cis = torch.polar(torch.ones_like(freqs), freqs) # complex64
|
| 64 |
+
return freqs_cis
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def rope_apply(x, freqs, num_heads):
|
| 68 |
+
x = rearrange(x, "b s (n d) -> b s n d", n=num_heads)
|
| 69 |
+
x_out = torch.view_as_complex(
|
| 70 |
+
x.to(torch.float64).reshape(x.shape[0], x.shape[1], x.shape[2], -1, 2)
|
| 71 |
+
)
|
| 72 |
+
freqs = freqs.to(torch.complex64) if freqs.device.type == "npu" else freqs
|
| 73 |
+
x_out = torch.view_as_real(x_out * freqs).flatten(2)
|
| 74 |
+
return x_out.to(x.dtype)
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def create_group_causal_attn_mask(
|
| 78 |
+
num_temporal_groups: int, num_query_per_group: int, num_key_per_group: int, mode: str = "causal"
|
| 79 |
+
) -> torch.Tensor:
|
| 80 |
+
"""
|
| 81 |
+
Creates a group-based attention mask for scaled dot-product attention with two modes:
|
| 82 |
+
'causal' and 'group_diagonal'.
|
| 83 |
+
|
| 84 |
+
Parameters:
|
| 85 |
+
- num_temporal_groups (int): The number of temporal groups (e.g., frames in a video sequence).
|
| 86 |
+
- num_query_per_group (int): The number of query tokens per temporal group. (e.g., latent tokens in a frame, H x W).
|
| 87 |
+
- num_key_per_group (int): The number of key tokens per temporal group. (e.g., action tokens per frame).
|
| 88 |
+
- mode (str): The mode of the attention mask. Options are:
|
| 89 |
+
- 'causal': Query tokens can attend to key tokens from the same or previous temporal groups.
|
| 90 |
+
- 'group_diagonal': Query tokens can attend only to key tokens from the same temporal group.
|
| 91 |
+
|
| 92 |
+
Returns:
|
| 93 |
+
- attn_mask (torch.Tensor): A boolean tensor of shape (L, S), where:
|
| 94 |
+
- L = num_temporal_groups * num_query_per_group (total number of query tokens)
|
| 95 |
+
- S = num_temporal_groups * num_key_per_group (total number of key tokens)
|
| 96 |
+
The mask indicates where attention is allowed (True) and disallowed (False).
|
| 97 |
+
|
| 98 |
+
Example:
|
| 99 |
+
Input:
|
| 100 |
+
num_temporal_groups = 3
|
| 101 |
+
num_query_per_group = 4
|
| 102 |
+
num_key_per_group = 2
|
| 103 |
+
Output:
|
| 104 |
+
Causal Mask Shape: torch.Size([12, 6])
|
| 105 |
+
Group Diagonal Mask Shape: torch.Size([12, 6])
|
| 106 |
+
if mode='causal':
|
| 107 |
+
tensor([[ True, True, False, False, False, False],
|
| 108 |
+
[ True, True, False, False, False, False],
|
| 109 |
+
[ True, True, False, False, False, False],
|
| 110 |
+
[ True, True, False, False, False, False],
|
| 111 |
+
[ True, True, True, True, False, False],
|
| 112 |
+
[ True, True, True, True, False, False],
|
| 113 |
+
[ True, True, True, True, False, False],
|
| 114 |
+
[ True, True, True, True, False, False],
|
| 115 |
+
[ True, True, True, True, True, True],
|
| 116 |
+
[ True, True, True, True, True, True],
|
| 117 |
+
[ True, True, True, True, True, True],
|
| 118 |
+
[ True, True, True, True, True, True]])
|
| 119 |
+
|
| 120 |
+
if mode='group_diagonal':
|
| 121 |
+
tensor([[ True, True, False, False, False, False],
|
| 122 |
+
[ True, True, False, False, False, False],
|
| 123 |
+
[ True, True, False, False, False, False],
|
| 124 |
+
[ True, True, False, False, False, False],
|
| 125 |
+
[False, False, True, True, False, False],
|
| 126 |
+
[False, False, True, True, False, False],
|
| 127 |
+
[False, False, True, True, False, False],
|
| 128 |
+
[False, False, True, True, False, False],
|
| 129 |
+
[False, False, False, False, True, True],
|
| 130 |
+
[False, False, False, False, True, True],
|
| 131 |
+
[False, False, False, False, True, True],
|
| 132 |
+
[False, False, False, False, True, True]])
|
| 133 |
+
|
| 134 |
+
"""
|
| 135 |
+
assert mode in ["causal", "group_diagonal"], f"Mode {mode} must be 'causal' or 'group_diagonal'"
|
| 136 |
+
|
| 137 |
+
# Total number of query and key tokens
|
| 138 |
+
total_num_query_tokens = (
|
| 139 |
+
num_temporal_groups * num_query_per_group
|
| 140 |
+
) # Total number of query tokens (L)
|
| 141 |
+
total_num_key_tokens = num_temporal_groups * num_key_per_group # Total number of key tokens (S)
|
| 142 |
+
|
| 143 |
+
# Generate time indices for query and key tokens (shape: [L] and [S])
|
| 144 |
+
query_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 145 |
+
num_query_per_group
|
| 146 |
+
) # Shape: [L]
|
| 147 |
+
key_time_indices = torch.arange(num_temporal_groups).repeat_interleave(
|
| 148 |
+
num_key_per_group
|
| 149 |
+
) # Shape: [S]
|
| 150 |
+
|
| 151 |
+
# Expand dimensions to compute outer comparison
|
| 152 |
+
query_time_indices = query_time_indices.unsqueeze(1) # Shape: [L, 1]
|
| 153 |
+
key_time_indices = key_time_indices.unsqueeze(0) # Shape: [1, S]
|
| 154 |
+
|
| 155 |
+
if mode == "causal":
|
| 156 |
+
# Causal Mode: Query can attend to keys where key_time <= query_time
|
| 157 |
+
attn_mask = query_time_indices >= key_time_indices # Shape: [L, S]
|
| 158 |
+
elif mode == "group_diagonal":
|
| 159 |
+
# Group Diagonal Mode: Query can attend only to keys where key_time == query_time
|
| 160 |
+
attn_mask = query_time_indices == key_time_indices # Shape: [L, S]
|
| 161 |
+
|
| 162 |
+
assert attn_mask.shape == (
|
| 163 |
+
total_num_query_tokens,
|
| 164 |
+
total_num_key_tokens,
|
| 165 |
+
), "Attention mask shape mismatch"
|
| 166 |
+
return attn_mask
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class RMSNorm(nn.Module):
|
| 170 |
+
def __init__(self, dim, eps=1e-5):
|
| 171 |
+
super().__init__()
|
| 172 |
+
self.eps = eps
|
| 173 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 174 |
+
|
| 175 |
+
def norm(self, x):
|
| 176 |
+
return x * torch.rsqrt(x.pow(2).mean(dim=-1, keepdim=True) + self.eps)
|
| 177 |
+
|
| 178 |
+
def forward(self, x):
|
| 179 |
+
dtype = x.dtype
|
| 180 |
+
return self.norm(x.float()).to(dtype) * self.weight
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
class AttentionModule(nn.Module):
|
| 184 |
+
def __init__(self, num_heads):
|
| 185 |
+
super().__init__()
|
| 186 |
+
self.num_heads = num_heads
|
| 187 |
+
|
| 188 |
+
def forward(self, q, k, v, ctx_mask=None):
|
| 189 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 190 |
+
return x
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SelfAttention(nn.Module):
|
| 194 |
+
def __init__(self, hidden_dim: int, attn_head_dim: int, num_heads: int, eps: float = 1e-6):
|
| 195 |
+
super().__init__()
|
| 196 |
+
self.hidden_dim = hidden_dim
|
| 197 |
+
self.num_heads = num_heads
|
| 198 |
+
self.attn_head_dim = attn_head_dim
|
| 199 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 200 |
+
|
| 201 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 202 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 203 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 204 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 205 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 206 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 207 |
+
|
| 208 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 209 |
+
|
| 210 |
+
def forward(self, x, freqs, self_attn_mask: Optional[torch.Tensor] = None):
|
| 211 |
+
q = self.norm_q(self.q(x))
|
| 212 |
+
k = self.norm_k(self.k(x))
|
| 213 |
+
v = self.v(x)
|
| 214 |
+
q = rope_apply(q, freqs, self.num_heads)
|
| 215 |
+
k = rope_apply(k, freqs, self.num_heads)
|
| 216 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=self_attn_mask)
|
| 217 |
+
return self.o(x)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class CrossAttention(nn.Module):
|
| 221 |
+
def __init__(
|
| 222 |
+
self,
|
| 223 |
+
hidden_dim: int,
|
| 224 |
+
attn_head_dim: int,
|
| 225 |
+
num_heads: int,
|
| 226 |
+
eps: float = 1e-6,
|
| 227 |
+
):
|
| 228 |
+
super().__init__()
|
| 229 |
+
self.hidden_dim = hidden_dim
|
| 230 |
+
self.num_heads = num_heads
|
| 231 |
+
self.attn_head_dim = attn_head_dim
|
| 232 |
+
self.attn_hidden_dim = self.num_heads * self.attn_head_dim
|
| 233 |
+
|
| 234 |
+
self.q = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 235 |
+
self.k = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 236 |
+
self.v = nn.Linear(hidden_dim, self.attn_hidden_dim)
|
| 237 |
+
self.o = nn.Linear(self.attn_hidden_dim, hidden_dim)
|
| 238 |
+
self.norm_q = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 239 |
+
self.norm_k = RMSNorm(self.attn_hidden_dim, eps=eps)
|
| 240 |
+
|
| 241 |
+
# self.attn = AttentionModule(self.num_heads)
|
| 242 |
+
|
| 243 |
+
def forward(self, x: torch.Tensor, ctx: torch.Tensor, ctx_mask: Optional[torch.Tensor] = None):
|
| 244 |
+
q = self.norm_q(self.q(x))
|
| 245 |
+
k = self.norm_k(self.k(ctx))
|
| 246 |
+
v = self.v(ctx)
|
| 247 |
+
x = flash_attention(q=q, k=k, v=v, num_heads=self.num_heads, ctx_mask=ctx_mask)
|
| 248 |
+
return self.o(x)
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
class GateModule(nn.Module):
|
| 252 |
+
def __init__(
|
| 253 |
+
self,
|
| 254 |
+
):
|
| 255 |
+
super().__init__()
|
| 256 |
+
|
| 257 |
+
def forward(self, x, gate, residual):
|
| 258 |
+
return x + gate * residual
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class DiTBlock(nn.Module):
|
| 262 |
+
def __init__(
|
| 263 |
+
self, hidden_dim: int, attn_head_dim: int, num_heads: int, ffn_dim: int, eps: float = 1e-6
|
| 264 |
+
):
|
| 265 |
+
super().__init__()
|
| 266 |
+
self.hidden_dim = hidden_dim
|
| 267 |
+
self.attn_head_dim = attn_head_dim
|
| 268 |
+
self.num_heads = num_heads
|
| 269 |
+
self.ffn_dim = ffn_dim
|
| 270 |
+
|
| 271 |
+
self.self_attn = SelfAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 272 |
+
self.cross_attn = CrossAttention(hidden_dim, attn_head_dim, num_heads, eps)
|
| 273 |
+
self.norm1 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 274 |
+
self.norm2 = nn.LayerNorm(hidden_dim, eps=eps, elementwise_affine=False)
|
| 275 |
+
self.norm3 = nn.LayerNorm(hidden_dim, eps=eps)
|
| 276 |
+
self.ffn = nn.Sequential(
|
| 277 |
+
nn.Linear(hidden_dim, ffn_dim),
|
| 278 |
+
nn.GELU(approximate="tanh"),
|
| 279 |
+
nn.Linear(ffn_dim, hidden_dim),
|
| 280 |
+
)
|
| 281 |
+
self.modulation = nn.Parameter(torch.randn(1, 6, hidden_dim) / hidden_dim**0.5)
|
| 282 |
+
self.gate = GateModule()
|
| 283 |
+
|
| 284 |
+
def forward(
|
| 285 |
+
self,
|
| 286 |
+
x,
|
| 287 |
+
context,
|
| 288 |
+
t_mod,
|
| 289 |
+
freqs,
|
| 290 |
+
context_mask=None,
|
| 291 |
+
self_attn_mask: Optional[torch.Tensor] = None,
|
| 292 |
+
):
|
| 293 |
+
if context_mask is not None and context_mask.dim() == 3:
|
| 294 |
+
context_mask = context_mask.unsqueeze(1) # (B, 1, seq_len, context_len), 1 for heads
|
| 295 |
+
has_seq = len(t_mod.shape) == 4
|
| 296 |
+
chunk_dim = 2 if has_seq else 1
|
| 297 |
+
# msa: multi-head self-attention mlp: multi-layer perceptron
|
| 298 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 299 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 300 |
+
).chunk(6, dim=chunk_dim)
|
| 301 |
+
if has_seq:
|
| 302 |
+
# means t_mod has separate modulation for each token, otherwise same modulation for all tokens in the block
|
| 303 |
+
shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
|
| 304 |
+
shift_msa.squeeze(2),
|
| 305 |
+
scale_msa.squeeze(2),
|
| 306 |
+
gate_msa.squeeze(2),
|
| 307 |
+
shift_mlp.squeeze(2),
|
| 308 |
+
scale_mlp.squeeze(2),
|
| 309 |
+
gate_mlp.squeeze(2),
|
| 310 |
+
)
|
| 311 |
+
input_x = modulate(self.norm1(x), shift_msa, scale_msa)
|
| 312 |
+
x = self.gate(x, gate_msa, self.self_attn(input_x, freqs, self_attn_mask=self_attn_mask))
|
| 313 |
+
x = x + self.cross_attn(self.norm3(x), context, ctx_mask=context_mask)
|
| 314 |
+
input_x = modulate(self.norm2(x), shift_mlp, scale_mlp)
|
| 315 |
+
x = self.gate(x, gate_mlp, self.ffn(input_x))
|
| 316 |
+
return x
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
class MLP(torch.nn.Module):
|
| 320 |
+
def __init__(self, in_dim, out_dim, has_pos_emb=False):
|
| 321 |
+
super().__init__()
|
| 322 |
+
self.proj = torch.nn.Sequential(
|
| 323 |
+
nn.LayerNorm(in_dim),
|
| 324 |
+
nn.Linear(in_dim, in_dim),
|
| 325 |
+
nn.GELU(),
|
| 326 |
+
nn.Linear(in_dim, out_dim),
|
| 327 |
+
nn.LayerNorm(out_dim),
|
| 328 |
+
)
|
| 329 |
+
self.has_pos_emb = has_pos_emb
|
| 330 |
+
if has_pos_emb:
|
| 331 |
+
self.emb_pos = torch.nn.Parameter(torch.zeros((1, 514, 1280)))
|
| 332 |
+
|
| 333 |
+
def forward(self, x):
|
| 334 |
+
if self.has_pos_emb:
|
| 335 |
+
x = x + self.emb_pos.to(dtype=x.dtype, device=x.device)
|
| 336 |
+
return self.proj(x)
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
class Head(nn.Module):
|
| 340 |
+
def __init__(self, dim: int, out_dim: int, patch_size: Tuple[int, int, int], eps: float):
|
| 341 |
+
super().__init__()
|
| 342 |
+
self.dim = dim
|
| 343 |
+
self.patch_size = patch_size
|
| 344 |
+
self.norm = nn.LayerNorm(dim, eps=eps, elementwise_affine=False)
|
| 345 |
+
self.head = nn.Linear(dim, out_dim * math.prod(patch_size))
|
| 346 |
+
self.modulation = nn.Parameter(torch.randn(1, 2, dim) / dim**0.5)
|
| 347 |
+
|
| 348 |
+
def forward(self, x, t_mod):
|
| 349 |
+
if len(t_mod.shape) == 3:
|
| 350 |
+
shift, scale = (
|
| 351 |
+
self.modulation.unsqueeze(0).to(dtype=t_mod.dtype, device=t_mod.device)
|
| 352 |
+
+ t_mod.unsqueeze(2)
|
| 353 |
+
).chunk(2, dim=2)
|
| 354 |
+
x = self.head(self.norm(x) * (1 + scale.squeeze(2)) + shift.squeeze(2))
|
| 355 |
+
else:
|
| 356 |
+
shift, scale = (
|
| 357 |
+
self.modulation.to(dtype=t_mod.dtype, device=t_mod.device) + t_mod
|
| 358 |
+
).chunk(2, dim=1)
|
| 359 |
+
x = self.head(self.norm(x) * (1 + scale) + shift)
|
| 360 |
+
return x
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
class WanVideoDiT(torch.nn.Module):
|
| 364 |
+
def __init__(
|
| 365 |
+
self,
|
| 366 |
+
hidden_dim: int,
|
| 367 |
+
in_dim: int,
|
| 368 |
+
ffn_dim: int,
|
| 369 |
+
out_dim: int,
|
| 370 |
+
text_dim: int,
|
| 371 |
+
freq_dim: int,
|
| 372 |
+
eps: float,
|
| 373 |
+
patch_size: Tuple[int, int, int],
|
| 374 |
+
num_heads: int,
|
| 375 |
+
attn_head_dim: int,
|
| 376 |
+
num_layers: int,
|
| 377 |
+
has_image_input: bool,
|
| 378 |
+
has_image_pos_emb: bool = False,
|
| 379 |
+
has_ref_conv: bool = False,
|
| 380 |
+
add_control_adapter: bool = False,
|
| 381 |
+
in_dim_control_adapter: int = 24,
|
| 382 |
+
seperated_timestep: bool = False,
|
| 383 |
+
require_vae_embedding: bool = False,
|
| 384 |
+
require_clip_embedding: bool = False,
|
| 385 |
+
fuse_vae_embedding_in_latents: bool = True,
|
| 386 |
+
action_conditioned: bool = False,
|
| 387 |
+
action_dim: int = 7,
|
| 388 |
+
action_group_causal_mask_mode="causal",
|
| 389 |
+
video_attention_mask_mode: str = "bidirectional",
|
| 390 |
+
use_gradient_checkpointing: bool = False,
|
| 391 |
+
):
|
| 392 |
+
super().__init__()
|
| 393 |
+
self.hidden_dim = hidden_dim
|
| 394 |
+
self.in_dim = in_dim
|
| 395 |
+
self.freq_dim = freq_dim
|
| 396 |
+
self.patch_size = patch_size
|
| 397 |
+
self.num_heads = num_heads
|
| 398 |
+
self.attn_head_dim = attn_head_dim
|
| 399 |
+
self.seperated_timestep = seperated_timestep
|
| 400 |
+
self.require_vae_embedding = require_vae_embedding
|
| 401 |
+
self.require_clip_embedding = require_clip_embedding
|
| 402 |
+
self.fuse_vae_embedding_in_latents = fuse_vae_embedding_in_latents
|
| 403 |
+
self.video_attention_mask_mode = str(video_attention_mask_mode)
|
| 404 |
+
|
| 405 |
+
if num_heads <= 0:
|
| 406 |
+
raise ValueError(f"`num_heads` must be > 0, got {num_heads}")
|
| 407 |
+
if attn_head_dim <= 0:
|
| 408 |
+
raise ValueError(f"`attn_head_dim` must be > 0, got {attn_head_dim}")
|
| 409 |
+
if attn_head_dim % 2 != 0:
|
| 410 |
+
raise ValueError(f"`attn_head_dim` must be even for RoPE, got {attn_head_dim}")
|
| 411 |
+
|
| 412 |
+
self.action_conditioned = action_conditioned
|
| 413 |
+
self.action_dim = action_dim
|
| 414 |
+
assert has_image_input == False
|
| 415 |
+
assert require_clip_embedding == False
|
| 416 |
+
assert (
|
| 417 |
+
require_vae_embedding == False and fuse_vae_embedding_in_latents == True
|
| 418 |
+
), "Only support fusing vae embedding in latents"
|
| 419 |
+
|
| 420 |
+
self.patch_embedding = nn.Conv3d(
|
| 421 |
+
in_dim, hidden_dim, kernel_size=patch_size, stride=patch_size
|
| 422 |
+
)
|
| 423 |
+
self.text_embedding = nn.Sequential(
|
| 424 |
+
nn.Linear(text_dim, hidden_dim),
|
| 425 |
+
nn.GELU(approximate="tanh"),
|
| 426 |
+
nn.Linear(hidden_dim, hidden_dim),
|
| 427 |
+
)
|
| 428 |
+
self.time_embedding = nn.Sequential(
|
| 429 |
+
nn.Linear(freq_dim, hidden_dim), nn.SiLU(), nn.Linear(hidden_dim, hidden_dim)
|
| 430 |
+
)
|
| 431 |
+
self.time_projection = nn.Sequential(nn.SiLU(), nn.Linear(hidden_dim, hidden_dim * 6))
|
| 432 |
+
self.blocks = nn.ModuleList(
|
| 433 |
+
[
|
| 434 |
+
DiTBlock(hidden_dim, attn_head_dim, num_heads, ffn_dim, eps)
|
| 435 |
+
for _ in range(num_layers)
|
| 436 |
+
]
|
| 437 |
+
)
|
| 438 |
+
self.head = Head(hidden_dim, out_dim, patch_size, eps)
|
| 439 |
+
self.freqs = precompute_freqs_cis_3d(attn_head_dim)
|
| 440 |
+
if has_ref_conv:
|
| 441 |
+
self.ref_conv = nn.Conv2d(16, hidden_dim, kernel_size=(2, 2), stride=(2, 2))
|
| 442 |
+
self.has_image_pos_emb = has_image_pos_emb
|
| 443 |
+
self.has_ref_conv = has_ref_conv
|
| 444 |
+
self.control_adapter = None
|
| 445 |
+
|
| 446 |
+
if self.action_conditioned:
|
| 447 |
+
self.action_embedding = nn.Linear(action_dim, hidden_dim)
|
| 448 |
+
self.action_group_causal_mask_mode = action_group_causal_mask_mode
|
| 449 |
+
|
| 450 |
+
self.use_gradient_checkpointing = use_gradient_checkpointing
|
| 451 |
+
if self.use_gradient_checkpointing:
|
| 452 |
+
logger.info(
|
| 453 |
+
"Using gradient checkpointing for DiT blocks. This will save memory but use more computation."
|
| 454 |
+
)
|
| 455 |
+
|
| 456 |
+
def patchify(
|
| 457 |
+
self, x: torch.Tensor, control_camera_latents_input: Optional[torch.Tensor] = None
|
| 458 |
+
):
|
| 459 |
+
x = self.patch_embedding(x)
|
| 460 |
+
if self.control_adapter is not None and control_camera_latents_input is not None:
|
| 461 |
+
y_camera = self.control_adapter(control_camera_latents_input)
|
| 462 |
+
x = [u + v for u, v in zip(x, y_camera)]
|
| 463 |
+
x = x[0].unsqueeze(0)
|
| 464 |
+
return x
|
| 465 |
+
|
| 466 |
+
def unpatchify(self, x: torch.Tensor, grid_size: torch.Tensor):
|
| 467 |
+
return rearrange(
|
| 468 |
+
x,
|
| 469 |
+
"b (f h w) (x y z c) -> b c (f x) (h y) (w z)",
|
| 470 |
+
f=grid_size[0],
|
| 471 |
+
h=grid_size[1],
|
| 472 |
+
w=grid_size[2],
|
| 473 |
+
x=self.patch_size[0],
|
| 474 |
+
y=self.patch_size[1],
|
| 475 |
+
z=self.patch_size[2],
|
| 476 |
+
)
|
| 477 |
+
|
| 478 |
+
def _validate_forward_inputs(
|
| 479 |
+
self,
|
| 480 |
+
x: torch.Tensor,
|
| 481 |
+
timestep: torch.Tensor,
|
| 482 |
+
context: torch.Tensor,
|
| 483 |
+
context_mask: Optional[torch.Tensor],
|
| 484 |
+
action: Optional[torch.Tensor],
|
| 485 |
+
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
|
| 486 |
+
if x.ndim != 5:
|
| 487 |
+
raise ValueError(f"`latents` must be 5D [B, C, T, H, W], got shape {tuple(x.shape)}")
|
| 488 |
+
num_latent_frames = x.shape[2]
|
| 489 |
+
if context.ndim != 3:
|
| 490 |
+
raise ValueError(f"`context` must be 3D [B, L, D], got shape {tuple(context.shape)}")
|
| 491 |
+
if timestep.ndim != 1:
|
| 492 |
+
raise ValueError(f"`timestep` must be 1D [B] or [1], got shape {tuple(timestep.shape)}")
|
| 493 |
+
if self.action_conditioned:
|
| 494 |
+
allow_text_only_single_frame = num_latent_frames == 1 and action is None
|
| 495 |
+
if not allow_text_only_single_frame:
|
| 496 |
+
assert action is not None, "Action input is required for action-conditioned model."
|
| 497 |
+
if action.ndim != 3:
|
| 498 |
+
raise ValueError(
|
| 499 |
+
f"`action` must be 3D [B, action_horizon, action_dim], got shape {tuple(action.shape)}"
|
| 500 |
+
)
|
| 501 |
+
if action.shape[2] != self.action_dim:
|
| 502 |
+
raise ValueError(
|
| 503 |
+
f"`action` last dimension must be {self.action_dim}, got {action.shape[2]}"
|
| 504 |
+
)
|
| 505 |
+
if num_latent_frames <= 1:
|
| 506 |
+
raise ValueError(
|
| 507 |
+
f"video length must be > 1 for action-conditioned model, got {num_latent_frames}"
|
| 508 |
+
)
|
| 509 |
+
if action.shape[1] % (num_latent_frames - 1) != 0:
|
| 510 |
+
raise ValueError(
|
| 511 |
+
f"action horizon must be divisible by (num_latent_frames - 1), got action_horizon={action.shape[1]}"
|
| 512 |
+
)
|
| 513 |
+
if context_mask is None:
|
| 514 |
+
context_mask = torch.ones(
|
| 515 |
+
(context.shape[0], context.shape[1]), dtype=torch.bool, device=context.device
|
| 516 |
+
)
|
| 517 |
+
else:
|
| 518 |
+
if context_mask.ndim != 2:
|
| 519 |
+
raise ValueError(
|
| 520 |
+
f"`context_mask` must be 2D [B, L], got shape {tuple(context_mask.shape)}"
|
| 521 |
+
)
|
| 522 |
+
if (
|
| 523 |
+
context_mask.shape[0] != context.shape[0]
|
| 524 |
+
or context_mask.shape[1] != context.shape[1]
|
| 525 |
+
):
|
| 526 |
+
raise ValueError(
|
| 527 |
+
f"`context_mask` shape must match `context` shape [B, L], got {tuple(context_mask.shape)} vs {tuple(context.shape)}"
|
| 528 |
+
)
|
| 529 |
+
|
| 530 |
+
batch_size = x.shape[0]
|
| 531 |
+
if batch_size != context.shape[0]:
|
| 532 |
+
if not self.training and batch_size == 1:
|
| 533 |
+
x = x.expand(context.shape[0], -1, -1, -1, -1)
|
| 534 |
+
batch_size = context.shape[0]
|
| 535 |
+
else:
|
| 536 |
+
raise ValueError(
|
| 537 |
+
f"Batch mismatch between latents and context: {batch_size} vs {context.shape[0]}."
|
| 538 |
+
)
|
| 539 |
+
|
| 540 |
+
if timestep.shape[0] not in (1, batch_size):
|
| 541 |
+
raise ValueError(
|
| 542 |
+
f"`timestep` length must be 1 or batch_size({batch_size}), got {timestep.shape[0]}"
|
| 543 |
+
)
|
| 544 |
+
if timestep.shape[0] == 1 and batch_size > 1:
|
| 545 |
+
assert not self.training, "During training, timestep length must match batch_size."
|
| 546 |
+
timestep = timestep.expand(batch_size)
|
| 547 |
+
return x, timestep, context_mask
|
| 548 |
+
|
| 549 |
+
def build_video_to_video_mask(
|
| 550 |
+
self,
|
| 551 |
+
video_seq_len: int,
|
| 552 |
+
video_tokens_per_frame: int,
|
| 553 |
+
device: torch.device,
|
| 554 |
+
) -> torch.Tensor:
|
| 555 |
+
if video_seq_len <= 0:
|
| 556 |
+
raise ValueError(f"`video_seq_len` must be positive, got {video_seq_len}")
|
| 557 |
+
if video_tokens_per_frame <= 0:
|
| 558 |
+
raise ValueError(
|
| 559 |
+
f"`video_tokens_per_frame` must be positive, got {video_tokens_per_frame}"
|
| 560 |
+
)
|
| 561 |
+
|
| 562 |
+
if self.video_attention_mask_mode == "bidirectional":
|
| 563 |
+
return torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 564 |
+
|
| 565 |
+
if self.video_attention_mask_mode == "per_frame_causal":
|
| 566 |
+
if video_seq_len % video_tokens_per_frame != 0:
|
| 567 |
+
raise ValueError(
|
| 568 |
+
"`video_seq_len` must be divisible by `video_tokens_per_frame` in `per_frame_causal` mode, "
|
| 569 |
+
f"got {video_seq_len} and {video_tokens_per_frame}"
|
| 570 |
+
)
|
| 571 |
+
num_video_frames = video_seq_len // video_tokens_per_frame
|
| 572 |
+
frame_causal = torch.tril(
|
| 573 |
+
torch.ones((num_video_frames, num_video_frames), dtype=torch.bool, device=device)
|
| 574 |
+
)
|
| 575 |
+
return frame_causal.repeat_interleave(video_tokens_per_frame, dim=0).repeat_interleave(
|
| 576 |
+
video_tokens_per_frame, dim=1
|
| 577 |
+
)
|
| 578 |
+
|
| 579 |
+
if self.video_attention_mask_mode == "first_frame_causal":
|
| 580 |
+
video_mask = torch.ones((video_seq_len, video_seq_len), dtype=torch.bool, device=device)
|
| 581 |
+
first_frame_tokens = min(video_tokens_per_frame, video_seq_len)
|
| 582 |
+
video_mask[:first_frame_tokens, first_frame_tokens:] = False
|
| 583 |
+
return video_mask
|
| 584 |
+
|
| 585 |
+
raise ValueError(f"Unsupported video attention mask mode: {self.video_attention_mask_mode}")
|
| 586 |
+
|
| 587 |
+
def pre_dit(
|
| 588 |
+
self,
|
| 589 |
+
x: torch.Tensor,
|
| 590 |
+
timestep: torch.Tensor,
|
| 591 |
+
context: torch.Tensor,
|
| 592 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 593 |
+
action: Optional[torch.Tensor] = None,
|
| 594 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 595 |
+
control_camera_latents_input: Optional[torch.Tensor] = None,
|
| 596 |
+
) -> Dict[str, Any]:
|
| 597 |
+
x, timestep, context_mask = self._validate_forward_inputs(
|
| 598 |
+
x=x,
|
| 599 |
+
timestep=timestep,
|
| 600 |
+
context=context,
|
| 601 |
+
context_mask=context_mask,
|
| 602 |
+
action=action,
|
| 603 |
+
)
|
| 604 |
+
|
| 605 |
+
batch_size = x.shape[0]
|
| 606 |
+
patch_h = int(self.patch_size[1])
|
| 607 |
+
patch_w = int(self.patch_size[2])
|
| 608 |
+
if x.shape[3] % patch_h != 0 or x.shape[4] % patch_w != 0:
|
| 609 |
+
raise ValueError(
|
| 610 |
+
"Latent spatial shape must be divisible by DiT patch size, "
|
| 611 |
+
f"got HxW=({x.shape[3]}, {x.shape[4]}), patch=({patch_h}, {patch_w})"
|
| 612 |
+
)
|
| 613 |
+
tokens_per_frame = (x.shape[3] // patch_h) * (x.shape[4] // patch_w)
|
| 614 |
+
|
| 615 |
+
if self.seperated_timestep and fuse_vae_embedding_in_latents:
|
| 616 |
+
if not hasattr(self, "patch_size") or len(self.patch_size) < 3:
|
| 617 |
+
raise ValueError(f"Invalid dit.patch_size: {getattr(self, 'patch_size', None)}")
|
| 618 |
+
|
| 619 |
+
token_timesteps = torch.ones(
|
| 620 |
+
(batch_size, x.shape[2], tokens_per_frame),
|
| 621 |
+
dtype=timestep.dtype,
|
| 622 |
+
device=timestep.device,
|
| 623 |
+
) * timestep.view(batch_size, 1, 1)
|
| 624 |
+
token_timesteps[:, 0, :] = 0
|
| 625 |
+
token_timesteps = token_timesteps.reshape(batch_size, -1)
|
| 626 |
+
token_t_emb = sinusoidal_embedding_1d(self.freq_dim, token_timesteps.reshape(-1))
|
| 627 |
+
t = self.time_embedding(token_t_emb).reshape(batch_size, -1, self.hidden_dim)
|
| 628 |
+
t_mod = self.time_projection(t).unflatten(2, (6, self.hidden_dim))
|
| 629 |
+
else:
|
| 630 |
+
raise NotImplementedError(
|
| 631 |
+
"Only support seperated_timestep with fuse_vae_embedding_in_latents for now."
|
| 632 |
+
)
|
| 633 |
+
t = self.time_embedding(sinusoidal_embedding_1d(self.freq_dim, timestep))
|
| 634 |
+
t_mod = self.time_projection(t).unflatten(1, (6, self.hidden_dim))
|
| 635 |
+
x = self.patchify(x, control_camera_latents_input=control_camera_latents_input)
|
| 636 |
+
f, h, w = x.shape[2:]
|
| 637 |
+
|
| 638 |
+
context = self.text_embedding(context) # (B, L, dim)
|
| 639 |
+
context_len = context.shape[1]
|
| 640 |
+
if self.action_conditioned and action is not None:
|
| 641 |
+
action_len = action.shape[1]
|
| 642 |
+
action_emb = self.action_embedding(action) # (B, action_len, dim)
|
| 643 |
+
action_pos_embed = sinusoidal_embedding_1d(
|
| 644 |
+
self.hidden_dim, torch.arange(action_len, device=action_emb.device)
|
| 645 |
+
) # (action_len, dim)
|
| 646 |
+
action_emb = action_emb + action_pos_embed.unsqueeze(0) # (B, action_len, dim)
|
| 647 |
+
context = torch.cat([context, action_emb], dim=1) # (B, context_len + action_len, dim)
|
| 648 |
+
|
| 649 |
+
# new mask
|
| 650 |
+
num_temporal_groups = f - 1 # first latent frame do not attend to actions
|
| 651 |
+
if num_temporal_groups <= 0:
|
| 652 |
+
raise ValueError(
|
| 653 |
+
"Action-conditioned context mask requires at least 2 latent frames when `action` is provided."
|
| 654 |
+
)
|
| 655 |
+
assert (
|
| 656 |
+
action_emb.shape[1] % num_temporal_groups == 0
|
| 657 |
+
), f"Action embedding length {action_emb.shape[1]} must be divisible by number of temporal groups {num_temporal_groups}"
|
| 658 |
+
# Each latent frame (from the 2nd one) attends to the corresponding group of action tokens
|
| 659 |
+
action_group_mask = create_group_causal_attn_mask(
|
| 660 |
+
num_temporal_groups=num_temporal_groups,
|
| 661 |
+
num_query_per_group=tokens_per_frame,
|
| 662 |
+
num_key_per_group=action_len // num_temporal_groups,
|
| 663 |
+
mode=self.action_group_causal_mask_mode,
|
| 664 |
+
).to(
|
| 665 |
+
context.device
|
| 666 |
+
) # ((f-1)*tokens_per_frame, action_len)
|
| 667 |
+
|
| 668 |
+
seq_len = f * h * w # query length
|
| 669 |
+
final_context_mask = torch.zeros(
|
| 670 |
+
(batch_size, seq_len, context.shape[1]), dtype=torch.bool, device=context.device
|
| 671 |
+
) # (B, seq_len, L + action_len)
|
| 672 |
+
# all latent frames attend to text tokens
|
| 673 |
+
final_context_mask[:, :, :context_len] = context_mask.unsqueeze(1).expand(
|
| 674 |
+
-1, seq_len, -1
|
| 675 |
+
) # (B, seq_len, L)
|
| 676 |
+
# latent frames from the 2nd one attend to action tokens
|
| 677 |
+
final_context_mask[:, tokens_per_frame:, context_len:] = action_group_mask.unsqueeze(
|
| 678 |
+
0
|
| 679 |
+
).expand(
|
| 680 |
+
batch_size, -1, -1
|
| 681 |
+
) # (B, seq_len, action_len)
|
| 682 |
+
context_mask = final_context_mask
|
| 683 |
+
elif self.action_conditioned and action is None:
|
| 684 |
+
if f != 1:
|
| 685 |
+
raise ValueError(
|
| 686 |
+
"Action-conditioned model requires `action` unless running single-frame text-only mode with num_latent_frames=1."
|
| 687 |
+
)
|
| 688 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 689 |
+
else:
|
| 690 |
+
context_mask = context_mask.unsqueeze(1).expand(-1, f * h * w, -1) # (B, seq_len, L)
|
| 691 |
+
|
| 692 |
+
x_tokens = rearrange(x, "b c f h w -> b (f h w) c").contiguous()
|
| 693 |
+
|
| 694 |
+
freqs = (
|
| 695 |
+
torch.cat(
|
| 696 |
+
[
|
| 697 |
+
self.freqs[0][:f].view(f, 1, 1, -1).expand(f, h, w, -1),
|
| 698 |
+
self.freqs[1][:h].view(1, h, 1, -1).expand(f, h, w, -1),
|
| 699 |
+
self.freqs[2][:w].view(1, 1, w, -1).expand(f, h, w, -1),
|
| 700 |
+
],
|
| 701 |
+
dim=-1,
|
| 702 |
+
)
|
| 703 |
+
.reshape(f * h * w, 1, -1)
|
| 704 |
+
.to(x_tokens.device)
|
| 705 |
+
)
|
| 706 |
+
|
| 707 |
+
return {
|
| 708 |
+
"tokens": x_tokens,
|
| 709 |
+
"freqs": freqs,
|
| 710 |
+
"t": t,
|
| 711 |
+
"t_mod": t_mod,
|
| 712 |
+
"context": context,
|
| 713 |
+
"context_mask": context_mask,
|
| 714 |
+
"meta": {
|
| 715 |
+
"grid_size": (f, h, w),
|
| 716 |
+
"tokens_per_frame": tokens_per_frame,
|
| 717 |
+
"batch_size": batch_size,
|
| 718 |
+
},
|
| 719 |
+
}
|
| 720 |
+
|
| 721 |
+
def post_dit(self, x_tokens: torch.Tensor, pre_state: Dict[str, Any]) -> torch.Tensor:
|
| 722 |
+
f, h, w = pre_state["meta"]["grid_size"]
|
| 723 |
+
x = self.head(x_tokens, pre_state["t"])
|
| 724 |
+
x = self.unpatchify(x, (f, h, w))
|
| 725 |
+
return x
|
| 726 |
+
|
| 727 |
+
def forward(
|
| 728 |
+
self,
|
| 729 |
+
x: torch.Tensor,
|
| 730 |
+
timestep: torch.Tensor,
|
| 731 |
+
context: torch.Tensor,
|
| 732 |
+
context_mask: Optional[torch.Tensor] = None,
|
| 733 |
+
action: Optional[torch.Tensor] = None,
|
| 734 |
+
fuse_vae_embedding_in_latents: bool = False,
|
| 735 |
+
):
|
| 736 |
+
pre_state = self.pre_dit(
|
| 737 |
+
x=x,
|
| 738 |
+
timestep=timestep,
|
| 739 |
+
context=context,
|
| 740 |
+
context_mask=context_mask,
|
| 741 |
+
action=action,
|
| 742 |
+
fuse_vae_embedding_in_latents=fuse_vae_embedding_in_latents,
|
| 743 |
+
)
|
| 744 |
+
x_tokens = pre_state["tokens"]
|
| 745 |
+
context_emb = pre_state["context"]
|
| 746 |
+
t_mod = pre_state["t_mod"]
|
| 747 |
+
freqs = pre_state["freqs"]
|
| 748 |
+
context_attn_mask = pre_state["context_mask"]
|
| 749 |
+
self_attn_mask = (
|
| 750 |
+
self.build_video_to_video_mask(
|
| 751 |
+
video_seq_len=x_tokens.shape[1],
|
| 752 |
+
video_tokens_per_frame=int(pre_state["meta"]["tokens_per_frame"]),
|
| 753 |
+
device=x_tokens.device,
|
| 754 |
+
)
|
| 755 |
+
if self.video_attention_mask_mode != "bidirectional"
|
| 756 |
+
else None
|
| 757 |
+
) # special rule for faster speed
|
| 758 |
+
|
| 759 |
+
for block in self.blocks:
|
| 760 |
+
if self.use_gradient_checkpointing:
|
| 761 |
+
x_tokens = gradient_checkpoint_forward(
|
| 762 |
+
block,
|
| 763 |
+
self.use_gradient_checkpointing,
|
| 764 |
+
x_tokens,
|
| 765 |
+
context_emb,
|
| 766 |
+
t_mod,
|
| 767 |
+
freqs,
|
| 768 |
+
context_mask=context_attn_mask,
|
| 769 |
+
self_attn_mask=self_attn_mask,
|
| 770 |
+
)
|
| 771 |
+
else:
|
| 772 |
+
x_tokens = block(
|
| 773 |
+
x_tokens,
|
| 774 |
+
context_emb,
|
| 775 |
+
t_mod,
|
| 776 |
+
freqs,
|
| 777 |
+
context_mask=context_attn_mask,
|
| 778 |
+
self_attn_mask=self_attn_mask,
|
| 779 |
+
)
|
| 780 |
+
|
| 781 |
+
return self.post_dit(x_tokens, pre_state)
|
tools/model_code/recorded/main/__init__.py
ADDED
|
File without changes
|