Haiyang Liu commited on
Commit
272e50d
·
verified ·
1 Parent(s): 44ad3ac

Add dated historical interpolation weights and matching runtime

Browse files
Files changed (46) hide show
  1. 2409_variants/v7_dup_14_continue_2_step655000/README.md +34 -0
  2. 2409_variants/v7_dup_14_continue_2_step655000/asset_manifest.json +155 -0
  3. 2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin +3 -0
  4. 2411_variants/v7_dup_14_s2_12frames_512_step30000/README.md +34 -0
  5. 2411_variants/v7_dup_14_s2_12frames_512_step30000/asset_manifest.json +155 -0
  6. 2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin +3 -0
  7. 2411_variants/v7_dup_14_s2_8frames_512_step9000/README.md +34 -0
  8. 2411_variants/v7_dup_14_s2_8frames_512_step9000/asset_manifest.json +155 -0
  9. 2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin +3 -0
  10. 2610_runtime_asset_manifest.json +200 -0
  11. 2610_variant_asset_manifest.json +395 -0
  12. 2610_variant_runtime/LICENSE +201 -0
  13. 2610_variant_runtime/NOTICE +30 -0
  14. 2610_variant_runtime/README.md +115 -0
  15. 2610_variant_runtime/asset_manifest.json +54 -0
  16. 2610_variant_runtime/diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml +55 -0
  17. 2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml +55 -0
  18. 2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml +55 -0
  19. 2610_variant_runtime/diffusion/inference.py +468 -0
  20. 2610_variant_runtime/diffusion/models/attention.py +526 -0
  21. 2610_variant_runtime/diffusion/models/conv_in.py +26 -0
  22. 2610_variant_runtime/diffusion/models/model_vfi.py +987 -0
  23. 2610_variant_runtime/diffusion/models/motion_module.py +390 -0
  24. 2610_variant_runtime/diffusion/models/mutual_self_attention.py +365 -0
  25. 2610_variant_runtime/diffusion/models/pose_guider.py +57 -0
  26. 2610_variant_runtime/diffusion/models/resnet.py +252 -0
  27. 2610_variant_runtime/diffusion/models/transformer_2d.py +396 -0
  28. 2610_variant_runtime/diffusion/models/transformer_3d.py +170 -0
  29. 2610_variant_runtime/diffusion/models/unet_2d_blocks.py +1076 -0
  30. 2610_variant_runtime/diffusion/models/unet_2d_condition.py +1313 -0
  31. 2610_variant_runtime/diffusion/models/unet_3d.py +668 -0
  32. 2610_variant_runtime/diffusion/models/unet_3d_blocks.py +863 -0
  33. 2610_variant_runtime/diffusion/pipelines/__init__.py +1 -0
  34. 2610_variant_runtime/diffusion/pipelines/pipeline_vfi2video_share_vae.py +509 -0
  35. 2610_variant_runtime/diffusion/utils/__init__.py +1 -0
  36. 2610_variant_runtime/diffusion/utils/util.py +168 -0
  37. 2610_variant_runtime/diffusion/utils/video_utils.py +89 -0
  38. 2610_variant_runtime/licenses/AnimateDiff.txt +201 -0
  39. 2610_variant_runtime/licenses/DWPose.txt +219 -0
  40. 2610_variant_runtime/licenses/OpenRAIL-M.txt +82 -0
  41. 2610_variant_runtime/licenses/PixArt-alpha.txt +201 -0
  42. 2610_variant_runtime/licenses/diffusers.txt +201 -0
  43. 2610_variant_runtime/licenses/magic-animate.txt +28 -0
  44. 2610_variant_runtime/requirements.lock.txt +133 -0
  45. 2610_variant_runtime/scripts/download_assets.py +50 -0
  46. README.md +13 -0
2409_variants/v7_dup_14_continue_2_step655000/README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2409 historical interpolation variant — step 655000
2
+
3
+ Historical interpolation checkpoint. Its relationship to any final TANGO or ACInterp paper model is unconfirmed.
4
+
5
+ The date prefix records source material from 2024-09; it does not reconstruct the training start date. The original run is `v7_dup_14_continue_2`, step `655000`. This historical variant is separate from the existing `finetune_weighted/checkpoint-8000` release.
6
+
7
+ ## Verification status
8
+
9
+ The downloaded source file passed a full SHA256 check. A strict CPU comparison against the meta-constructed model passed for all 1,974 keys with no missing or unexpected keys and no shape mismatch. The seed-guider convolution has shape `[320, 5, 3, 3]`.
10
+
11
+ **GPU forward execution, rendered-video evaluation and fresh-Hub-download verification are pending.** The CPU check did not run a forward pass.
12
+
13
+ | File | Bytes | SHA256 |
14
+ | --- | ---: | --- |
15
+ | `pytorch_model.bin` | 8699157476 | `beae0aadd1fc049da2f776ecef51a356727eccd18fa5cb5481738ae3adfbabe1` |
16
+
17
+ See the [asset manifest](asset_manifest.json) and [standalone runtime instructions](../../2610_variant_runtime/README.md). The runtime is frozen and identified by its file hashes; its upstream base commit alone does not contain the new variant support.
18
+
19
+ ## Configured inference command
20
+
21
+ From `2610_variant_runtime/`, after installing the pinned environment, downloading the base assets and creating your aligned input JSON:
22
+
23
+ ```sh
24
+ WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml --checkpoint ../2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin --json inputs/input.json --output-dir outputs
25
+ ```
26
+
27
+ Configuration SHA256: `100c01244d99bc9bd263a9695e6cc95685b0acdebc17681741d709e3116ba5b4`.
28
+ Seed: 2024; layout: 3 + 8 + 3 frames; image size: 512 with black padding; DDIM steps: 20; guidance: 3.5.
29
+
30
+ The standard SD VAE is used. No custom temporal decoder is required by this packaged profile. This is a full custom PyTorch state dictionary, not a standalone Diffusers pipeline. No quality, best-checkpoint or paper-benchmark equivalence claim is made.
31
+
32
+ ## Retention and license
33
+
34
+ Optimizer, scheduler, mixed-precision scaler and random-number-generator state are excluded, so exact training continuation is not supported. Weights retain the repository's CreativeML OpenRAIL-M terms; upstream components retain their respective licenses. The runtime source's Apache-2.0 and third-party source notices are separate from model licensing. See the repository [model license](../../LICENSE) and runtime [notices](../../2610_variant_runtime/NOTICE).
2409_variants/v7_dup_14_continue_2_step655000/asset_manifest.json ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "status": "source_sha256_and_cpu_key_shape_verified_gpu_render_pending",
4
+ "variant": {
5
+ "variant_id": "v7_dup_14_continue_2_step655000",
6
+ "relative_directory": "2409_variants/v7_dup_14_continue_2_step655000",
7
+ "source_material_month": "2024-09",
8
+ "date_basis": "Earliest confirmed source-material month; not an inferred training-start date.",
9
+ "original_run": "v7_dup_14_continue_2",
10
+ "checkpoint_step": 655000,
11
+ "scope": "Historical interpolation checkpoint. Its relationship to any final TANGO or ACInterp paper model is unconfirmed.",
12
+ "assets": [
13
+ {
14
+ "path": "2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin",
15
+ "filename": "pytorch_model.bin",
16
+ "bytes": 8699157476,
17
+ "sha256": "beae0aadd1fc049da2f776ecef51a356727eccd18fa5cb5481738ae3adfbabe1",
18
+ "format": "PyTorch full model state dictionary",
19
+ "sha256_evidence": "Full SHA256 of the downloaded source file matches the source-storage SHA256; independent fresh-Hub-download verification is pending."
20
+ }
21
+ ],
22
+ "architecture": {
23
+ "code_family": "Custom pose-guided diffusion interpolation",
24
+ "seed_guider_channels_expected_from_source": 5,
25
+ "seed_guider_tensor_shape_verified": [
26
+ 320,
27
+ 5,
28
+ 3,
29
+ 3
30
+ ],
31
+ "context_frames_per_end": 3,
32
+ "generated_frames": 8,
33
+ "total_frames": 14,
34
+ "image_size": 512,
35
+ "verification_status": "CPU strict key/shape verified; GPU forward pending",
36
+ "seed_mask_channels": "4 latent + 1 known-frame mask"
37
+ },
38
+ "inference": {
39
+ "profile": "standard_pose",
40
+ "vae": "stabilityai/sd-vae-ft-mse",
41
+ "custom_temporal_decoder_required": false,
42
+ "code_repo": "https://github.com/H-Liu1997/Video-Motion-Graphs",
43
+ "code_revision": null,
44
+ "config_path": "2610_variant_runtime/diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml",
45
+ "config_sha256": "100c01244d99bc9bd263a9695e6cc95685b0acdebc17681741d709e3116ba5b4",
46
+ "environment_lock_path": "2610_variant_runtime/requirements.lock.txt",
47
+ "environment_lock_sha256": "dfdd012e92ece6da107024040eded8ef55e75b9ab51ba0a8e95b19f0f7621f20",
48
+ "commands": [
49
+ "WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml --checkpoint ../2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin --json inputs/input.json --output-dir outputs"
50
+ ],
51
+ "status": "frozen command; CPU key/shape passed; GPU execution pending",
52
+ "code_source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
53
+ "code_source_contains_frozen_uncommitted_changes": true,
54
+ "runtime_root": "2610_variant_runtime",
55
+ "runtime_manifest": "2610_runtime_asset_manifest.json",
56
+ "runtime_bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
57
+ "command_working_directory": "2610_variant_runtime",
58
+ "seed": 2024,
59
+ "guidance_scale": 3.5,
60
+ "denoising_steps": 20
61
+ },
62
+ "validation": {
63
+ "source_file_sha256": "verified",
64
+ "source_sha256": "beae0aadd1fc049da2f776ecef51a356727eccd18fa5cb5481738ae3adfbabe1",
65
+ "source_bytes_verified": true,
66
+ "hub_commit": null,
67
+ "hub_lfs_sha256": "pending",
68
+ "fresh_download_sha256": "pending",
69
+ "cpu_key_shape_check": {
70
+ "status": "passed",
71
+ "method": "CPU mmap state dict against exact meta-constructed model; shape/key check without tensor copies or forward",
72
+ "key_count": 1974,
73
+ "missing_keys": [],
74
+ "unexpected_keys": [],
75
+ "seed_guider_weight_shape": [
76
+ 320,
77
+ 5,
78
+ 3,
79
+ 3
80
+ ],
81
+ "forward_executed": false
82
+ },
83
+ "strict_gpu_load": "pending",
84
+ "real_input_render": "pending",
85
+ "input_assets": [],
86
+ "output_video": null,
87
+ "hardware": null,
88
+ "environment": null,
89
+ "seed": 2024,
90
+ "metrics": null,
91
+ "receipt": null
92
+ },
93
+ "excluded_training_state": [
94
+ "optimizer",
95
+ "scheduler",
96
+ "mixed-precision scaler",
97
+ "random-number generator state"
98
+ ],
99
+ "training_resume_supported": false,
100
+ "license": "creativeml-openrail-m",
101
+ "license_note": "Retain the applicable Stable Diffusion / CreativeML OpenRAIL-M model terms and upstream component terms. Project source-code licensing is separate."
102
+ },
103
+ "base_components": [
104
+ {
105
+ "path": "weights/image_encoder/pytorch_model.bin",
106
+ "group": "base",
107
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/pytorch_model.bin",
108
+ "bytes": 1215993967,
109
+ "sha256": "89d2aa29b5fdf64f3ad4f45fb4227ea98bc45156bbae673b85be1af7783dbabb"
110
+ },
111
+ {
112
+ "path": "weights/image_encoder/config.json",
113
+ "group": "base",
114
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/config.json",
115
+ "bytes": 703,
116
+ "sha256": "ba41139cc9dad159163a53e2aa847356b627f53fef988ad461659bd2d587d886"
117
+ },
118
+ {
119
+ "path": "weights/stable-diffusion-v1-5/unet/diffusion_pytorch_model.bin",
120
+ "group": "base",
121
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/diffusion_pytorch_model.bin",
122
+ "bytes": 3438354725,
123
+ "sha256": "c7da0e21ba7ea50637bee26e81c220844defdf01aafca02b2c42ecdadb813de4"
124
+ },
125
+ {
126
+ "path": "weights/stable-diffusion-v1-5/unet/config.json",
127
+ "group": "base",
128
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/config.json",
129
+ "bytes": 743,
130
+ "sha256": "78f474de6bab3d893868f37be97b636ae65c0df3073ed3256ca458ff599b5f96"
131
+ },
132
+ {
133
+ "path": "weights/sd-vae-ft-mse/diffusion_pytorch_model.bin",
134
+ "group": "base",
135
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/diffusion_pytorch_model.bin",
136
+ "bytes": 334707217,
137
+ "sha256": "1b4889b6b1d4ce7ae320a02dedaeff1780ad77d415ea0d744b476155c6377ddc"
138
+ },
139
+ {
140
+ "path": "weights/sd-vae-ft-mse/config.json",
141
+ "group": "base",
142
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/config.json",
143
+ "bytes": 547,
144
+ "sha256": "92d3dfb746fca211a2c9e019e285f8597412211728dce3c5bcf4eda0f2d62e7e"
145
+ },
146
+ {
147
+ "path": "weights/animatediff/mm_sd_v15_v2.ckpt",
148
+ "group": "base",
149
+ "url": "https://huggingface.co/guoyww/animatediff/resolve/fdfe36afa161e51b3e9c24022b0e368d59e7345e/mm_sd_v15_v2.ckpt",
150
+ "bytes": 1817888431,
151
+ "sha256": "69ed0f5fef82b110aca51bcab73b21104242bc65d6ab4b8b2a2a94d31cad1bf0"
152
+ }
153
+ ],
154
+ "base_components_note": "Seven pinned standard-VAE base components have been downloaded and SHA256 verified. GPU execution with the new variants is pending."
155
+ }
2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:beae0aadd1fc049da2f776ecef51a356727eccd18fa5cb5481738ae3adfbabe1
3
+ size 8699157476
2411_variants/v7_dup_14_s2_12frames_512_step30000/README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2411 historical 12-frame 512 variant — step 30000
2
+
3
+ Historical checkpoint referenced by the 12-frame 512 inference configuration; no best-checkpoint or paper-final claim.
4
+
5
+ The date prefix records source material from 2024-11; it does not reconstruct the training start date. The original run is `v7_dup_14_s2_12frames_512`, step `30000`. This historical variant is separate from the existing `finetune_weighted/checkpoint-8000` release.
6
+
7
+ ## Verification status
8
+
9
+ The downloaded source file passed a full SHA256 check. A strict CPU comparison against the meta-constructed model passed for all 1,974 keys with no missing or unexpected keys and no shape mismatch. The seed-guider convolution has shape `[320, 5, 3, 3]`.
10
+
11
+ **GPU forward execution, rendered-video evaluation and fresh-Hub-download verification are pending.** The CPU check did not run a forward pass.
12
+
13
+ | File | Bytes | SHA256 |
14
+ | --- | ---: | --- |
15
+ | `pytorch_model.bin` | 8699157476 | `98bc64d7c931a7e414e9e9b45709420477d8625055043e945ad01d121f2302fb` |
16
+
17
+ See the [asset manifest](asset_manifest.json) and [standalone runtime instructions](../../2610_variant_runtime/README.md). The runtime is frozen and identified by its file hashes; its upstream base commit alone does not contain the new variant support.
18
+
19
+ ## Configured inference command
20
+
21
+ From `2610_variant_runtime/`, after installing the pinned environment, downloading the base assets and creating your aligned input JSON:
22
+
23
+ ```sh
24
+ WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin --json inputs/input.json --output-dir outputs
25
+ ```
26
+
27
+ Configuration SHA256: `7258d8124521c81d2b2724115f0e55d2ece513f8715a0f8a3d378c6537096ef1`.
28
+ Seed: 2024; layout: 1 + 12 + 1 frames; image size: 512 with black padding; DDIM steps: 20; guidance: 3.5.
29
+
30
+ The standard SD VAE is used. No custom temporal decoder is required by this packaged profile. This is a full custom PyTorch state dictionary, not a standalone Diffusers pipeline. No quality, best-checkpoint or paper-benchmark equivalence claim is made.
31
+
32
+ ## Retention and license
33
+
34
+ Optimizer, scheduler, mixed-precision scaler and random-number-generator state are excluded, so exact training continuation is not supported. Weights retain the repository's CreativeML OpenRAIL-M terms; upstream components retain their respective licenses. The runtime source's Apache-2.0 and third-party source notices are separate from model licensing. See the repository [model license](../../LICENSE) and runtime [notices](../../2610_variant_runtime/NOTICE).
2411_variants/v7_dup_14_s2_12frames_512_step30000/asset_manifest.json ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "status": "source_sha256_and_cpu_key_shape_verified_gpu_render_pending",
4
+ "variant": {
5
+ "variant_id": "v7_dup_14_s2_12frames_512_step30000",
6
+ "relative_directory": "2411_variants/v7_dup_14_s2_12frames_512_step30000",
7
+ "source_material_month": "2024-11",
8
+ "date_basis": "Earliest confirmed source-material month; not an inferred training-start date.",
9
+ "original_run": "v7_dup_14_s2_12frames_512",
10
+ "checkpoint_step": 30000,
11
+ "scope": "Historical checkpoint referenced by the 12-frame 512 inference configuration; no best-checkpoint or paper-final claim.",
12
+ "assets": [
13
+ {
14
+ "path": "2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin",
15
+ "filename": "pytorch_model.bin",
16
+ "bytes": 8699157476,
17
+ "sha256": "98bc64d7c931a7e414e9e9b45709420477d8625055043e945ad01d121f2302fb",
18
+ "format": "PyTorch full model state dictionary",
19
+ "sha256_evidence": "Full SHA256 of the downloaded source file matches the source-storage SHA256; independent fresh-Hub-download verification is pending."
20
+ }
21
+ ],
22
+ "architecture": {
23
+ "code_family": "Custom pose-guided diffusion interpolation",
24
+ "seed_guider_channels_expected_from_source": 5,
25
+ "seed_guider_tensor_shape_verified": [
26
+ 320,
27
+ 5,
28
+ 3,
29
+ 3
30
+ ],
31
+ "context_frames_per_end": 1,
32
+ "generated_frames": 12,
33
+ "total_frames": 14,
34
+ "image_size": 512,
35
+ "verification_status": "CPU strict key/shape verified; GPU forward pending",
36
+ "seed_mask_channels": "4 latent + 1 known-frame mask"
37
+ },
38
+ "inference": {
39
+ "profile": "standard_pose",
40
+ "vae": "stabilityai/sd-vae-ft-mse",
41
+ "custom_temporal_decoder_required": false,
42
+ "code_repo": "https://github.com/H-Liu1997/Video-Motion-Graphs",
43
+ "code_revision": null,
44
+ "config_path": "2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml",
45
+ "config_sha256": "7258d8124521c81d2b2724115f0e55d2ece513f8715a0f8a3d378c6537096ef1",
46
+ "environment_lock_path": "2610_variant_runtime/requirements.lock.txt",
47
+ "environment_lock_sha256": "dfdd012e92ece6da107024040eded8ef55e75b9ab51ba0a8e95b19f0f7621f20",
48
+ "commands": [
49
+ "WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin --json inputs/input.json --output-dir outputs"
50
+ ],
51
+ "status": "frozen command; CPU key/shape passed; GPU execution pending",
52
+ "code_source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
53
+ "code_source_contains_frozen_uncommitted_changes": true,
54
+ "runtime_root": "2610_variant_runtime",
55
+ "runtime_manifest": "2610_runtime_asset_manifest.json",
56
+ "runtime_bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
57
+ "command_working_directory": "2610_variant_runtime",
58
+ "seed": 2024,
59
+ "guidance_scale": 3.5,
60
+ "denoising_steps": 20
61
+ },
62
+ "validation": {
63
+ "source_file_sha256": "verified",
64
+ "source_sha256": "98bc64d7c931a7e414e9e9b45709420477d8625055043e945ad01d121f2302fb",
65
+ "source_bytes_verified": true,
66
+ "hub_commit": null,
67
+ "hub_lfs_sha256": "pending",
68
+ "fresh_download_sha256": "pending",
69
+ "cpu_key_shape_check": {
70
+ "status": "passed",
71
+ "method": "CPU mmap state dict against exact meta-constructed model; shape/key check without tensor copies or forward",
72
+ "key_count": 1974,
73
+ "missing_keys": [],
74
+ "unexpected_keys": [],
75
+ "seed_guider_weight_shape": [
76
+ 320,
77
+ 5,
78
+ 3,
79
+ 3
80
+ ],
81
+ "forward_executed": false
82
+ },
83
+ "strict_gpu_load": "pending",
84
+ "real_input_render": "pending",
85
+ "input_assets": [],
86
+ "output_video": null,
87
+ "hardware": null,
88
+ "environment": null,
89
+ "seed": 2024,
90
+ "metrics": null,
91
+ "receipt": null
92
+ },
93
+ "excluded_training_state": [
94
+ "optimizer",
95
+ "scheduler",
96
+ "mixed-precision scaler",
97
+ "random-number generator state"
98
+ ],
99
+ "training_resume_supported": false,
100
+ "license": "creativeml-openrail-m",
101
+ "license_note": "Retain the applicable Stable Diffusion / CreativeML OpenRAIL-M model terms and upstream component terms. Project source-code licensing is separate."
102
+ },
103
+ "base_components": [
104
+ {
105
+ "path": "weights/image_encoder/pytorch_model.bin",
106
+ "group": "base",
107
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/pytorch_model.bin",
108
+ "bytes": 1215993967,
109
+ "sha256": "89d2aa29b5fdf64f3ad4f45fb4227ea98bc45156bbae673b85be1af7783dbabb"
110
+ },
111
+ {
112
+ "path": "weights/image_encoder/config.json",
113
+ "group": "base",
114
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/config.json",
115
+ "bytes": 703,
116
+ "sha256": "ba41139cc9dad159163a53e2aa847356b627f53fef988ad461659bd2d587d886"
117
+ },
118
+ {
119
+ "path": "weights/stable-diffusion-v1-5/unet/diffusion_pytorch_model.bin",
120
+ "group": "base",
121
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/diffusion_pytorch_model.bin",
122
+ "bytes": 3438354725,
123
+ "sha256": "c7da0e21ba7ea50637bee26e81c220844defdf01aafca02b2c42ecdadb813de4"
124
+ },
125
+ {
126
+ "path": "weights/stable-diffusion-v1-5/unet/config.json",
127
+ "group": "base",
128
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/config.json",
129
+ "bytes": 743,
130
+ "sha256": "78f474de6bab3d893868f37be97b636ae65c0df3073ed3256ca458ff599b5f96"
131
+ },
132
+ {
133
+ "path": "weights/sd-vae-ft-mse/diffusion_pytorch_model.bin",
134
+ "group": "base",
135
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/diffusion_pytorch_model.bin",
136
+ "bytes": 334707217,
137
+ "sha256": "1b4889b6b1d4ce7ae320a02dedaeff1780ad77d415ea0d744b476155c6377ddc"
138
+ },
139
+ {
140
+ "path": "weights/sd-vae-ft-mse/config.json",
141
+ "group": "base",
142
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/config.json",
143
+ "bytes": 547,
144
+ "sha256": "92d3dfb746fca211a2c9e019e285f8597412211728dce3c5bcf4eda0f2d62e7e"
145
+ },
146
+ {
147
+ "path": "weights/animatediff/mm_sd_v15_v2.ckpt",
148
+ "group": "base",
149
+ "url": "https://huggingface.co/guoyww/animatediff/resolve/fdfe36afa161e51b3e9c24022b0e368d59e7345e/mm_sd_v15_v2.ckpt",
150
+ "bytes": 1817888431,
151
+ "sha256": "69ed0f5fef82b110aca51bcab73b21104242bc65d6ab4b8b2a2a94d31cad1bf0"
152
+ }
153
+ ],
154
+ "base_components_note": "Seven pinned standard-VAE base components have been downloaded and SHA256 verified. GPU execution with the new variants is pending."
155
+ }
2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:98bc64d7c931a7e414e9e9b45709420477d8625055043e945ad01d121f2302fb
3
+ size 8699157476
2411_variants/v7_dup_14_s2_8frames_512_step9000/README.md ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2411 historical 8-frame 512 variant — step 9000
2
+
3
+ Historical checkpoint referenced by the 8-frame 512 inference configuration; no best-checkpoint or paper-final claim.
4
+
5
+ The date prefix records source material from 2024-11; it does not reconstruct the training start date. The original run is `v7_dup_14_s2_8frames_512`, step `9000`. This historical variant is separate from the existing `finetune_weighted/checkpoint-8000` release.
6
+
7
+ ## Verification status
8
+
9
+ The downloaded source file passed a full SHA256 check. A strict CPU comparison against the meta-constructed model passed for all 1,974 keys with no missing or unexpected keys and no shape mismatch. The seed-guider convolution has shape `[320, 5, 3, 3]`.
10
+
11
+ **GPU forward execution, rendered-video evaluation and fresh-Hub-download verification are pending.** The CPU check did not run a forward pass.
12
+
13
+ | File | Bytes | SHA256 |
14
+ | --- | ---: | --- |
15
+ | `pytorch_model.bin` | 8699157476 | `6a1288711eaf2792f3581b3e175fb79bb8988e5b192a61178de322c587e810b8` |
16
+
17
+ See the [asset manifest](asset_manifest.json) and [standalone runtime instructions](../../2610_variant_runtime/README.md). The runtime is frozen and identified by its file hashes; its upstream base commit alone does not contain the new variant support.
18
+
19
+ ## Configured inference command
20
+
21
+ From `2610_variant_runtime/`, after installing the pinned environment, downloading the base assets and creating your aligned input JSON:
22
+
23
+ ```sh
24
+ WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin --json inputs/input.json --output-dir outputs
25
+ ```
26
+
27
+ Configuration SHA256: `37cf67ec1a2b9c8020927ca849fae7a8da7b63762d9c9010a59570b0619a7aa3`.
28
+ Seed: 2024; layout: 3 + 8 + 3 frames; image size: 512 with black padding; DDIM steps: 20; guidance: 1.0.
29
+
30
+ The standard SD VAE is used. No custom temporal decoder is required by this packaged profile. This is a full custom PyTorch state dictionary, not a standalone Diffusers pipeline. No quality, best-checkpoint or paper-benchmark equivalence claim is made.
31
+
32
+ ## Retention and license
33
+
34
+ Optimizer, scheduler, mixed-precision scaler and random-number-generator state are excluded, so exact training continuation is not supported. Weights retain the repository's CreativeML OpenRAIL-M terms; upstream components retain their respective licenses. The runtime source's Apache-2.0 and third-party source notices are separate from model licensing. See the repository [model license](../../LICENSE) and runtime [notices](../../2610_variant_runtime/NOTICE).
2411_variants/v7_dup_14_s2_8frames_512_step9000/asset_manifest.json ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "status": "source_sha256_and_cpu_key_shape_verified_gpu_render_pending",
4
+ "variant": {
5
+ "variant_id": "v7_dup_14_s2_8frames_512_step9000",
6
+ "relative_directory": "2411_variants/v7_dup_14_s2_8frames_512_step9000",
7
+ "source_material_month": "2024-11",
8
+ "date_basis": "Earliest confirmed source-material month; not an inferred training-start date.",
9
+ "original_run": "v7_dup_14_s2_8frames_512",
10
+ "checkpoint_step": 9000,
11
+ "scope": "Historical checkpoint referenced by the 8-frame 512 inference configuration; no best-checkpoint or paper-final claim.",
12
+ "assets": [
13
+ {
14
+ "path": "2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin",
15
+ "filename": "pytorch_model.bin",
16
+ "bytes": 8699157476,
17
+ "sha256": "6a1288711eaf2792f3581b3e175fb79bb8988e5b192a61178de322c587e810b8",
18
+ "format": "PyTorch full model state dictionary",
19
+ "sha256_evidence": "Full SHA256 of the downloaded source file matches the source-storage SHA256; independent fresh-Hub-download verification is pending."
20
+ }
21
+ ],
22
+ "architecture": {
23
+ "code_family": "Custom pose-guided diffusion interpolation",
24
+ "seed_guider_channels_expected_from_source": 5,
25
+ "seed_guider_tensor_shape_verified": [
26
+ 320,
27
+ 5,
28
+ 3,
29
+ 3
30
+ ],
31
+ "context_frames_per_end": 3,
32
+ "generated_frames": 8,
33
+ "total_frames": 14,
34
+ "image_size": 512,
35
+ "verification_status": "CPU strict key/shape verified; GPU forward pending",
36
+ "seed_mask_channels": "4 latent + 1 known-frame mask"
37
+ },
38
+ "inference": {
39
+ "profile": "standard_pose",
40
+ "vae": "stabilityai/sd-vae-ft-mse",
41
+ "custom_temporal_decoder_required": false,
42
+ "code_repo": "https://github.com/H-Liu1997/Video-Motion-Graphs",
43
+ "code_revision": null,
44
+ "config_path": "2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml",
45
+ "config_sha256": "37cf67ec1a2b9c8020927ca849fae7a8da7b63762d9c9010a59570b0619a7aa3",
46
+ "environment_lock_path": "2610_variant_runtime/requirements.lock.txt",
47
+ "environment_lock_sha256": "dfdd012e92ece6da107024040eded8ef55e75b9ab51ba0a8e95b19f0f7621f20",
48
+ "commands": [
49
+ "WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin --json inputs/input.json --output-dir outputs"
50
+ ],
51
+ "status": "frozen command; CPU key/shape passed; GPU execution pending",
52
+ "code_source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
53
+ "code_source_contains_frozen_uncommitted_changes": true,
54
+ "runtime_root": "2610_variant_runtime",
55
+ "runtime_manifest": "2610_runtime_asset_manifest.json",
56
+ "runtime_bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
57
+ "command_working_directory": "2610_variant_runtime",
58
+ "seed": 2024,
59
+ "guidance_scale": 1.0,
60
+ "denoising_steps": 20
61
+ },
62
+ "validation": {
63
+ "source_file_sha256": "verified",
64
+ "source_sha256": "6a1288711eaf2792f3581b3e175fb79bb8988e5b192a61178de322c587e810b8",
65
+ "source_bytes_verified": true,
66
+ "hub_commit": null,
67
+ "hub_lfs_sha256": "pending",
68
+ "fresh_download_sha256": "pending",
69
+ "cpu_key_shape_check": {
70
+ "status": "passed",
71
+ "method": "CPU mmap state dict against exact meta-constructed model; shape/key check without tensor copies or forward",
72
+ "key_count": 1974,
73
+ "missing_keys": [],
74
+ "unexpected_keys": [],
75
+ "seed_guider_weight_shape": [
76
+ 320,
77
+ 5,
78
+ 3,
79
+ 3
80
+ ],
81
+ "forward_executed": false
82
+ },
83
+ "strict_gpu_load": "pending",
84
+ "real_input_render": "pending",
85
+ "input_assets": [],
86
+ "output_video": null,
87
+ "hardware": null,
88
+ "environment": null,
89
+ "seed": 2024,
90
+ "metrics": null,
91
+ "receipt": null
92
+ },
93
+ "excluded_training_state": [
94
+ "optimizer",
95
+ "scheduler",
96
+ "mixed-precision scaler",
97
+ "random-number generator state"
98
+ ],
99
+ "training_resume_supported": false,
100
+ "license": "creativeml-openrail-m",
101
+ "license_note": "Retain the applicable Stable Diffusion / CreativeML OpenRAIL-M model terms and upstream component terms. Project source-code licensing is separate."
102
+ },
103
+ "base_components": [
104
+ {
105
+ "path": "weights/image_encoder/pytorch_model.bin",
106
+ "group": "base",
107
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/pytorch_model.bin",
108
+ "bytes": 1215993967,
109
+ "sha256": "89d2aa29b5fdf64f3ad4f45fb4227ea98bc45156bbae673b85be1af7783dbabb"
110
+ },
111
+ {
112
+ "path": "weights/image_encoder/config.json",
113
+ "group": "base",
114
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/config.json",
115
+ "bytes": 703,
116
+ "sha256": "ba41139cc9dad159163a53e2aa847356b627f53fef988ad461659bd2d587d886"
117
+ },
118
+ {
119
+ "path": "weights/stable-diffusion-v1-5/unet/diffusion_pytorch_model.bin",
120
+ "group": "base",
121
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/diffusion_pytorch_model.bin",
122
+ "bytes": 3438354725,
123
+ "sha256": "c7da0e21ba7ea50637bee26e81c220844defdf01aafca02b2c42ecdadb813de4"
124
+ },
125
+ {
126
+ "path": "weights/stable-diffusion-v1-5/unet/config.json",
127
+ "group": "base",
128
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/config.json",
129
+ "bytes": 743,
130
+ "sha256": "78f474de6bab3d893868f37be97b636ae65c0df3073ed3256ca458ff599b5f96"
131
+ },
132
+ {
133
+ "path": "weights/sd-vae-ft-mse/diffusion_pytorch_model.bin",
134
+ "group": "base",
135
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/diffusion_pytorch_model.bin",
136
+ "bytes": 334707217,
137
+ "sha256": "1b4889b6b1d4ce7ae320a02dedaeff1780ad77d415ea0d744b476155c6377ddc"
138
+ },
139
+ {
140
+ "path": "weights/sd-vae-ft-mse/config.json",
141
+ "group": "base",
142
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/config.json",
143
+ "bytes": 547,
144
+ "sha256": "92d3dfb746fca211a2c9e019e285f8597412211728dce3c5bcf4eda0f2d62e7e"
145
+ },
146
+ {
147
+ "path": "weights/animatediff/mm_sd_v15_v2.ckpt",
148
+ "group": "base",
149
+ "url": "https://huggingface.co/guoyww/animatediff/resolve/fdfe36afa161e51b3e9c24022b0e368d59e7345e/mm_sd_v15_v2.ckpt",
150
+ "bytes": 1817888431,
151
+ "sha256": "69ed0f5fef82b110aca51bcab73b21104242bc65d6ab4b8b2a2a94d31cad1bf0"
152
+ }
153
+ ],
154
+ "base_components_note": "Seven pinned standard-VAE base components have been downloaded and SHA256 verified. GPU execution with the new variants is pending."
155
+ }
2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:6a1288711eaf2792f3581b3e175fb79bb8988e5b192a61178de322c587e810b8
3
+ size 8699157476
2610_runtime_asset_manifest.json ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "root": "2610_variant_runtime",
4
+ "status": "source_frozen_cpu_key_shape_verified_gpu_render_pending",
5
+ "source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
6
+ "source_contains_frozen_uncommitted_changes": true,
7
+ "source_freeze_sha256": "b8ab0585b0b827d4b19da49d6064793ed0f796d978707b5be3f749aec763efbf",
8
+ "source_file_count": 32,
9
+ "generated_document_and_base_manifest_count": 2,
10
+ "total_file_count": 34,
11
+ "total_bytes": 420063,
12
+ "bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
13
+ "bundle_sha256_format": "SHA256 of sorted UTF-8 lines: path + TAB + decimal bytes + TAB + sha256 + LF",
14
+ "files": [
15
+ {
16
+ "path": "2610_variant_runtime/LICENSE",
17
+ "bytes": 11357,
18
+ "sha256": "f9e2070c247517b1ddf65f7b11b393484a18da91a958fd18a97bd0f241c3125c"
19
+ },
20
+ {
21
+ "path": "2610_variant_runtime/NOTICE",
22
+ "bytes": 1517,
23
+ "sha256": "f77eb47163db686b37493c42071822b69823c3997a2be1f17eb53d6b6879d3a4"
24
+ },
25
+ {
26
+ "path": "2610_variant_runtime/README.md",
27
+ "bytes": 7049,
28
+ "sha256": "059a5ded8a4e914fc3d727783efa02c80e61fd92bd8a9240d5d4e99d3e9da4f9"
29
+ },
30
+ {
31
+ "path": "2610_variant_runtime/asset_manifest.json",
32
+ "bytes": 2484,
33
+ "sha256": "1d72168a5e9ed5bf3e8dc7878526646b9e8ed7091a0c0834f36a93bab9bdd05b"
34
+ },
35
+ {
36
+ "path": "2610_variant_runtime/diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml",
37
+ "bytes": 1493,
38
+ "sha256": "100c01244d99bc9bd263a9695e6cc95685b0acdebc17681741d709e3116ba5b4"
39
+ },
40
+ {
41
+ "path": "2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml",
42
+ "bytes": 1502,
43
+ "sha256": "7258d8124521c81d2b2724115f0e55d2ece513f8715a0f8a3d378c6537096ef1"
44
+ },
45
+ {
46
+ "path": "2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml",
47
+ "bytes": 1497,
48
+ "sha256": "37cf67ec1a2b9c8020927ca849fae7a8da7b63762d9c9010a59570b0619a7aa3"
49
+ },
50
+ {
51
+ "path": "2610_variant_runtime/diffusion/inference.py",
52
+ "bytes": 18709,
53
+ "sha256": "09ab1c04ad2c551a5ba5a941207bb96a27107c60a814815fde83dd12f1d2a122"
54
+ },
55
+ {
56
+ "path": "2610_variant_runtime/diffusion/models/attention.py",
57
+ "bytes": 21014,
58
+ "sha256": "966a677b946c7461343a70f166fad7f6db71b4b89fdf59805913fc65cb1fa388"
59
+ },
60
+ {
61
+ "path": "2610_variant_runtime/diffusion/models/conv_in.py",
62
+ "bytes": 745,
63
+ "sha256": "6e5938de720d0b58cf70f70e859fcc6aada7ffad7add7a75b97571820447c901"
64
+ },
65
+ {
66
+ "path": "2610_variant_runtime/diffusion/models/model_vfi.py",
67
+ "bytes": 32321,
68
+ "sha256": "1d82eb6527b48e8a7f91dc399e18a0b22dd09588b651833abc768a57bd2ba04a"
69
+ },
70
+ {
71
+ "path": "2610_variant_runtime/diffusion/models/motion_module.py",
72
+ "bytes": 13140,
73
+ "sha256": "b7b31fdc11731a14eb8335f658b0b731c137cdacdb4ac7523046fbcee34bd69b"
74
+ },
75
+ {
76
+ "path": "2610_variant_runtime/diffusion/models/mutual_self_attention.py",
77
+ "bytes": 14561,
78
+ "sha256": "d062e505eea0bbd925b971e4871ce4c0dfc9a6bb99873f5f394411d6b7c338d2"
79
+ },
80
+ {
81
+ "path": "2610_variant_runtime/diffusion/models/pose_guider.py",
82
+ "bytes": 1674,
83
+ "sha256": "f10fc38a83dda911a252033a01d6b11d19b6becf6ccb80e8b0fe252563ec7528"
84
+ },
85
+ {
86
+ "path": "2610_variant_runtime/diffusion/models/resnet.py",
87
+ "bytes": 8153,
88
+ "sha256": "186c7efd14d1b6284807b7ab3561973af90b6ffc8e149b73787034840de93e31"
89
+ },
90
+ {
91
+ "path": "2610_variant_runtime/diffusion/models/transformer_2d.py",
92
+ "bytes": 18933,
93
+ "sha256": "36fe3665376cc07eb5feeae43a3c50c5c64913c02412e2d536954460f103f2bb"
94
+ },
95
+ {
96
+ "path": "2610_variant_runtime/diffusion/models/transformer_3d.py",
97
+ "bytes": 5897,
98
+ "sha256": "68cd30d1e85122bc7621ef13d3a9a165dc3e6bcbcb97ef5a9aa2500fb6826b35"
99
+ },
100
+ {
101
+ "path": "2610_variant_runtime/diffusion/models/unet_2d_blocks.py",
102
+ "bytes": 41508,
103
+ "sha256": "da56135d0d1b6e56fa87e636f83c731fbe809de42430dfecccebf27a42434eb2"
104
+ },
105
+ {
106
+ "path": "2610_variant_runtime/diffusion/models/unet_2d_condition.py",
107
+ "bytes": 63680,
108
+ "sha256": "7aec0a8de40cd3d8ea38c051aebb480a245212ccdb942d1b1db9a43d5347225f"
109
+ },
110
+ {
111
+ "path": "2610_variant_runtime/diffusion/models/unet_3d.py",
112
+ "bytes": 27957,
113
+ "sha256": "d3e3948b2b29cd3ecbf6c5c3d5affcd1d8987923c85658a5c187c7583585b38c"
114
+ },
115
+ {
116
+ "path": "2610_variant_runtime/diffusion/models/unet_3d_blocks.py",
117
+ "bytes": 31017,
118
+ "sha256": "274c5eb419db218a16920cf85aa0e2d2f33f0079a3be55da98fb7c2b2fd2a7da"
119
+ },
120
+ {
121
+ "path": "2610_variant_runtime/diffusion/pipelines/__init__.py",
122
+ "bytes": 1,
123
+ "sha256": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b"
124
+ },
125
+ {
126
+ "path": "2610_variant_runtime/diffusion/pipelines/pipeline_vfi2video_share_vae.py",
127
+ "bytes": 19217,
128
+ "sha256": "fa608e5abdc75e6393bba8aa405e3fe3d1f8b4c0f656e0ae0c5aa0b654a2f355"
129
+ },
130
+ {
131
+ "path": "2610_variant_runtime/diffusion/utils/__init__.py",
132
+ "bytes": 1,
133
+ "sha256": "01ba4719c80b6fe911b091a7c05124b64eeece964e09c058ef8f9805daca546b"
134
+ },
135
+ {
136
+ "path": "2610_variant_runtime/diffusion/utils/util.py",
137
+ "bytes": 5124,
138
+ "sha256": "654e0001976be1b0bbfcb8cb5c4def29fb5dabe55d7c6896a02603745d721296"
139
+ },
140
+ {
141
+ "path": "2610_variant_runtime/diffusion/utils/video_utils.py",
142
+ "bytes": 2859,
143
+ "sha256": "0ddb8a7cac82b24295c4c0f5a18f529df82e44c0d4a0bb5ea8acf0d128d37baf"
144
+ },
145
+ {
146
+ "path": "2610_variant_runtime/licenses/AnimateDiff.txt",
147
+ "bytes": 11357,
148
+ "sha256": "c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4"
149
+ },
150
+ {
151
+ "path": "2610_variant_runtime/licenses/DWPose.txt",
152
+ "bytes": 11994,
153
+ "sha256": "3abf0a61cbaa441957d4c5820be5185b910ed207abf80f60f92c9533b2e16e47"
154
+ },
155
+ {
156
+ "path": "2610_variant_runtime/licenses/OpenRAIL-M.txt",
157
+ "bytes": 14385,
158
+ "sha256": "be351ebe7ac01bcdbb018639aadcfd38f136b7dc3f2a3d4d3a24db51d1b210ef"
159
+ },
160
+ {
161
+ "path": "2610_variant_runtime/licenses/PixArt-alpha.txt",
162
+ "bytes": 11365,
163
+ "sha256": "6582247f37ea5556681f6224e86db09ec7272c99091e7284bb5c9cf83d6edca1"
164
+ },
165
+ {
166
+ "path": "2610_variant_runtime/licenses/diffusers.txt",
167
+ "bytes": 11357,
168
+ "sha256": "f9e2070c247517b1ddf65f7b11b393484a18da91a958fd18a97bd0f241c3125c"
169
+ },
170
+ {
171
+ "path": "2610_variant_runtime/licenses/magic-animate.txt",
172
+ "bytes": 1519,
173
+ "sha256": "6c76998d8b6a8c903d741de4f0c41fd7971d08746aebd2f39e9a9f0fb9b662e5"
174
+ },
175
+ {
176
+ "path": "2610_variant_runtime/requirements.lock.txt",
177
+ "bytes": 2766,
178
+ "sha256": "dfdd012e92ece6da107024040eded8ef55e75b9ab51ba0a8e95b19f0f7621f20"
179
+ },
180
+ {
181
+ "path": "2610_variant_runtime/scripts/download_assets.py",
182
+ "bytes": 1910,
183
+ "sha256": "50657ca0d2257d9fdd85c766ffd00ee4b5b0185e0a9a583e27ebd633c41ad488"
184
+ }
185
+ ],
186
+ "excludes": [
187
+ "model weights inside runtime",
188
+ "private inputs",
189
+ "training data",
190
+ "logs",
191
+ "tests",
192
+ "optimizer/RNG state",
193
+ "custom temporal decoder",
194
+ "git metadata",
195
+ "virtual environments"
196
+ ],
197
+ "hub_commit": null,
198
+ "fresh_hub_download_verification": "pending",
199
+ "gpu_render": "pending"
200
+ }
2610_variant_asset_manifest.json ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "status": "source_sha256_and_cpu_key_shape_verified_gpu_render_pending",
4
+ "prepared_at": "2026-10-17",
5
+ "repo_id": "H-Liu1997/Video-Motion-Graphs",
6
+ "existing_release_preserved": {
7
+ "path": "finetune_weighted/checkpoint-8000/pytorch_model.bin",
8
+ "sha256": "9cc0f0354c5ec4b33085196ba5786f845e0901fd1dc7159e57be14d972c371af",
9
+ "revision": "44ad3acb918e062f5f0c11ccc2e63cb0f3965e63"
10
+ },
11
+ "new_variant_count": 3,
12
+ "new_model_bytes": 26097472428,
13
+ "variants": [
14
+ {
15
+ "variant_id": "v7_dup_14_continue_2_step655000",
16
+ "relative_directory": "2409_variants/v7_dup_14_continue_2_step655000",
17
+ "source_material_month": "2024-09",
18
+ "date_basis": "Earliest confirmed source-material month; not an inferred training-start date.",
19
+ "original_run": "v7_dup_14_continue_2",
20
+ "checkpoint_step": 655000,
21
+ "scope": "Historical interpolation checkpoint. Its relationship to any final TANGO or ACInterp paper model is unconfirmed.",
22
+ "assets": [
23
+ {
24
+ "path": "2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin",
25
+ "filename": "pytorch_model.bin",
26
+ "bytes": 8699157476,
27
+ "sha256": "beae0aadd1fc049da2f776ecef51a356727eccd18fa5cb5481738ae3adfbabe1",
28
+ "format": "PyTorch full model state dictionary",
29
+ "sha256_evidence": "Full SHA256 of the downloaded source file matches the source-storage SHA256; independent fresh-Hub-download verification is pending."
30
+ }
31
+ ],
32
+ "architecture": {
33
+ "code_family": "Custom pose-guided diffusion interpolation",
34
+ "seed_guider_channels_expected_from_source": 5,
35
+ "seed_guider_tensor_shape_verified": [
36
+ 320,
37
+ 5,
38
+ 3,
39
+ 3
40
+ ],
41
+ "context_frames_per_end": 3,
42
+ "generated_frames": 8,
43
+ "total_frames": 14,
44
+ "image_size": 512,
45
+ "verification_status": "CPU strict key/shape verified; GPU forward pending",
46
+ "seed_mask_channels": "4 latent + 1 known-frame mask"
47
+ },
48
+ "inference": {
49
+ "profile": "standard_pose",
50
+ "vae": "stabilityai/sd-vae-ft-mse",
51
+ "custom_temporal_decoder_required": false,
52
+ "code_repo": "https://github.com/H-Liu1997/Video-Motion-Graphs",
53
+ "code_revision": null,
54
+ "config_path": "2610_variant_runtime/diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml",
55
+ "config_sha256": "100c01244d99bc9bd263a9695e6cc95685b0acdebc17681741d709e3116ba5b4",
56
+ "environment_lock_path": "2610_variant_runtime/requirements.lock.txt",
57
+ "environment_lock_sha256": "dfdd012e92ece6da107024040eded8ef55e75b9ab51ba0a8e95b19f0f7621f20",
58
+ "commands": [
59
+ "WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml --checkpoint ../2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin --json inputs/input.json --output-dir outputs"
60
+ ],
61
+ "status": "frozen command; CPU key/shape passed; GPU execution pending",
62
+ "code_source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
63
+ "code_source_contains_frozen_uncommitted_changes": true,
64
+ "runtime_root": "2610_variant_runtime",
65
+ "runtime_manifest": "2610_runtime_asset_manifest.json",
66
+ "runtime_bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
67
+ "command_working_directory": "2610_variant_runtime",
68
+ "seed": 2024,
69
+ "guidance_scale": 3.5,
70
+ "denoising_steps": 20
71
+ },
72
+ "validation": {
73
+ "source_file_sha256": "verified",
74
+ "source_sha256": "beae0aadd1fc049da2f776ecef51a356727eccd18fa5cb5481738ae3adfbabe1",
75
+ "source_bytes_verified": true,
76
+ "hub_commit": null,
77
+ "hub_lfs_sha256": "pending",
78
+ "fresh_download_sha256": "pending",
79
+ "cpu_key_shape_check": {
80
+ "status": "passed",
81
+ "method": "CPU mmap state dict against exact meta-constructed model; shape/key check without tensor copies or forward",
82
+ "key_count": 1974,
83
+ "missing_keys": [],
84
+ "unexpected_keys": [],
85
+ "seed_guider_weight_shape": [
86
+ 320,
87
+ 5,
88
+ 3,
89
+ 3
90
+ ],
91
+ "forward_executed": false
92
+ },
93
+ "strict_gpu_load": "pending",
94
+ "real_input_render": "pending",
95
+ "input_assets": [],
96
+ "output_video": null,
97
+ "hardware": null,
98
+ "environment": null,
99
+ "seed": 2024,
100
+ "metrics": null,
101
+ "receipt": null
102
+ },
103
+ "excluded_training_state": [
104
+ "optimizer",
105
+ "scheduler",
106
+ "mixed-precision scaler",
107
+ "random-number generator state"
108
+ ],
109
+ "training_resume_supported": false,
110
+ "license": "creativeml-openrail-m",
111
+ "license_note": "Retain the applicable Stable Diffusion / CreativeML OpenRAIL-M model terms and upstream component terms. Project source-code licensing is separate."
112
+ },
113
+ {
114
+ "variant_id": "v7_dup_14_s2_8frames_512_step9000",
115
+ "relative_directory": "2411_variants/v7_dup_14_s2_8frames_512_step9000",
116
+ "source_material_month": "2024-11",
117
+ "date_basis": "Earliest confirmed source-material month; not an inferred training-start date.",
118
+ "original_run": "v7_dup_14_s2_8frames_512",
119
+ "checkpoint_step": 9000,
120
+ "scope": "Historical checkpoint referenced by the 8-frame 512 inference configuration; no best-checkpoint or paper-final claim.",
121
+ "assets": [
122
+ {
123
+ "path": "2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin",
124
+ "filename": "pytorch_model.bin",
125
+ "bytes": 8699157476,
126
+ "sha256": "6a1288711eaf2792f3581b3e175fb79bb8988e5b192a61178de322c587e810b8",
127
+ "format": "PyTorch full model state dictionary",
128
+ "sha256_evidence": "Full SHA256 of the downloaded source file matches the source-storage SHA256; independent fresh-Hub-download verification is pending."
129
+ }
130
+ ],
131
+ "architecture": {
132
+ "code_family": "Custom pose-guided diffusion interpolation",
133
+ "seed_guider_channels_expected_from_source": 5,
134
+ "seed_guider_tensor_shape_verified": [
135
+ 320,
136
+ 5,
137
+ 3,
138
+ 3
139
+ ],
140
+ "context_frames_per_end": 3,
141
+ "generated_frames": 8,
142
+ "total_frames": 14,
143
+ "image_size": 512,
144
+ "verification_status": "CPU strict key/shape verified; GPU forward pending",
145
+ "seed_mask_channels": "4 latent + 1 known-frame mask"
146
+ },
147
+ "inference": {
148
+ "profile": "standard_pose",
149
+ "vae": "stabilityai/sd-vae-ft-mse",
150
+ "custom_temporal_decoder_required": false,
151
+ "code_repo": "https://github.com/H-Liu1997/Video-Motion-Graphs",
152
+ "code_revision": null,
153
+ "config_path": "2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml",
154
+ "config_sha256": "37cf67ec1a2b9c8020927ca849fae7a8da7b63762d9c9010a59570b0619a7aa3",
155
+ "environment_lock_path": "2610_variant_runtime/requirements.lock.txt",
156
+ "environment_lock_sha256": "dfdd012e92ece6da107024040eded8ef55e75b9ab51ba0a8e95b19f0f7621f20",
157
+ "commands": [
158
+ "WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin --json inputs/input.json --output-dir outputs"
159
+ ],
160
+ "status": "frozen command; CPU key/shape passed; GPU execution pending",
161
+ "code_source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
162
+ "code_source_contains_frozen_uncommitted_changes": true,
163
+ "runtime_root": "2610_variant_runtime",
164
+ "runtime_manifest": "2610_runtime_asset_manifest.json",
165
+ "runtime_bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
166
+ "command_working_directory": "2610_variant_runtime",
167
+ "seed": 2024,
168
+ "guidance_scale": 1.0,
169
+ "denoising_steps": 20
170
+ },
171
+ "validation": {
172
+ "source_file_sha256": "verified",
173
+ "source_sha256": "6a1288711eaf2792f3581b3e175fb79bb8988e5b192a61178de322c587e810b8",
174
+ "source_bytes_verified": true,
175
+ "hub_commit": null,
176
+ "hub_lfs_sha256": "pending",
177
+ "fresh_download_sha256": "pending",
178
+ "cpu_key_shape_check": {
179
+ "status": "passed",
180
+ "method": "CPU mmap state dict against exact meta-constructed model; shape/key check without tensor copies or forward",
181
+ "key_count": 1974,
182
+ "missing_keys": [],
183
+ "unexpected_keys": [],
184
+ "seed_guider_weight_shape": [
185
+ 320,
186
+ 5,
187
+ 3,
188
+ 3
189
+ ],
190
+ "forward_executed": false
191
+ },
192
+ "strict_gpu_load": "pending",
193
+ "real_input_render": "pending",
194
+ "input_assets": [],
195
+ "output_video": null,
196
+ "hardware": null,
197
+ "environment": null,
198
+ "seed": 2024,
199
+ "metrics": null,
200
+ "receipt": null
201
+ },
202
+ "excluded_training_state": [
203
+ "optimizer",
204
+ "scheduler",
205
+ "mixed-precision scaler",
206
+ "random-number generator state"
207
+ ],
208
+ "training_resume_supported": false,
209
+ "license": "creativeml-openrail-m",
210
+ "license_note": "Retain the applicable Stable Diffusion / CreativeML OpenRAIL-M model terms and upstream component terms. Project source-code licensing is separate."
211
+ },
212
+ {
213
+ "variant_id": "v7_dup_14_s2_12frames_512_step30000",
214
+ "relative_directory": "2411_variants/v7_dup_14_s2_12frames_512_step30000",
215
+ "source_material_month": "2024-11",
216
+ "date_basis": "Earliest confirmed source-material month; not an inferred training-start date.",
217
+ "original_run": "v7_dup_14_s2_12frames_512",
218
+ "checkpoint_step": 30000,
219
+ "scope": "Historical checkpoint referenced by the 12-frame 512 inference configuration; no best-checkpoint or paper-final claim.",
220
+ "assets": [
221
+ {
222
+ "path": "2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin",
223
+ "filename": "pytorch_model.bin",
224
+ "bytes": 8699157476,
225
+ "sha256": "98bc64d7c931a7e414e9e9b45709420477d8625055043e945ad01d121f2302fb",
226
+ "format": "PyTorch full model state dictionary",
227
+ "sha256_evidence": "Full SHA256 of the downloaded source file matches the source-storage SHA256; independent fresh-Hub-download verification is pending."
228
+ }
229
+ ],
230
+ "architecture": {
231
+ "code_family": "Custom pose-guided diffusion interpolation",
232
+ "seed_guider_channels_expected_from_source": 5,
233
+ "seed_guider_tensor_shape_verified": [
234
+ 320,
235
+ 5,
236
+ 3,
237
+ 3
238
+ ],
239
+ "context_frames_per_end": 1,
240
+ "generated_frames": 12,
241
+ "total_frames": 14,
242
+ "image_size": 512,
243
+ "verification_status": "CPU strict key/shape verified; GPU forward pending",
244
+ "seed_mask_channels": "4 latent + 1 known-frame mask"
245
+ },
246
+ "inference": {
247
+ "profile": "standard_pose",
248
+ "vae": "stabilityai/sd-vae-ft-mse",
249
+ "custom_temporal_decoder_required": false,
250
+ "code_repo": "https://github.com/H-Liu1997/Video-Motion-Graphs",
251
+ "code_revision": null,
252
+ "config_path": "2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml",
253
+ "config_sha256": "7258d8124521c81d2b2724115f0e55d2ece513f8715a0f8a3d378c6537096ef1",
254
+ "environment_lock_path": "2610_variant_runtime/requirements.lock.txt",
255
+ "environment_lock_sha256": "dfdd012e92ece6da107024040eded8ef55e75b9ab51ba0a8e95b19f0f7621f20",
256
+ "commands": [
257
+ "WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin --json inputs/input.json --output-dir outputs"
258
+ ],
259
+ "status": "frozen command; CPU key/shape passed; GPU execution pending",
260
+ "code_source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
261
+ "code_source_contains_frozen_uncommitted_changes": true,
262
+ "runtime_root": "2610_variant_runtime",
263
+ "runtime_manifest": "2610_runtime_asset_manifest.json",
264
+ "runtime_bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
265
+ "command_working_directory": "2610_variant_runtime",
266
+ "seed": 2024,
267
+ "guidance_scale": 3.5,
268
+ "denoising_steps": 20
269
+ },
270
+ "validation": {
271
+ "source_file_sha256": "verified",
272
+ "source_sha256": "98bc64d7c931a7e414e9e9b45709420477d8625055043e945ad01d121f2302fb",
273
+ "source_bytes_verified": true,
274
+ "hub_commit": null,
275
+ "hub_lfs_sha256": "pending",
276
+ "fresh_download_sha256": "pending",
277
+ "cpu_key_shape_check": {
278
+ "status": "passed",
279
+ "method": "CPU mmap state dict against exact meta-constructed model; shape/key check without tensor copies or forward",
280
+ "key_count": 1974,
281
+ "missing_keys": [],
282
+ "unexpected_keys": [],
283
+ "seed_guider_weight_shape": [
284
+ 320,
285
+ 5,
286
+ 3,
287
+ 3
288
+ ],
289
+ "forward_executed": false
290
+ },
291
+ "strict_gpu_load": "pending",
292
+ "real_input_render": "pending",
293
+ "input_assets": [],
294
+ "output_video": null,
295
+ "hardware": null,
296
+ "environment": null,
297
+ "seed": 2024,
298
+ "metrics": null,
299
+ "receipt": null
300
+ },
301
+ "excluded_training_state": [
302
+ "optimizer",
303
+ "scheduler",
304
+ "mixed-precision scaler",
305
+ "random-number generator state"
306
+ ],
307
+ "training_resume_supported": false,
308
+ "license": "creativeml-openrail-m",
309
+ "license_note": "Retain the applicable Stable Diffusion / CreativeML OpenRAIL-M model terms and upstream component terms. Project source-code licensing is separate."
310
+ }
311
+ ],
312
+ "base_components": [
313
+ {
314
+ "path": "weights/image_encoder/pytorch_model.bin",
315
+ "group": "base",
316
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/pytorch_model.bin",
317
+ "bytes": 1215993967,
318
+ "sha256": "89d2aa29b5fdf64f3ad4f45fb4227ea98bc45156bbae673b85be1af7783dbabb"
319
+ },
320
+ {
321
+ "path": "weights/image_encoder/config.json",
322
+ "group": "base",
323
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/config.json",
324
+ "bytes": 703,
325
+ "sha256": "ba41139cc9dad159163a53e2aa847356b627f53fef988ad461659bd2d587d886"
326
+ },
327
+ {
328
+ "path": "weights/stable-diffusion-v1-5/unet/diffusion_pytorch_model.bin",
329
+ "group": "base",
330
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/diffusion_pytorch_model.bin",
331
+ "bytes": 3438354725,
332
+ "sha256": "c7da0e21ba7ea50637bee26e81c220844defdf01aafca02b2c42ecdadb813de4"
333
+ },
334
+ {
335
+ "path": "weights/stable-diffusion-v1-5/unet/config.json",
336
+ "group": "base",
337
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/config.json",
338
+ "bytes": 743,
339
+ "sha256": "78f474de6bab3d893868f37be97b636ae65c0df3073ed3256ca458ff599b5f96"
340
+ },
341
+ {
342
+ "path": "weights/sd-vae-ft-mse/diffusion_pytorch_model.bin",
343
+ "group": "base",
344
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/diffusion_pytorch_model.bin",
345
+ "bytes": 334707217,
346
+ "sha256": "1b4889b6b1d4ce7ae320a02dedaeff1780ad77d415ea0d744b476155c6377ddc"
347
+ },
348
+ {
349
+ "path": "weights/sd-vae-ft-mse/config.json",
350
+ "group": "base",
351
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/config.json",
352
+ "bytes": 547,
353
+ "sha256": "92d3dfb746fca211a2c9e019e285f8597412211728dce3c5bcf4eda0f2d62e7e"
354
+ },
355
+ {
356
+ "path": "weights/animatediff/mm_sd_v15_v2.ckpt",
357
+ "group": "base",
358
+ "url": "https://huggingface.co/guoyww/animatediff/resolve/fdfe36afa161e51b3e9c24022b0e368d59e7345e/mm_sd_v15_v2.ckpt",
359
+ "bytes": 1817888431,
360
+ "sha256": "69ed0f5fef82b110aca51bcab73b21104242bc65d6ab4b8b2a2a94d31cad1bf0"
361
+ }
362
+ ],
363
+ "base_components_note": "Seven pinned standard-VAE base files totaling 6,806,946,333 bytes have passed full SHA256 checks; GPU inference remains pending.",
364
+ "runtime": {
365
+ "root": "2610_variant_runtime",
366
+ "source_base_commit": "331fcff579d1bc60e54e568b9f524aa812f64c80",
367
+ "source_contains_frozen_uncommitted_changes": true,
368
+ "bundle_sha256": "2b1b5a1b19f8be6f97a74a640a085b728ee568d8953f8dbc7a3b5054ac5d8e95",
369
+ "total_file_count": 34,
370
+ "total_bytes": 420063,
371
+ "manifest": "2610_runtime_asset_manifest.json"
372
+ },
373
+ "upstream_license_metadata": [
374
+ {
375
+ "repo": "stabilityai/sd-vae-ft-mse",
376
+ "revision": "31f26fdeee1355a5c34592e401dd41e45d25a493",
377
+ "license": "mit"
378
+ },
379
+ {
380
+ "repo": "guoyww/animatediff",
381
+ "revision": "fdfe36afa161e51b3e9c24022b0e368d59e7345e",
382
+ "license": "apache-2.0"
383
+ },
384
+ {
385
+ "repo": "lambda/sd-image-variations-diffusers",
386
+ "revision": "42bc0ee1726b141d49f519a6ea02ccfbf073db2e",
387
+ "license": "creativeml-openrail-m"
388
+ },
389
+ {
390
+ "repo": "stable-diffusion-v1-5/stable-diffusion-v1-5",
391
+ "revision": "451f4fe16113bff5a5d2269ed5ad43b0592e9a14",
392
+ "license": "creativeml-openrail-m"
393
+ }
394
+ ]
395
+ }
2610_variant_runtime/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, Any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
2610_variant_runtime/NOTICE ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Video Motion Graphs
2
+ Copyright 2026 Haiyang Liu and contributors.
3
+
4
+ Original project code is licensed under Apache License 2.0. The following
5
+ adapted components retain their original notices and licenses:
6
+
7
+ Hugging Face Diffusers: diffusion/models/{attention,resnet,transformer_2d,
8
+ unet_2d_blocks,unet_2d_condition,unet_3d_blocks}.py and diffusion/utils/util.py.
9
+ Apache-2.0; see licenses/diffusers.txt.
10
+ AnimateDiff: diffusion/models/{motion_module,unet_3d}.py.
11
+ Apache-2.0; see licenses/AnimateDiff.txt.
12
+ MagicAnimate: diffusion/models/mutual_self_attention.py.
13
+ BSD-3-Clause; see licenses/magic-animate.txt.
14
+ DWPose: vmg/dataloaders/tools/dwpose/.
15
+ Apache-2.0; see licenses/DWPose.txt.
16
+ PixArt-alpha: attention implementation cited in diffusion/models/attention.py.
17
+ Apache-2.0; see licenses/PixArt-alpha.txt.
18
+
19
+ These implementations were adapted for weighted-pose video interpolation,
20
+ reference attention, motion-graph construction and local video preprocessing.
21
+ Original attribution headers remain in the corresponding source files.
22
+
23
+ Downloaded model weights retain their own terms. Stable Diffusion 1.5,
24
+ SD image variations and the derived VMG checkpoint use CreativeML OpenRAIL-M
25
+ (licenses/OpenRAIL-M.txt). SD-VAE-ft-mse declares MIT and AnimateDiff model
26
+ weights declare Apache-2.0 in their upstream model cards. The project source
27
+ license does not replace third-party model or example-media terms.
28
+
29
+ The five-channel seed-mask inference path is adapted from Haiyang Liu's
30
+ November 2024 HMInterp research code.
2610_variant_runtime/README.md ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 2610 standalone historical-variant runtime
2
+
3
+ This bundle runs the three dated five-channel interpolation checkpoints in this model repository with the standard SD VAE. Model SHA256 checks and strict CPU key/shape checks have passed. **GPU forward execution, rendered-video evaluation and fresh-Hub-download verification are pending.** CPU checks do not establish inference quality or a successful GPU run.
4
+
5
+ The code is a frozen snapshot based on upstream commit `331fcff579d1bc60e54e568b9f524aa812f64c80` with the included variant support. It is identified by the per-file hashes in [runtime manifest](../2610_runtime_asset_manifest.json), not by claiming that the upstream commit already contains these changes. Only the standard-VAE profile is included. The original four-channel `finetune_weighted/checkpoint-8000` release is separate.
6
+
7
+ ## Download
8
+
9
+ Install `uv`, then run this in a new directory. It resolves one Hub commit and downloads all three variants and the runtime from that same revision. The transfer tools run outside the model environment.
10
+
11
+ ```sh
12
+ uv run --no-project --with huggingface_hub==2.2.0 python - <<'PY'
13
+ from huggingface_hub import HfApi, snapshot_download
14
+ repo = "H-Liu1997/Video-Motion-Graphs"
15
+ revision = HfApi(token=False).model_info(repo).sha
16
+ snapshot_download(
17
+ repo_id=repo,
18
+ revision=revision,
19
+ token=False,
20
+ local_dir="vmg-variant-release",
21
+ allow_patterns=[
22
+ "2610_variant_runtime/*",
23
+ "2610_runtime_asset_manifest.json",
24
+ "2610_variant_asset_manifest.json",
25
+ "2409_variants/v7_dup_14_continue_2_step655000/*",
26
+ "2411_variants/v7_dup_14_s2_8frames_512_step9000/*",
27
+ "2411_variants/v7_dup_14_s2_12frames_512_step30000/*",
28
+ ],
29
+ )
30
+ print("Downloaded revision:", revision)
31
+ PY
32
+ ```
33
+
34
+ Record the printed commit for reproduction. Before inference, verify the downloaded runtime and model files against their manifests:
35
+
36
+ ```sh
37
+ cd vmg-variant-release
38
+ python3 - <<'PY'
39
+ import hashlib, json
40
+ from pathlib import Path
41
+ root = Path.cwd()
42
+ runtime = json.loads((root / "2610_runtime_asset_manifest.json").read_text())
43
+ variants = json.loads((root / "2610_variant_asset_manifest.json").read_text())
44
+ files = list(runtime["files"])
45
+ files += [a for v in variants["variants"] for a in v["assets"]]
46
+ for item in files:
47
+ path = root / item["path"]
48
+ assert path.stat().st_size == item["bytes"], item["path"]
49
+ digest = hashlib.sha256()
50
+ with path.open("rb") as stream:
51
+ for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
52
+ digest.update(chunk)
53
+ assert digest.hexdigest() == item["sha256"], item["path"]
54
+ print("Verified files:", len(files))
55
+ PY
56
+ ```
57
+
58
+ ## Install and fetch base components
59
+
60
+ The required platform is Linux x86_64 with an NVIDIA CUDA-capable GPU. The model environment pins Python 3.10, PyTorch 2.2.2 / CUDA 12.1 and Diffusers 0.24.0. Variant GPU memory requirements and inference execution remain unverified.
61
+
62
+ ```sh
63
+ cd 2610_variant_runtime
64
+ uv venv --python 3.10 .venv
65
+ uv pip install --python .venv/bin/python --no-deps --index-strategy unsafe-best-match --extra-index-url https://download.pytorch.org/whl/cu121 -r requirements.lock.txt
66
+ .venv/bin/python scripts/download_assets.py --group base
67
+ .venv/bin/python scripts/download_assets.py --group base --verify-only
68
+ ```
69
+
70
+ The seven base files total 6,806,946,333 bytes. Their public URLs and SHA256 hashes are pinned in `asset_manifest.json`. The downloader places them in this runtime's `weights/` directory. Keep the inference environment's pinned `huggingface-hub==0.25.2`; use a separate tool environment for modern Hub transfers.
71
+
72
+ ## Supply aligned input
73
+
74
+ Provide your own RGB video and its aligned weighted-pose heatmap video with the same frame rate and dimensions. Each needs at least 14 frames from `start_idx`. Ordinary skeleton-only pose renderings are not interchangeable with the weighted heatmaps expected by this profile. This bundle contains no private validation videos, preprocessing models, training data or logs.
75
+
76
+ Save `inputs/input.json` with the following structure, replacing only the two input paths:
77
+
78
+ ```json
79
+ [
80
+ {
81
+ "video_path": "/path/to/rgb.mp4",
82
+ "kps_path": "/path/to/weighted_heatmap.mp4",
83
+ "mode": "test",
84
+ "start_idx": 0
85
+ }
86
+ ]
87
+ ```
88
+
89
+ ## Run a selected variant
90
+
91
+ Run from `2610_variant_runtime/`. The explicit `--checkpoint` argument selects the dated model file; the configuration's historical default weight path is not the Hub layout.
92
+
93
+ ```sh
94
+ WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml --checkpoint ../2409_variants/v7_dup_14_continue_2_step655000/pytorch_model.bin --json inputs/input.json --output-dir outputs
95
+
96
+ WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin --json inputs/input.json --output-dir outputs
97
+
98
+ WANDB_MODE=disabled .venv/bin/python diffusion/inference.py --config diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml --checkpoint ../2411_variants/v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin --json inputs/input.json --output-dir outputs
99
+ ```
100
+
101
+ These are the configured commands, not a claim that a GPU render has already completed. Outputs are separated by the configuration's experiment name. Local inference receipts can contain your input paths; review them before sharing.
102
+
103
+ | Variant | Seed | Context + Generated + Context | Size | DDIM Steps | Guidance |
104
+ | --- | ---: | --- | --- | ---: | ---: |
105
+ | 2409 step 655000 | 2024 | 3 + 8 + 3 | 512 square with black padding | 20 | 3.5 |
106
+ | 2411 8-frame step 9000 | 2024 | 3 + 8 + 3 | 512 square with black padding | 20 | 1.0 |
107
+ | 2411 12-frame step 30000 | 2024 | 1 + 12 + 1 | 512 square with black padding | 20 | 3.5 |
108
+
109
+ All three checkpoints have 1,974 keys and a seed-guider convolution with shape `[320, 5, 3, 3]`: four latent channels plus one known-frame mask. A strict CPU check against the meta-constructed model found no missing or unexpected keys and no shape mismatch. No forward pass was performed by that check.
110
+
111
+ ## License and provenance
112
+
113
+ Original project runtime code is Apache-2.0, with adapted components retaining the notices in [NOTICE](NOTICE) and `licenses/`, including the MagicAnimate BSD-3-Clause terms. This source-code license does not relicense model weights or user inputs. The variant model weights retain the repository's CreativeML OpenRAIL-M terms. Upstream SD 1.5 and image-variation components declare CreativeML OpenRAIL-M, SD-VAE-ft-mse declares MIT, and AnimateDiff weights declare Apache-2.0 at the pinned revisions. Preserve these upstream terms.
114
+
115
+ The `2409` and `2411` model-directory prefixes describe source material from September and November 2024. The `2610` runtime prefix describes this October 2026 packaging. No best-checkpoint, final-TANGO/ACInterp or paper-benchmark equivalence claim is made. Training optimizer, scheduler, scaler and RNG state are not included.
2610_variant_runtime/asset_manifest.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "format_version": 1,
3
+ "assets": [
4
+ {
5
+ "path": "weights/image_encoder/pytorch_model.bin",
6
+ "group": "base",
7
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/pytorch_model.bin",
8
+ "bytes": 1215993967,
9
+ "sha256": "89d2aa29b5fdf64f3ad4f45fb4227ea98bc45156bbae673b85be1af7783dbabb"
10
+ },
11
+ {
12
+ "path": "weights/image_encoder/config.json",
13
+ "group": "base",
14
+ "url": "https://huggingface.co/lambda/sd-image-variations-diffusers/resolve/42bc0ee1726b141d49f519a6ea02ccfbf073db2e/image_encoder/config.json",
15
+ "bytes": 703,
16
+ "sha256": "ba41139cc9dad159163a53e2aa847356b627f53fef988ad461659bd2d587d886"
17
+ },
18
+ {
19
+ "path": "weights/stable-diffusion-v1-5/unet/diffusion_pytorch_model.bin",
20
+ "group": "base",
21
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/diffusion_pytorch_model.bin",
22
+ "bytes": 3438354725,
23
+ "sha256": "c7da0e21ba7ea50637bee26e81c220844defdf01aafca02b2c42ecdadb813de4"
24
+ },
25
+ {
26
+ "path": "weights/stable-diffusion-v1-5/unet/config.json",
27
+ "group": "base",
28
+ "url": "https://huggingface.co/stable-diffusion-v1-5/stable-diffusion-v1-5/resolve/451f4fe16113bff5a5d2269ed5ad43b0592e9a14/unet/config.json",
29
+ "bytes": 743,
30
+ "sha256": "78f474de6bab3d893868f37be97b636ae65c0df3073ed3256ca458ff599b5f96"
31
+ },
32
+ {
33
+ "path": "weights/sd-vae-ft-mse/diffusion_pytorch_model.bin",
34
+ "group": "base",
35
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/diffusion_pytorch_model.bin",
36
+ "bytes": 334707217,
37
+ "sha256": "1b4889b6b1d4ce7ae320a02dedaeff1780ad77d415ea0d744b476155c6377ddc"
38
+ },
39
+ {
40
+ "path": "weights/sd-vae-ft-mse/config.json",
41
+ "group": "base",
42
+ "url": "https://huggingface.co/stabilityai/sd-vae-ft-mse/resolve/31f26fdeee1355a5c34592e401dd41e45d25a493/config.json",
43
+ "bytes": 547,
44
+ "sha256": "92d3dfb746fca211a2c9e019e285f8597412211728dce3c5bcf4eda0f2d62e7e"
45
+ },
46
+ {
47
+ "path": "weights/animatediff/mm_sd_v15_v2.ckpt",
48
+ "group": "base",
49
+ "url": "https://huggingface.co/guoyww/animatediff/resolve/fdfe36afa161e51b3e9c24022b0e368d59e7345e/mm_sd_v15_v2.ckpt",
50
+ "bytes": 1817888431,
51
+ "sha256": "69ed0f5fef82b110aca51bcab73b21104242bc65d6ab4b8b2a2a94d31cad1bf0"
52
+ }
53
+ ]
54
+ }
2610_variant_runtime/diffusion/configs/2409_v7_dup_14_continue_2_step655000.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ wandb_project: video-motion-graphs
2
+ exp_name: 2409_v7_dup_14_continue_2_step655000
3
+ wandb_log_dir: outputs/wandb
4
+ output_dir: outputs/diffusion
5
+ seed: 2024
6
+ base_model_path: weights/stable-diffusion-v1-5
7
+ vae_model_path: weights/sd-vae-ft-mse
8
+ image_encoder_path: weights/image_encoder
9
+ mm_path: weights/animatediff/mm_sd_v15_v2.ckpt
10
+ checkpoint_path: weights/variants/2409_v7_dup_14_continue_2_step655000/pytorch_model.bin
11
+ seed_input_channels: 5
12
+ data:
13
+ meta_paths:
14
+ - cache/Sequence_01_6/inference.json
15
+ image_size: 512
16
+ sample_frames: 14
17
+ seed_frames: 3
18
+ generated_frames: 8
19
+ validation:
20
+ guidance_scale: 3.5
21
+ denoising_steps: 20
22
+ solver:
23
+ gradient_accumulation_steps: 1
24
+ mixed_precision: fp16
25
+ enable_xformers_memory_efficient_attention: true
26
+ noise_scheduler_kwargs:
27
+ num_train_timesteps: 1000
28
+ beta_start: 0.00085
29
+ beta_end: 0.012
30
+ beta_schedule: linear
31
+ steps_offset: 1
32
+ clip_sample: false
33
+ unet_additional_kwargs:
34
+ use_inflated_groupnorm: true
35
+ unet_use_cross_frame_attention: false
36
+ unet_use_temporal_attention: false
37
+ use_motion_module: true
38
+ motion_module_resolutions:
39
+ - 1
40
+ - 2
41
+ - 4
42
+ - 8
43
+ motion_module_mid_block: true
44
+ motion_module_decoder_only: false
45
+ motion_module_type: Vanilla
46
+ motion_module_kwargs:
47
+ num_attention_heads: 8
48
+ num_transformer_block: 1
49
+ attention_block_types:
50
+ - Temporal_Self
51
+ - Temporal_Self
52
+ temporal_position_encoding: true
53
+ temporal_position_encoding_max_len: 32
54
+ temporal_attention_dim_div: 1
55
+ enable_zero_snr: true
2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_12frames_512_step30000.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ wandb_project: video-motion-graphs
2
+ exp_name: 2411_v7_dup_14_s2_12frames_512_step30000
3
+ wandb_log_dir: outputs/wandb
4
+ output_dir: outputs/diffusion
5
+ seed: 2024
6
+ base_model_path: weights/stable-diffusion-v1-5
7
+ vae_model_path: weights/sd-vae-ft-mse
8
+ image_encoder_path: weights/image_encoder
9
+ mm_path: weights/animatediff/mm_sd_v15_v2.ckpt
10
+ checkpoint_path: weights/variants/2411_v7_dup_14_s2_12frames_512_step30000/pytorch_model.bin
11
+ seed_input_channels: 5
12
+ data:
13
+ meta_paths:
14
+ - cache/Sequence_01_6/inference.json
15
+ image_size: 512
16
+ sample_frames: 14
17
+ seed_frames: 1
18
+ generated_frames: 12
19
+ validation:
20
+ guidance_scale: 3.5
21
+ denoising_steps: 20
22
+ solver:
23
+ gradient_accumulation_steps: 1
24
+ mixed_precision: fp16
25
+ enable_xformers_memory_efficient_attention: true
26
+ noise_scheduler_kwargs:
27
+ num_train_timesteps: 1000
28
+ beta_start: 0.00085
29
+ beta_end: 0.012
30
+ beta_schedule: linear
31
+ steps_offset: 1
32
+ clip_sample: false
33
+ unet_additional_kwargs:
34
+ use_inflated_groupnorm: true
35
+ unet_use_cross_frame_attention: false
36
+ unet_use_temporal_attention: false
37
+ use_motion_module: true
38
+ motion_module_resolutions:
39
+ - 1
40
+ - 2
41
+ - 4
42
+ - 8
43
+ motion_module_mid_block: true
44
+ motion_module_decoder_only: false
45
+ motion_module_type: Vanilla
46
+ motion_module_kwargs:
47
+ num_attention_heads: 8
48
+ num_transformer_block: 1
49
+ attention_block_types:
50
+ - Temporal_Self
51
+ - Temporal_Self
52
+ temporal_position_encoding: true
53
+ temporal_position_encoding_max_len: 32
54
+ temporal_attention_dim_div: 1
55
+ enable_zero_snr: true
2610_variant_runtime/diffusion/configs/2411_v7_dup_14_s2_8frames_512_step9000.yaml ADDED
@@ -0,0 +1,55 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ wandb_project: video-motion-graphs
2
+ exp_name: 2411_v7_dup_14_s2_8frames_512_step9000
3
+ wandb_log_dir: outputs/wandb
4
+ output_dir: outputs/diffusion
5
+ seed: 2024
6
+ base_model_path: weights/stable-diffusion-v1-5
7
+ vae_model_path: weights/sd-vae-ft-mse
8
+ image_encoder_path: weights/image_encoder
9
+ mm_path: weights/animatediff/mm_sd_v15_v2.ckpt
10
+ checkpoint_path: weights/variants/2411_v7_dup_14_s2_8frames_512_step9000/pytorch_model.bin
11
+ seed_input_channels: 5
12
+ data:
13
+ meta_paths:
14
+ - cache/Sequence_01_6/inference.json
15
+ image_size: 512
16
+ sample_frames: 14
17
+ seed_frames: 3
18
+ generated_frames: 8
19
+ validation:
20
+ guidance_scale: 1.0
21
+ denoising_steps: 20
22
+ solver:
23
+ gradient_accumulation_steps: 1
24
+ mixed_precision: fp16
25
+ enable_xformers_memory_efficient_attention: true
26
+ noise_scheduler_kwargs:
27
+ num_train_timesteps: 1000
28
+ beta_start: 0.00085
29
+ beta_end: 0.012
30
+ beta_schedule: linear
31
+ steps_offset: 1
32
+ clip_sample: false
33
+ unet_additional_kwargs:
34
+ use_inflated_groupnorm: true
35
+ unet_use_cross_frame_attention: false
36
+ unet_use_temporal_attention: false
37
+ use_motion_module: true
38
+ motion_module_resolutions:
39
+ - 1
40
+ - 2
41
+ - 4
42
+ - 8
43
+ motion_module_mid_block: true
44
+ motion_module_decoder_only: false
45
+ motion_module_type: Vanilla
46
+ motion_module_kwargs:
47
+ num_attention_heads: 8
48
+ num_transformer_block: 1
49
+ attention_block_types:
50
+ - Temporal_Self
51
+ - Temporal_Self
52
+ temporal_position_encoding: true
53
+ temporal_position_encoding_max_len: 32
54
+ temporal_attention_dim_div: 1
55
+ enable_zero_snr: true
2610_variant_runtime/diffusion/inference.py ADDED
@@ -0,0 +1,468 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import warnings
5
+ from pathlib import Path
6
+ import json
7
+
8
+ import wandb
9
+ from datetime import datetime
10
+ import diffusers
11
+ import numpy as np
12
+ import torch
13
+ import torch.utils.checkpoint
14
+ import transformers
15
+ from accelerate import Accelerator
16
+ from accelerate.logging import get_logger
17
+ from accelerate.utils import DistributedDataParallelKwargs
18
+ from diffusers import AutoencoderKL, DDIMScheduler
19
+ from diffusers.utils import check_min_version
20
+ from diffusers.utils.import_utils import is_xformers_available
21
+ from omegaconf import OmegaConf
22
+ from PIL import Image, ImageOps
23
+ from transformers import CLIPVisionModelWithProjection
24
+ from decord import VideoReader
25
+
26
+ from pipelines.pipeline_vfi2video_share_vae import Pose2VideoPipeline
27
+ from models.model_vfi import VFIShareVAEModel
28
+ from models.pose_guider import PoseGuider
29
+ from models.conv_in import ConvIn
30
+
31
+ from models.unet_2d_condition import UNet2DConditionModel
32
+ from models.unet_3d import UNet3DConditionModel
33
+ from models.mutual_self_attention import ReferenceAttentionControl
34
+
35
+ from utils.util import seed_everything
36
+ from utils.video_utils import concat_pil
37
+
38
+ warnings.filterwarnings("ignore")
39
+ check_min_version("0.10.0.dev0")
40
+ logger = get_logger(__name__, log_level="INFO")
41
+
42
+ def save_videos_from_pil(pil_images, path, fps=8, bitrate=None):
43
+ import av
44
+
45
+ save_fmt = Path(path).suffix
46
+ os.makedirs(os.path.dirname(path), exist_ok=True)
47
+ width, height = pil_images[0].size
48
+
49
+ if save_fmt == ".mp4":
50
+ codec = "libx264"
51
+ container = av.open(path, "w")
52
+ stream = container.add_stream(codec, rate=fps, )
53
+
54
+ stream.width = width
55
+ stream.height = height
56
+ if bitrate is not None:
57
+ stream.bit_rate = bitrate
58
+
59
+ for pil_image in pil_images:
60
+ # pil_image = Image.fromarray(image_arr).convert("RGB")
61
+ av_frame = av.VideoFrame.from_image(pil_image)
62
+ container.mux(stream.encode(av_frame))
63
+ container.mux(stream.encode())
64
+ container.close()
65
+
66
+ elif save_fmt == ".gif":
67
+ pil_images[0].save(
68
+ fp=path,
69
+ format="GIF",
70
+ append_images=pil_images[1:],
71
+ save_all=True,
72
+ duration=(1 / fps * 1000),
73
+ loop=0,
74
+ )
75
+ else:
76
+ raise ValueError("Unsupported file type. Use .mp4 or .gif.")
77
+
78
+
79
+ def pad_to_square(image, size):
80
+ width, height = image.size
81
+ ratio = size / max(width, height)
82
+ width, height = int(width * ratio), int(height * ratio)
83
+ image = image.resize((width, height))
84
+ left, top = (size - width) // 2, (size - height) // 2
85
+ return ImageOps.expand(image, (left, top, size - width - left, size - height - top), fill=0)
86
+
87
+
88
+ def log_validation(
89
+ cfg,
90
+ vae,
91
+ image_enc,
92
+ model,
93
+ scheduler,
94
+ accelerator,
95
+ width,
96
+ height,
97
+ seed=42,
98
+ dtype=torch.float32,
99
+ ):
100
+ logger.info("Running validation ...")
101
+ unwrap_model = accelerator.unwrap_model(model).eval()
102
+ denoising_unet = unwrap_model.denoising_unet
103
+ reference_unet = unwrap_model.reference_unet
104
+ pose_guider = unwrap_model.pose_guider
105
+ seed_guider = unwrap_model.seed_guider
106
+ generator = torch.manual_seed(seed)
107
+ vae = vae.to(dtype=dtype)
108
+ image_enc = image_enc.to(dtype=dtype)
109
+
110
+ pipeline = Pose2VideoPipeline(
111
+ vae=vae,
112
+ image_encoder=image_enc,
113
+ reference_unet=reference_unet,
114
+ denoising_unet=denoising_unet,
115
+ pose_guider=pose_guider,
116
+ seed_guider=seed_guider,
117
+ scheduler=scheduler,
118
+ )
119
+ pipeline = pipeline.to(accelerator.device)
120
+
121
+ vid_meta = []
122
+ for data_meta_path in cfg.data.meta_paths:
123
+ vid_meta.extend(json.load(open(data_meta_path, "r")))
124
+ all_test_cases = [item for item in vid_meta if item.get("mode") == "test"]
125
+ current_device_id = accelerator.process_index
126
+ pil_images = []
127
+
128
+ # if cfg.wandb_project == "debug":
129
+ # all_test_cases = all_test_cases[:2] + all_test_cases[-2:]
130
+ # else:
131
+ # all_test_cases = all_test_cases[:8] + all_test_cases[-8:]
132
+
133
+ with torch.no_grad():
134
+ for idx, test_case in enumerate(all_test_cases):
135
+ # if idx > 1: break
136
+ if idx % accelerator.num_processes == current_device_id:
137
+ video_path = test_case["video_path"]
138
+ kps_pth = test_case["kps_path"]
139
+ rgb_video = VideoReader(video_path)
140
+ kps_video = VideoReader(kps_pth)
141
+
142
+ # if idx >= len(all_test_cases) // 2:
143
+ # # for dance video we pick from 8s
144
+ # ref_id = 120
145
+ # else:
146
+ ref_id = test_case.get("start_idx", 3 - cfg.data.seed_frames) + cfg.data.seed_frames
147
+
148
+ start_g = ref_id - cfg.data.seed_frames
149
+ end_s = ref_id + cfg.data.generated_frames
150
+ end_g = ref_id + cfg.data.generated_frames + cfg.data.seed_frames
151
+
152
+ ref_img = rgb_video[ref_id-1]
153
+ ref_img_pil = Image.fromarray(ref_img.asnumpy())
154
+ w, h = ref_img_pil.size
155
+
156
+ tgt_vidpil_lst = []
157
+ tgt_guid_vid_list = []
158
+ pose_guid_vid_list = []
159
+ for index in range(start_g, ref_id):
160
+ img = rgb_video[index]
161
+ pil_img = Image.fromarray(img.asnumpy())
162
+ tgt_guid_pil = pil_img.copy()
163
+ pose_guid_pil = Image.new(pil_img.mode, pil_img.size, 0)
164
+ pose_guid_vid_list.append(pose_guid_pil)
165
+ tgt_vidpil_lst.append(pil_img)
166
+ tgt_guid_vid_list.append(tgt_guid_pil)
167
+
168
+ for index in range(ref_id, end_s):
169
+ if index >= ref_id + cfg.data.generated_frames // 2 :
170
+ img_dup = rgb_video[end_s]
171
+ pil_img_dup = Image.fromarray(img_dup.asnumpy())
172
+ tgt_guid_vid_list.append(pil_img_dup)
173
+ else:
174
+ img_dup = rgb_video[ref_id-1]
175
+ pil_img_dup = Image.fromarray(img_dup.asnumpy())
176
+ tgt_guid_vid_list.append(pil_img_dup)
177
+ pose_guid_pil = Image.fromarray(kps_video[index].asnumpy())
178
+ pose_guid_vid_list.append(pose_guid_pil)
179
+
180
+ img = rgb_video[index]
181
+ pil_img = Image.fromarray(img.asnumpy())
182
+ tgt_vidpil_lst.append(pil_img)
183
+
184
+ for index in range(end_s, end_g):
185
+ img = rgb_video[index]
186
+ pil_img = Image.fromarray(img.asnumpy())
187
+ tgt_guid_pil = pil_img.copy()
188
+ pose_guid_pil = Image.new(pil_img.mode, pil_img.size, 0)
189
+ pose_guid_vid_list.append(pose_guid_pil)
190
+ tgt_vidpil_lst.append(pil_img)
191
+ tgt_guid_vid_list.append(tgt_guid_pil)
192
+
193
+ seed_mask = None
194
+ if cfg.get("seed_input_channels", 4) == 5:
195
+ w = h = cfg.data.image_size
196
+ ref_img_pil = pad_to_square(ref_img_pil, w)
197
+ tgt_guid_vid_list = [pad_to_square(image, w) for image in tgt_guid_vid_list]
198
+ pose_guid_vid_list = [pad_to_square(image, w) for image in pose_guid_vid_list]
199
+ tgt_vidpil_lst = [pad_to_square(image, w) for image in tgt_vidpil_lst]
200
+ seed_mask = torch.zeros(
201
+ (1, 1, cfg.data.sample_frames, h // 8, w // 8), device=accelerator.device
202
+ )
203
+ seed_mask[:, :, :cfg.data.seed_frames] = 1
204
+ seed_mask[:, :, -cfg.data.seed_frames:] = 1
205
+
206
+ ori_w = w
207
+ ori_h = h
208
+
209
+ # generator = torch.manual_seed(seed)
210
+ if cfg.get("seed_input_channels", 4) == 5:
211
+ generator = torch.Generator(device=accelerator.device).manual_seed(seed)
212
+ else:
213
+ generator = torch.manual_seed(seed)
214
+ video_tensor = pipeline(
215
+ ref_img_pil,
216
+ pose_guid_vid_list,
217
+ tgt_guid_vid_list,
218
+ w,
219
+ h,
220
+ cfg.data.sample_frames,
221
+ cfg.validation.denoising_steps,
222
+ cfg.validation.guidance_scale,
223
+ generator=generator,
224
+ seed_mask=seed_mask,
225
+ ).videos
226
+ video_tensor = video_tensor[0, ...].permute(1, 2, 3, 0).cpu().numpy()
227
+
228
+ video_pil_lst = []
229
+ video_pil_lst_original_size = []
230
+ gap_w = (w - ori_w) // 2
231
+ gap_h = (h - ori_h) // 2
232
+ for frame_idx, image_tensor in enumerate(video_tensor):
233
+ result_img_pil = Image.fromarray((image_tensor * 255).astype(np.uint8))
234
+ result_img_pil_2 = result_img_pil.copy()
235
+ result_img_np = np.array(result_img_pil_2)
236
+ result_img_np_ori = result_img_np[gap_h:gap_h+ori_h, gap_w:gap_w+ori_w]
237
+ result_img_pil_ori = Image.fromarray(result_img_np_ori)
238
+ # print(result_img_pil_ori.size)
239
+ if frame_idx >= cfg.data.seed_frames and frame_idx < cfg.data.seed_frames+cfg.data.generated_frames:
240
+ result_pil_lst = [pose_guid_vid_list[frame_idx], tgt_guid_vid_list[frame_idx], result_img_pil, tgt_vidpil_lst[frame_idx], result_img_pil]
241
+ else:
242
+ result_pil_lst = [pose_guid_vid_list[frame_idx], tgt_guid_vid_list[frame_idx], result_img_pil, tgt_vidpil_lst[frame_idx], tgt_vidpil_lst[frame_idx]]
243
+ concated_pil = concat_pil(result_pil_lst)
244
+ video_pil_lst_original_size.append(result_img_pil_ori)
245
+ video_pil_lst.append(concated_pil)
246
+ pil_images.append({"name": f"{test_case['video_path'][-14:-4]}", "video": video_pil_lst})
247
+ # clip = ImageSequenceClip(video_pil_lst_original_size, fps=24)
248
+ # clip.write_videofile(video_path.replace("_rgb_", "_blend_res_"), codec='libx264', bitrate="4000k")
249
+ output_path = video_path.replace("_rgb_", "_blend_res_")
250
+ if cfg.get("seed_input_channels", 4) == 5 or output_path == video_path:
251
+ output_path = str(Path(cfg.output_dir) / cfg.exp_name / f"{Path(video_path).stem}_blend_res.mp4")
252
+ save_videos_from_pil(video_pil_lst_original_size, output_path, bitrate=4000000)
253
+
254
+ unwrap_model.train()
255
+ vae = vae.to(dtype=torch.float16)
256
+ image_enc = image_enc.to(dtype=torch.float16)
257
+
258
+ del pipeline
259
+ torch.cuda.empty_cache()
260
+ return pil_images
261
+
262
+ def main(cfg):
263
+ os.environ.setdefault("WANDB_MODE", "disabled")
264
+ kwargs = DistributedDataParallelKwargs(find_unused_parameters=True)
265
+ accelerator = Accelerator(
266
+ gradient_accumulation_steps=cfg.solver.gradient_accumulation_steps,
267
+ mixed_precision=cfg.solver.mixed_precision,
268
+ log_with="wandb",
269
+ project_dir=cfg.wandb_log_dir,
270
+ kwargs_handlers=[kwargs],
271
+ )
272
+
273
+ logging.basicConfig(
274
+ format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
275
+ datefmt="%m/%d/%Y %H:%M:%S",
276
+ level=logging.INFO,
277
+ )
278
+ logger.info(accelerator.state, main_process_only=True)
279
+
280
+ if accelerator.is_local_main_process:
281
+ transformers.utils.logging.set_verbosity_warning()
282
+ diffusers.utils.logging.set_verbosity_info()
283
+ else:
284
+ transformers.utils.logging.set_verbosity_error()
285
+ diffusers.utils.logging.set_verbosity_error()
286
+
287
+ if cfg.seed is not None:
288
+ seed_everything(cfg.seed)
289
+
290
+ sched_kwargs = OmegaConf.to_container(cfg.noise_scheduler_kwargs)
291
+ if cfg.enable_zero_snr:
292
+ sched_kwargs.update(
293
+ rescale_betas_zero_snr=True,
294
+ timestep_spacing="trailing",
295
+ prediction_type="v_prediction",
296
+ )
297
+ val_noise_scheduler = DDIMScheduler(**sched_kwargs)
298
+ sched_kwargs.update({"beta_schedule": "scaled_linear"})
299
+
300
+ vae = AutoencoderKL.from_pretrained(cfg.vae_model_path).to("cuda", dtype=torch.float32)
301
+ reference_unet = UNet2DConditionModel.from_pretrained(
302
+ cfg.base_model_path,
303
+ subfolder="unet",
304
+ ).to(device="cuda")
305
+ denoising_unet = UNet3DConditionModel.from_pretrained_2d(
306
+ cfg.base_model_path,
307
+ cfg.mm_path,
308
+ subfolder="unet",
309
+ unet_additional_kwargs=OmegaConf.to_container(
310
+ cfg.unet_additional_kwargs
311
+ ),
312
+ ).to(device="cuda")
313
+ image_enc = CLIPVisionModelWithProjection.from_pretrained(
314
+ cfg.image_encoder_path,
315
+ ).to(dtype=torch.float32, device="cuda")
316
+ pose_guider = PoseGuider(
317
+ conditioning_embedding_channels=320, block_out_channels=(16, 32, 96, 256),
318
+ conditioning_channels=3,
319
+ ).to(device="cuda")
320
+ seed_guider = ConvIn(
321
+ conditioning_embedding_channels=320, conditioning_channels=cfg.get("seed_input_channels", 4)
322
+ )
323
+
324
+ vae.requires_grad_(False)
325
+ image_enc.requires_grad_(False)
326
+ denoising_unet.requires_grad_(False)
327
+ pose_guider.requires_grad_(False)
328
+ seed_guider.requires_grad_(False)
329
+
330
+ reference_control_writer = ReferenceAttentionControl(
331
+ reference_unet,
332
+ do_classifier_free_guidance=False,
333
+ mode="write",
334
+ fusion_blocks="full",
335
+ )
336
+ reference_control_reader = ReferenceAttentionControl(
337
+ denoising_unet,
338
+ do_classifier_free_guidance=False,
339
+ mode="read",
340
+ fusion_blocks="full",
341
+ )
342
+
343
+ model = VFIShareVAEModel(
344
+ reference_unet,
345
+ denoising_unet,
346
+ seed_guider,
347
+ pose_guider,
348
+ reference_control_writer,
349
+ reference_control_reader,
350
+ )
351
+
352
+ checkpoint_path = cfg.get("checkpoint_path") or os.path.join(
353
+ cfg.stage1_ckpt_dir, f"checkpoint-{cfg.stage1_ckpt_step}", "pytorch_model.bin"
354
+ )
355
+ old_ckpt = torch.load(checkpoint_path, map_location="cpu", weights_only=True)
356
+ load_result = model.load_state_dict(old_ckpt, strict=True)
357
+ checkpoint_info = {
358
+ "path": str(checkpoint_path), "strict": True,
359
+ "missing_keys": load_result.missing_keys, "unexpected_keys": load_result.unexpected_keys,
360
+ "seed_guider_weight_shape": list(old_ckpt["seed_guider.conv_in.weight"].shape),
361
+ }
362
+ del old_ckpt
363
+ logger.info(f"Strictly loaded checkpoint {checkpoint_path}")
364
+
365
+ model = accelerator.prepare(
366
+ model
367
+ )
368
+
369
+ if cfg.solver.enable_xformers_memory_efficient_attention:
370
+ if is_xformers_available():
371
+ reference_unet.enable_xformers_memory_efficient_attention()
372
+ denoising_unet.enable_xformers_memory_efficient_attention()
373
+ else:
374
+ raise ValueError(
375
+ "xformers is not available. Make sure it is installed correctly"
376
+ )
377
+
378
+ if accelerator.is_main_process:
379
+ run_time = datetime.now().strftime("%Y%m%d-%H%M")
380
+ accelerator.init_trackers(
381
+ cfg.wandb_project,
382
+ init_kwargs={"wandb": {"name": cfg.exp_name + "_" + run_time, "dir":cfg.wandb_log_dir}},
383
+ )
384
+ config_dict = OmegaConf.to_container(cfg)
385
+ wandb.config.update(config_dict)
386
+
387
+ accelerator.wait_for_everyone()
388
+ sample_dicts = log_validation(
389
+ cfg=cfg,
390
+ vae=vae,
391
+ image_enc=image_enc,
392
+ model=model,
393
+ scheduler=val_noise_scheduler,
394
+ accelerator=accelerator,
395
+ width=cfg.data.image_size,
396
+ height=cfg.data.image_size,
397
+ seed=cfg.seed,
398
+ )
399
+ global_step = 0
400
+ image_save_dir = f"{cfg.wandb_log_dir}/{cfg.exp_name}/{global_step:06d}/"
401
+ if not os.path.exists(image_save_dir):
402
+ os.makedirs(image_save_dir, exist_ok=True)
403
+
404
+ for sample_id, sample_dict in enumerate(sample_dicts):
405
+ sample_name = sample_dict["name"]
406
+ img = sample_dict["video"]
407
+ if img[0].size[0] >= img[0].size[1]:
408
+ img_path = f"{image_save_dir}{global_step:06d}-{sample_name}-higher.mp4"
409
+ else:
410
+ img_path = f"{image_save_dir}{global_step:06d}-{sample_name}-wider.mp4"
411
+ save_videos_from_pil(img, img_path, fps=6)
412
+
413
+ accelerator.wait_for_everyone()
414
+ if accelerator.is_main_process:
415
+ images_to_log_higher = []
416
+ images_to_log_wider = []
417
+ for img_path in os.listdir(image_save_dir):
418
+ if img_path.endswith("-higher.mp4"):
419
+ wandb_img = wandb.Video(image_save_dir+img_path, caption=f"{global_step:06d}-{img_path}")
420
+ images_to_log_higher.append(wandb_img)
421
+ elif img_path.endswith("-wider.mp4"):
422
+ wandb_img = wandb.Video(image_save_dir+img_path, caption=f"{global_step:06d}-{img_path}")
423
+ images_to_log_wider.append(wandb_img)
424
+ wandb.log({
425
+ "images_higher": images_to_log_higher,
426
+ "images_wider": images_to_log_wider,
427
+ "iteration": global_step
428
+ })
429
+ accelerator.wait_for_everyone()
430
+ accelerator.end_training()
431
+ if accelerator.is_main_process:
432
+ receipt_dir = Path(cfg.output_dir) / cfg.exp_name
433
+ receipt_dir.mkdir(parents=True, exist_ok=True)
434
+ receipt = {
435
+ "status": "complete", "checkpoint": checkpoint_info,
436
+ "seed": cfg.seed, "data": OmegaConf.to_container(cfg.data),
437
+ "validation": OmegaConf.to_container(cfg.validation),
438
+ "vae_type": "AutoencoderKL", "vae_model_path": cfg.vae_model_path,
439
+ "input_jsons": list(cfg.data.meta_paths), "samples": len(sample_dicts),
440
+ }
441
+ (receipt_dir / "inference_receipt.json").write_text(json.dumps(receipt, indent=2) + "\n")
442
+
443
+ if __name__ == "__main__":
444
+ parser = argparse.ArgumentParser()
445
+ parser.add_argument("--config", type=str, default="diffusion/configs/inference.yaml")
446
+ parser.add_argument("--json", type=str, default="")
447
+ parser.add_argument("--checkpoint", type=str)
448
+ parser.add_argument("--output-dir", type=str)
449
+ parser.add_argument("--guidance-scale", type=float)
450
+ args = parser.parse_args()
451
+
452
+ if args.config[-5:] == ".yaml":
453
+ config = OmegaConf.load(args.config)
454
+ else:
455
+ raise ValueError("Do not support this format config file")
456
+
457
+ if args.json:
458
+ config.data.meta_paths = [args.json]
459
+
460
+ if args.checkpoint:
461
+ config.checkpoint_path = args.checkpoint
462
+ if args.output_dir:
463
+ config.output_dir = args.output_dir
464
+ config.wandb_log_dir = str(Path(args.output_dir) / "logs")
465
+ if args.guidance_scale is not None:
466
+ config.validation.guidance_scale = args.guidance_scale
467
+
468
+ main(config)
2610_variant_runtime/diffusion/models/attention.py ADDED
@@ -0,0 +1,526 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention.py
2
+
3
+ from typing import Any, Dict, Optional
4
+
5
+ import torch
6
+ from diffusers.models.attention import AdaLayerNorm, Attention, FeedForward
7
+ from diffusers.models.embeddings import SinusoidalPositionalEmbedding
8
+ from einops import rearrange
9
+
10
+ from torch import nn
11
+ import math
12
+ # import torch.onnx.operators
13
+ # from fairseq import utils
14
+
15
+ # class ScaledSinusoidalPositionalEmbedding(SinusoidalPositionalEmbedding):
16
+ # def __init__(self, embedding_dim, padding_idx, init_size=1024, base_fps=30):
17
+ # super().__init__(embedding_dim, padding_idx, init_size)
18
+ # self.base_fps = base_fps
19
+
20
+ # @staticmethod
21
+ # def get_embedding(
22
+ # num_embeddings: int,
23
+ # embedding_dim: int,
24
+ # padding_idx: Optional[int] = None,
25
+ # current_fps: Optional[float] = None,
26
+ # base_fps: float = 30.0
27
+ # ):
28
+ # if current_fps is None:
29
+ # scale_factor = 1.0
30
+ # else:
31
+ # scale_factor = current_fps / base_fps
32
+
33
+ # half_dim = embedding_dim // 2
34
+ # emb = math.log(10000) / (half_dim - 1)
35
+ # emb = torch.exp(torch.arange(half_dim, dtype=torch.float) * -emb)
36
+
37
+ # emb = torch.arange(num_embeddings, dtype=torch.float).unsqueeze(1) * emb.unsqueeze(0)
38
+ # emb = torch.cat([torch.sin(emb * scale_factor), torch.cos(emb * scale_factor)], dim=1)
39
+
40
+ # if embedding_dim % 2 == 1:
41
+ # emb = torch.cat([emb, torch.zeros(num_embeddings, 1)], dim=1)
42
+
43
+ # if padding_idx is not None:
44
+ # emb[padding_idx, :] = 0
45
+
46
+ # return emb
47
+
48
+ # def forward(
49
+ # self,
50
+ # input,
51
+ # incremental_state: Optional[Any] = None,
52
+ # timestep: Optional[Tensor] = None,
53
+ # positions: Optional[Any] = None,
54
+ # ):
55
+ # """Input is expected to be of size [bsz x seqlen]."""
56
+ # bspair = torch.onnx.operators.shape_as_tensor(input)
57
+ # bsz, seq_len = bspair[0], bspair[1]
58
+ # max_pos = self.padding_idx + 1 + seq_len
59
+ # self.weights = self.get_embedding(
60
+ # max_pos, self.embedding_dim, self.padding_idx, current_fps = current_fps,
61
+ # )
62
+ # self.weights = self.weights.to(self._float_tensor)
63
+
64
+ # if incremental_state is not None:
65
+ # # positions is the same for every token when decoding a single step
66
+ # pos = timestep.view(-1)[0] + 1 if timestep is not None else seq_len
67
+ # if self.onnx_trace:
68
+ # return (
69
+ # self.weights.index_select(index=self.padding_idx + pos, dim=0)
70
+ # .unsqueeze(1)
71
+ # .repeat(bsz, 1, 1)
72
+ # )
73
+ # return self.weights[self.padding_idx + pos, :].expand(bsz, 1, -1)
74
+
75
+ # positions = utils.make_positions(
76
+ # input, self.padding_idx, onnx_trace=self.onnx_trace
77
+ # )
78
+ # if self.onnx_trace:
79
+ # flat_embeddings = self.weights.detach().index_select(0, positions.view(-1))
80
+ # embedding_shape = torch.cat(
81
+ # (bsz.view(1), seq_len.view(1), torch.tensor([-1], dtype=torch.long))
82
+ # )
83
+ # embeddings = torch.onnx.operators.reshape_from_tensor_shape(
84
+ # flat_embeddings, embedding_shape
85
+ # )
86
+ # return embeddings
87
+ # return (
88
+ # self.weights.index_select(0, positions.view(-1))
89
+ # .view(bsz, seq_len, -1)
90
+ # .detach()
91
+ # )
92
+
93
+ class BasicTransformerBlock(nn.Module):
94
+ r"""
95
+ A basic Transformer block.
96
+
97
+ Parameters:
98
+ dim (`int`): The number of channels in the input and output.
99
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
100
+ attention_head_dim (`int`): The number of channels in each head.
101
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
102
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
103
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
104
+ num_embeds_ada_norm (:
105
+ obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
106
+ attention_bias (:
107
+ obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
108
+ only_cross_attention (`bool`, *optional*):
109
+ Whether to use only cross-attention layers. In this case two cross attention layers are used.
110
+ double_self_attention (`bool`, *optional*):
111
+ Whether to use two self-attention layers. In this case no cross attention layers are used.
112
+ upcast_attention (`bool`, *optional*):
113
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
114
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
115
+ Whether to use learnable elementwise affine parameters for normalization.
116
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
117
+ The normalization layer to use. Can be `"layer_norm"`, `"ada_norm"` or `"ada_norm_zero"`.
118
+ final_dropout (`bool` *optional*, defaults to False):
119
+ Whether to apply a final dropout after the last feed-forward layer.
120
+ attention_type (`str`, *optional*, defaults to `"default"`):
121
+ The type of attention to use. Can be `"default"` or `"gated"` or `"gated-text-image"`.
122
+ positional_embeddings (`str`, *optional*, defaults to `None`):
123
+ The type of positional embeddings to apply to.
124
+ num_positional_embeddings (`int`, *optional*, defaults to `None`):
125
+ The maximum number of positional embeddings to apply.
126
+ """
127
+
128
+ def __init__(
129
+ self,
130
+ dim: int,
131
+ num_attention_heads: int,
132
+ attention_head_dim: int,
133
+ dropout=0.0,
134
+ cross_attention_dim: Optional[int] = None,
135
+ activation_fn: str = "geglu",
136
+ num_embeds_ada_norm: Optional[int] = None,
137
+ attention_bias: bool = False,
138
+ only_cross_attention: bool = False,
139
+ double_self_attention: bool = False,
140
+ upcast_attention: bool = False,
141
+ norm_elementwise_affine: bool = True,
142
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single'
143
+ norm_eps: float = 1e-5,
144
+ final_dropout: bool = False,
145
+ attention_type: str = "default",
146
+ positional_embeddings: Optional[str] = None,
147
+ num_positional_embeddings: Optional[int] = None,
148
+ ):
149
+ super().__init__()
150
+ self.only_cross_attention = only_cross_attention
151
+
152
+ self.use_ada_layer_norm_zero = (
153
+ num_embeds_ada_norm is not None
154
+ ) and norm_type == "ada_norm_zero"
155
+ self.use_ada_layer_norm = (
156
+ num_embeds_ada_norm is not None
157
+ ) and norm_type == "ada_norm"
158
+ self.use_ada_layer_norm_single = norm_type == "ada_norm_single"
159
+ self.use_layer_norm = norm_type == "layer_norm"
160
+
161
+ if norm_type in ("ada_norm", "ada_norm_zero") and num_embeds_ada_norm is None:
162
+ raise ValueError(
163
+ f"`norm_type` is set to {norm_type}, but `num_embeds_ada_norm` is not defined. Please make sure to"
164
+ f" define `num_embeds_ada_norm` if setting `norm_type` to {norm_type}."
165
+ )
166
+
167
+ if positional_embeddings and (num_positional_embeddings is None):
168
+ raise ValueError(
169
+ "If `positional_embedding` type is defined, `num_positition_embeddings` must also be defined."
170
+ )
171
+
172
+ if positional_embeddings == "sinusoidal":
173
+ self.pos_embed = SinusoidalPositionalEmbedding(
174
+ dim, max_seq_length=num_positional_embeddings
175
+ )
176
+ else:
177
+ self.pos_embed = None
178
+
179
+ # print(self.pos_embed, positional_embeddings)
180
+
181
+ # Define 3 blocks. Each block has its own normalization layer.
182
+ # 1. Self-Attn
183
+ if self.use_ada_layer_norm:
184
+ self.norm1 = AdaLayerNorm(dim, num_embeds_ada_norm)
185
+ elif self.use_ada_layer_norm_zero:
186
+ self.norm1 = AdaLayerNormZero(dim, num_embeds_ada_norm)
187
+ else:
188
+ self.norm1 = nn.LayerNorm(
189
+ dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps
190
+ )
191
+
192
+ self.attn1 = Attention(
193
+ query_dim=dim,
194
+ heads=num_attention_heads,
195
+ dim_head=attention_head_dim,
196
+ dropout=dropout,
197
+ bias=attention_bias,
198
+ cross_attention_dim=cross_attention_dim if only_cross_attention else None,
199
+ upcast_attention=upcast_attention,
200
+ )
201
+
202
+ # 2. Cross-Attn
203
+ if cross_attention_dim is not None or double_self_attention:
204
+ # We currently only use AdaLayerNormZero for self attention where there will only be one attention block.
205
+ # I.e. the number of returned modulation chunks from AdaLayerZero would not make sense if returned during
206
+ # the second cross attention block.
207
+ self.norm2 = (
208
+ AdaLayerNorm(dim, num_embeds_ada_norm)
209
+ if self.use_ada_layer_norm
210
+ else nn.LayerNorm(
211
+ dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps
212
+ )
213
+ )
214
+ self.attn2 = Attention(
215
+ query_dim=dim,
216
+ cross_attention_dim=(
217
+ cross_attention_dim if not double_self_attention else None
218
+ ),
219
+ heads=num_attention_heads,
220
+ dim_head=attention_head_dim,
221
+ dropout=dropout,
222
+ bias=attention_bias,
223
+ upcast_attention=upcast_attention,
224
+ ) # is self-attn if encoder_hidden_states is none
225
+ else:
226
+ self.norm2 = None
227
+ self.attn2 = None
228
+
229
+ # 3. Feed-forward
230
+ if not self.use_ada_layer_norm_single:
231
+ self.norm3 = nn.LayerNorm(
232
+ dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps
233
+ )
234
+
235
+ self.ff = FeedForward(
236
+ dim,
237
+ dropout=dropout,
238
+ activation_fn=activation_fn,
239
+ final_dropout=final_dropout,
240
+ )
241
+
242
+ # 4. Fuser
243
+ if attention_type == "gated" or attention_type == "gated-text-image":
244
+ self.fuser = GatedSelfAttentionDense(
245
+ dim, cross_attention_dim, num_attention_heads, attention_head_dim
246
+ )
247
+
248
+ # 5. Scale-shift for PixArt-Alpha.
249
+ if self.use_ada_layer_norm_single:
250
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
251
+
252
+ # let chunk size default to None
253
+ self._chunk_size = None
254
+ self._chunk_dim = 0
255
+
256
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
257
+ # Sets chunk feed-forward
258
+ self._chunk_size = chunk_size
259
+ self._chunk_dim = dim
260
+
261
+ def forward(
262
+ self,
263
+ hidden_states: torch.FloatTensor,
264
+ attention_mask: Optional[torch.FloatTensor] = None,
265
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
266
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
267
+ timestep: Optional[torch.LongTensor] = None,
268
+ cross_attention_kwargs: Dict[str, Any] = None,
269
+ class_labels: Optional[torch.LongTensor] = None,
270
+ ) -> torch.FloatTensor:
271
+ # Notice that normalization is always applied before the real computation in the following blocks.
272
+ # 0. Self-Attention
273
+ batch_size = hidden_states.shape[0]
274
+
275
+ if self.use_ada_layer_norm:
276
+ norm_hidden_states = self.norm1(hidden_states, timestep)
277
+ elif self.use_ada_layer_norm_zero:
278
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
279
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
280
+ )
281
+ elif self.use_layer_norm:
282
+ norm_hidden_states = self.norm1(hidden_states)
283
+ elif self.use_ada_layer_norm_single:
284
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
285
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
286
+ ).chunk(6, dim=1)
287
+ norm_hidden_states = self.norm1(hidden_states)
288
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
289
+ norm_hidden_states = norm_hidden_states.squeeze(1)
290
+ else:
291
+ raise ValueError("Incorrect norm used")
292
+
293
+ if self.pos_embed is not None:
294
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
295
+
296
+ # 1. Retrieve lora scale.
297
+ lora_scale = (
298
+ cross_attention_kwargs.get("scale", 1.0)
299
+ if cross_attention_kwargs is not None
300
+ else 1.0
301
+ )
302
+
303
+ # 2. Prepare GLIGEN inputs
304
+ cross_attention_kwargs = (
305
+ cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
306
+ )
307
+ gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
308
+
309
+ attn_output = self.attn1(
310
+ norm_hidden_states,
311
+ encoder_hidden_states=(
312
+ encoder_hidden_states if self.only_cross_attention else None
313
+ ),
314
+ attention_mask=attention_mask,
315
+ **cross_attention_kwargs,
316
+ )
317
+ if self.use_ada_layer_norm_zero:
318
+ attn_output = gate_msa.unsqueeze(1) * attn_output
319
+ elif self.use_ada_layer_norm_single:
320
+ attn_output = gate_msa * attn_output
321
+
322
+ hidden_states = attn_output + hidden_states
323
+ if hidden_states.ndim == 4:
324
+ hidden_states = hidden_states.squeeze(1)
325
+
326
+ # 2.5 GLIGEN Control
327
+ if gligen_kwargs is not None:
328
+ hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
329
+
330
+ # 3. Cross-Attention
331
+ if self.attn2 is not None:
332
+ if self.use_ada_layer_norm:
333
+ norm_hidden_states = self.norm2(hidden_states, timestep)
334
+ elif self.use_ada_layer_norm_zero or self.use_layer_norm:
335
+ norm_hidden_states = self.norm2(hidden_states)
336
+ elif self.use_ada_layer_norm_single:
337
+ # For PixArt norm2 isn't applied here:
338
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
339
+ norm_hidden_states = hidden_states
340
+ else:
341
+ raise ValueError("Incorrect norm")
342
+
343
+ if self.pos_embed is not None and self.use_ada_layer_norm_single is False:
344
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
345
+
346
+ attn_output = self.attn2(
347
+ norm_hidden_states,
348
+ encoder_hidden_states=encoder_hidden_states,
349
+ attention_mask=encoder_attention_mask,
350
+ **cross_attention_kwargs,
351
+ )
352
+ hidden_states = attn_output + hidden_states
353
+
354
+ # 4. Feed-forward
355
+ if not self.use_ada_layer_norm_single:
356
+ norm_hidden_states = self.norm3(hidden_states)
357
+
358
+ if self.use_ada_layer_norm_zero:
359
+ norm_hidden_states = (
360
+ norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
361
+ )
362
+
363
+ if self.use_ada_layer_norm_single:
364
+ norm_hidden_states = self.norm2(hidden_states)
365
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
366
+
367
+ ff_output = self.ff(norm_hidden_states, scale=lora_scale)
368
+
369
+ if self.use_ada_layer_norm_zero:
370
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
371
+ elif self.use_ada_layer_norm_single:
372
+ ff_output = gate_mlp * ff_output
373
+
374
+ hidden_states = ff_output + hidden_states
375
+ if hidden_states.ndim == 4:
376
+ hidden_states = hidden_states.squeeze(1)
377
+
378
+ return hidden_states
379
+
380
+
381
+ class TemporalBasicTransformerBlock(nn.Module):
382
+ def __init__(
383
+ self,
384
+ dim: int,
385
+ num_attention_heads: int,
386
+ attention_head_dim: int,
387
+ dropout=0.0,
388
+ cross_attention_dim: Optional[int] = None,
389
+ activation_fn: str = "geglu",
390
+ num_embeds_ada_norm: Optional[int] = None,
391
+ attention_bias: bool = False,
392
+ only_cross_attention: bool = False,
393
+ upcast_attention: bool = False,
394
+ unet_use_cross_frame_attention=None,
395
+ unet_use_temporal_attention=None,
396
+ ):
397
+ super().__init__()
398
+ self.only_cross_attention = only_cross_attention
399
+ self.use_ada_layer_norm = num_embeds_ada_norm is not None
400
+ self.unet_use_cross_frame_attention = unet_use_cross_frame_attention
401
+ self.unet_use_temporal_attention = unet_use_temporal_attention
402
+
403
+ # SC-Attn
404
+ self.attn1 = Attention(
405
+ query_dim=dim,
406
+ heads=num_attention_heads,
407
+ dim_head=attention_head_dim,
408
+ dropout=dropout,
409
+ bias=attention_bias,
410
+ upcast_attention=upcast_attention,
411
+ )
412
+ self.norm1 = (
413
+ AdaLayerNorm(dim, num_embeds_ada_norm)
414
+ if self.use_ada_layer_norm
415
+ else nn.LayerNorm(dim)
416
+ )
417
+
418
+ # Cross-Attn
419
+ if cross_attention_dim is not None:
420
+ self.attn2 = Attention(
421
+ query_dim=dim,
422
+ cross_attention_dim=cross_attention_dim,
423
+ heads=num_attention_heads,
424
+ dim_head=attention_head_dim,
425
+ dropout=dropout,
426
+ bias=attention_bias,
427
+ upcast_attention=upcast_attention,
428
+ )
429
+ else:
430
+ self.attn2 = None
431
+
432
+ if cross_attention_dim is not None:
433
+ self.norm2 = (
434
+ AdaLayerNorm(dim, num_embeds_ada_norm)
435
+ if self.use_ada_layer_norm
436
+ else nn.LayerNorm(dim)
437
+ )
438
+ else:
439
+ self.norm2 = None
440
+
441
+ # Feed-forward
442
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
443
+ self.norm3 = nn.LayerNorm(dim)
444
+ self.use_ada_layer_norm_zero = False
445
+
446
+ # Temp-Attn
447
+ assert unet_use_temporal_attention is not None
448
+ if unet_use_temporal_attention:
449
+ self.attn_temp = Attention(
450
+ query_dim=dim,
451
+ heads=num_attention_heads,
452
+ dim_head=attention_head_dim,
453
+ dropout=dropout,
454
+ bias=attention_bias,
455
+ upcast_attention=upcast_attention,
456
+ )
457
+ nn.init.zeros_(self.attn_temp.to_out[0].weight.data)
458
+ self.norm_temp = (
459
+ AdaLayerNorm(dim, num_embeds_ada_norm)
460
+ if self.use_ada_layer_norm
461
+ else nn.LayerNorm(dim)
462
+ )
463
+
464
+ def forward(
465
+ self,
466
+ hidden_states,
467
+ encoder_hidden_states=None,
468
+ timestep=None,
469
+ attention_mask=None,
470
+ video_length=None,
471
+ ):
472
+ norm_hidden_states = (
473
+ self.norm1(hidden_states, timestep)
474
+ if self.use_ada_layer_norm
475
+ else self.norm1(hidden_states)
476
+ )
477
+ print(hidden_states.shape, video_length, "tem layer")
478
+ if self.unet_use_cross_frame_attention:
479
+ hidden_states = (
480
+ self.attn1(
481
+ norm_hidden_states,
482
+ attention_mask=attention_mask,
483
+ video_length=video_length,
484
+ )
485
+ + hidden_states
486
+ )
487
+ else:
488
+ hidden_states = (
489
+ self.attn1(norm_hidden_states, attention_mask=attention_mask)
490
+ + hidden_states
491
+ )
492
+
493
+ if self.attn2 is not None:
494
+ # Cross-Attention
495
+ norm_hidden_states = (
496
+ self.norm2(hidden_states, timestep)
497
+ if self.use_ada_layer_norm
498
+ else self.norm2(hidden_states)
499
+ )
500
+ hidden_states = (
501
+ self.attn2(
502
+ norm_hidden_states,
503
+ encoder_hidden_states=encoder_hidden_states,
504
+ attention_mask=attention_mask,
505
+ )
506
+ + hidden_states
507
+ )
508
+
509
+ # Feed-forward
510
+ hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
511
+
512
+ # Temporal-Attention
513
+ if self.unet_use_temporal_attention:
514
+ d = hidden_states.shape[1]
515
+ hidden_states = rearrange(
516
+ hidden_states, "(b f) d c -> (b d) f c", f=video_length
517
+ )
518
+ norm_hidden_states = (
519
+ self.norm_temp(hidden_states, timestep)
520
+ if self.use_ada_layer_norm
521
+ else self.norm_temp(hidden_states)
522
+ )
523
+ hidden_states = self.attn_temp(norm_hidden_states) + hidden_states
524
+ hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
525
+
526
+ return hidden_states
2610_variant_runtime/diffusion/models/conv_in.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import torch.nn.init as init
6
+ from diffusers.models.modeling_utils import ModelMixin
7
+
8
+ from models.motion_module import zero_module
9
+ from models.resnet import InflatedConv3d
10
+
11
+
12
+ class ConvIn(ModelMixin):
13
+ def __init__(
14
+ self,
15
+ conditioning_embedding_channels: int,
16
+ conditioning_channels: int = 3,
17
+ # block_out_channels: Tuple[int] = (16, 32, 64, 128),
18
+ ):
19
+ super().__init__()
20
+ self.conv_in = InflatedConv3d(
21
+ conditioning_channels, conditioning_embedding_channels, kernel_size=3, padding=1
22
+ )
23
+
24
+ def forward(self, conditioning):
25
+ embedding = self.conv_in(conditioning)
26
+ return embedding
2610_variant_runtime/diffusion/models/model_vfi.py ADDED
@@ -0,0 +1,987 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import torch.nn as nn
3
+ from models.unet_2d_condition import UNet2DConditionModel
4
+ from models.unet_3d import UNet3DConditionModel
5
+ from models.pose_guider import PoseGuider
6
+
7
+ class VFIPoseModel(nn.Module):
8
+ def __init__(
9
+ self,
10
+ reference_unet: UNet2DConditionModel,
11
+ denoising_unet: UNet3DConditionModel,
12
+ seed_guider: PoseGuider,
13
+ pose_guider: PoseGuider,
14
+ reference_control_writer,
15
+ reference_control_reader,
16
+ ):
17
+ super().__init__()
18
+ self.reference_unet = reference_unet
19
+ self.denoising_unet = denoising_unet
20
+ self.pose_guider = pose_guider
21
+ self.seed_guider = seed_guider
22
+ self.reference_control_writer = reference_control_writer
23
+ self.reference_control_reader = reference_control_reader
24
+
25
+ def forward(
26
+ self,
27
+ noisy_latents,
28
+ timesteps,
29
+ ref_image_latents,
30
+ clip_image_embeds,
31
+ pose_img,
32
+ seed_img,
33
+ uncond_fwd: bool = False,
34
+ ):
35
+ seed_cond_tensor = seed_img.to(device="cuda")
36
+ seed_fea = self.seed_guider(seed_cond_tensor)
37
+
38
+ pose_cond_tensor = pose_img.to(device="cuda")
39
+ pose_fea = self.pose_guider(pose_cond_tensor)
40
+
41
+ if not uncond_fwd:
42
+ ref_timesteps = torch.zeros_like(timesteps)
43
+ # bs, c, f h, w = ref_image_latents.shape
44
+ # ref_image_latents = ref_image_latents.reshape()
45
+ self.reference_unet(
46
+ ref_image_latents,
47
+ ref_timesteps,
48
+ encoder_hidden_states=clip_image_embeds,
49
+ return_dict=False,
50
+ )
51
+ self.reference_control_reader.update(self.reference_control_writer)
52
+
53
+ pose_fea = seed_fea + pose_fea
54
+
55
+ model_pred = self.denoising_unet(
56
+ noisy_latents,
57
+ timesteps,
58
+ guidance_fea=pose_fea,
59
+ encoder_hidden_states=clip_image_embeds,
60
+ ).sample
61
+
62
+ return model_pred
63
+
64
+
65
+
66
+ class VFIShareVAEModel(nn.Module):
67
+ def __init__(
68
+ self,
69
+ reference_unet: UNet2DConditionModel,
70
+ denoising_unet: UNet3DConditionModel,
71
+ seed_guider,
72
+ pose_guider: PoseGuider,
73
+ reference_control_writer,
74
+ reference_control_reader,
75
+ ):
76
+ super().__init__()
77
+ self.reference_unet = reference_unet
78
+ self.denoising_unet = denoising_unet
79
+ self.pose_guider = pose_guider
80
+ self.seed_guider = seed_guider
81
+ self.reference_control_writer = reference_control_writer
82
+ self.reference_control_reader = reference_control_reader
83
+
84
+ def forward(
85
+ self,
86
+ noisy_latents,
87
+ timesteps,
88
+ ref_image_latents,
89
+ clip_image_embeds,
90
+ seed_img = None,
91
+ pose_img = None,
92
+ uncond_fwd: bool = False,
93
+ ):
94
+ # print(seed_img.shape)
95
+ # print(pose_img.shape, seed_img.shape)
96
+ if seed_img is not None:
97
+ seed_cond_tensor = seed_img.to(device="cuda")
98
+ seed_fea = self.seed_guider(seed_cond_tensor)
99
+ else:
100
+ seed_fea = None
101
+
102
+ if pose_img is not None:
103
+ pose_cond_tensor = pose_img.to(device="cuda")
104
+ pose_fea = self.pose_guider(pose_cond_tensor)
105
+ if seed_fea is None:
106
+ pose_fea = pose_fea
107
+ else:
108
+ pose_fea = seed_fea + pose_fea
109
+ else:
110
+ pose_fea = seed_fea
111
+
112
+ if True:
113
+ ref_timesteps = torch.zeros_like(timesteps)
114
+ self.reference_unet(
115
+ ref_image_latents,
116
+ ref_timesteps,
117
+ encoder_hidden_states=clip_image_embeds,
118
+ return_dict=False,
119
+ )
120
+ self.reference_control_reader.update(self.reference_control_writer)
121
+
122
+ model_pred = self.denoising_unet(
123
+ noisy_latents,
124
+ timesteps,
125
+ guidance_fea=pose_fea,
126
+ encoder_hidden_states=clip_image_embeds,
127
+ ).sample
128
+
129
+ return model_pred
130
+
131
+
132
+ class VFIShareVAEModel_s1(nn.Module):
133
+ def __init__(
134
+ self,
135
+ reference_unet: UNet2DConditionModel,
136
+ denoising_unet: UNet3DConditionModel,
137
+ seed_guider,
138
+ pose_guider: PoseGuider,
139
+ reference_control_writer,
140
+ reference_control_reader,
141
+ ):
142
+ super().__init__()
143
+ self.reference_unet = reference_unet
144
+ self.denoising_unet = denoising_unet
145
+ self.pose_guider = pose_guider
146
+ self.seed_guider = seed_guider
147
+ self.reference_control_writer = reference_control_writer
148
+ self.reference_control_reader = reference_control_reader
149
+
150
+ def forward(
151
+ self,
152
+ noisy_latents,
153
+ timesteps,
154
+ ref_image_latents,
155
+ clip_image_embeds,
156
+ seed_img = None,
157
+ pose_img = None,
158
+ uncond_fwd: bool = False,
159
+ ):
160
+ # print(seed_img.shape)
161
+ # print(pose_img.shape, seed_img.shape)
162
+ if seed_img is not None:
163
+ seed_cond_tensor = seed_img.to(device="cuda")
164
+ seed_fea = self.seed_guider(seed_cond_tensor)
165
+ else:
166
+ seed_fea = None
167
+
168
+ if pose_img is not None:
169
+ pose_cond_tensor = pose_img.to(device="cuda")
170
+ pose_fea = self.pose_guider(pose_cond_tensor)
171
+ if seed_fea is None:
172
+ pose_fea = pose_fea
173
+ else:
174
+ pose_fea = seed_fea + pose_fea
175
+ else:
176
+ pose_fea = seed_fea
177
+
178
+ if not uncond_fwd:
179
+ ref_timesteps = torch.zeros_like(timesteps)
180
+ self.reference_unet(
181
+ ref_image_latents,
182
+ ref_timesteps,
183
+ encoder_hidden_states=clip_image_embeds,
184
+ return_dict=False,
185
+ )
186
+ self.reference_control_reader.update(self.reference_control_writer)
187
+
188
+ model_pred = self.denoising_unet(
189
+ noisy_latents,
190
+ timesteps,
191
+ guidance_fea=pose_fea,
192
+ encoder_hidden_states=clip_image_embeds,
193
+ ).sample
194
+
195
+ return model_pred
196
+
197
+
198
+ class VFINoCFGModel(nn.Module):
199
+ def __init__(
200
+ self,
201
+ reference_unet: UNet2DConditionModel,
202
+ denoising_unet: UNet3DConditionModel,
203
+ seed_guider,
204
+ pose_guider: PoseGuider,
205
+ reference_control_writer,
206
+ reference_control_reader,
207
+ ):
208
+ super().__init__()
209
+ self.reference_unet = reference_unet
210
+ self.denoising_unet = denoising_unet
211
+ self.pose_guider = pose_guider
212
+ self.seed_guider = seed_guider
213
+ self.reference_control_writer = reference_control_writer
214
+ self.reference_control_reader = reference_control_reader
215
+
216
+ def forward(
217
+ self,
218
+ noisy_latents,
219
+ timesteps,
220
+ ref_image_latents,
221
+ clip_image_embeds,
222
+ seed_img = None,
223
+ pose_img = None,
224
+ uncond_fwd: bool = False,
225
+ ):
226
+ # print(seed_img.shape)
227
+ # print(pose_img.shape, seed_img.shape)
228
+ if seed_img is not None:
229
+ seed_cond_tensor = seed_img.to(device="cuda")
230
+ seed_fea = self.seed_guider(seed_cond_tensor)
231
+ else:
232
+ seed_fea = None
233
+
234
+ if pose_img is not None:
235
+ pose_cond_tensor = pose_img.to(device="cuda")
236
+ pose_fea = self.pose_guider(pose_cond_tensor)
237
+ if seed_fea is None:
238
+ pose_fea = pose_fea
239
+ else:
240
+ pose_fea = seed_fea + pose_fea
241
+ else:
242
+ pose_fea = seed_fea
243
+
244
+ if not uncond_fwd:
245
+ ref_timesteps = torch.zeros_like(timesteps)
246
+ self.reference_unet(
247
+ ref_image_latents,
248
+ ref_timesteps,
249
+ encoder_hidden_states=clip_image_embeds,
250
+ return_dict=False,
251
+ )
252
+ self.reference_control_reader.update(self.reference_control_writer)
253
+
254
+ model_pred = self.denoising_unet(
255
+ noisy_latents,
256
+ timesteps,
257
+ guidance_fea=pose_fea,
258
+ encoder_hidden_states=clip_image_embeds,
259
+ ).sample
260
+
261
+ return model_pred
262
+
263
+
264
+ class VFINoRefModel(nn.Module):
265
+ def __init__(
266
+ self,
267
+ reference_unet: UNet2DConditionModel,
268
+ denoising_unet: UNet3DConditionModel,
269
+ seed_guider,
270
+ pose_guider: PoseGuider,
271
+ reference_control_writer,
272
+ reference_control_reader,
273
+ ):
274
+ super().__init__()
275
+ self.reference_unet = reference_unet
276
+ self.denoising_unet = denoising_unet
277
+ self.pose_guider = pose_guider
278
+ self.seed_guider = seed_guider
279
+ self.reference_control_writer = reference_control_writer
280
+ self.reference_control_reader = reference_control_reader
281
+
282
+ def forward(
283
+ self,
284
+ noisy_latents,
285
+ timesteps,
286
+ ref_image_latents,
287
+ clip_image_embeds,
288
+ seed_img = None,
289
+ pose_img = None,
290
+ uncond_fwd: bool = False,
291
+ ):
292
+ # print(seed_img.shape)
293
+ if seed_img is not None:
294
+ seed_cond_tensor = seed_img.to(device="cuda")
295
+ seed_fea = self.seed_guider(seed_cond_tensor)
296
+ else:
297
+ seed_fea = None
298
+
299
+ if pose_img is not None:
300
+ pose_cond_tensor = pose_img.to(device="cuda")
301
+ pose_fea = self.pose_guider(pose_cond_tensor)
302
+ if seed_fea is None:
303
+ pose_fea = pose_fea
304
+ else:
305
+ pose_fea = seed_fea + pose_fea
306
+ else:
307
+ pose_fea = seed_fea
308
+
309
+ model_pred = self.denoising_unet(
310
+ noisy_latents,
311
+ timesteps,
312
+ guidance_fea=pose_fea,
313
+ encoder_hidden_states=clip_image_embeds,
314
+ ).sample
315
+
316
+ return model_pred
317
+
318
+
319
+ # v1-dup
320
+ # reference image are cat to noise, re-train convin
321
+ # v2-dup
322
+ # reference add to, 2 convin
323
+ # v1-blank
324
+ # leave middle padding
325
+ # v2-blank
326
+ # all use 256, batch size 4
327
+
328
+ # v3-add, flexiable reference
329
+ class VFICatModel(nn.Module):
330
+ def __init__(
331
+ self,
332
+ reference_unet: UNet2DConditionModel,
333
+ denoising_unet: UNet3DConditionModel,
334
+ pose_guider: PoseGuider,
335
+ reference_control_writer,
336
+ reference_control_reader,
337
+ ):
338
+ super().__init__()
339
+ self.reference_unet = reference_unet
340
+ self.denoising_unet = denoising_unet
341
+ self.pose_guider = pose_guider
342
+ self.reference_control_writer = reference_control_writer
343
+ self.reference_control_reader = reference_control_reader
344
+
345
+ def forward(
346
+ self,
347
+ noisy_latents,
348
+ timesteps,
349
+ ref_image_latents,
350
+ clip_image_embeds,
351
+ seed_img = None,
352
+ pose_img = None,
353
+ uncond_fwd: bool = False,
354
+ ):
355
+ if seed_img is not None:
356
+ seed_cond_tensor = seed_img.to(device="cuda")
357
+ noisy_latents = torch.cat([noisy_latents, seed_cond_tensor], dim=1)
358
+ else:
359
+ noisy_latents = torch.cat([noisy_latents, torch.zeros_like(noisy_latents).to(device="cuda")], dim=1)
360
+
361
+ if pose_img is not None:
362
+ pose_cond_tensor = pose_img.to(device="cuda")
363
+ pose_fea = self.pose_guider(pose_cond_tensor)
364
+ else:
365
+ pose_fea = None
366
+ if not uncond_fwd:
367
+ ref_timesteps = torch.zeros_like(timesteps)
368
+ self.reference_unet(
369
+ ref_image_latents,
370
+ ref_timesteps,
371
+ encoder_hidden_states=clip_image_embeds,
372
+ return_dict=False,
373
+ )
374
+ self.reference_control_reader.update(self.reference_control_writer)
375
+
376
+ model_pred = self.denoising_unet(
377
+ noisy_latents,
378
+ timesteps,
379
+ guidance_fea=pose_fea,
380
+ encoder_hidden_states=clip_image_embeds,
381
+ ).sample
382
+ return model_pred
383
+
384
+ from einops import rearrange
385
+ class VFIMultiRefModel(nn.Module):
386
+ def __init__(
387
+ self,
388
+ reference_unet: UNet2DConditionModel,
389
+ denoising_unet: UNet3DConditionModel,
390
+ seed_guider,
391
+ pose_guider: PoseGuider,
392
+ reference_control_writer,
393
+ reference_control_reader,
394
+ ):
395
+ super().__init__()
396
+ self.reference_unet = reference_unet
397
+ self.denoising_unet = denoising_unet
398
+ self.pose_guider = pose_guider
399
+ self.seed_guider = seed_guider
400
+ self.reference_control_writer = reference_control_writer
401
+ self.reference_control_reader = reference_control_reader
402
+
403
+ def forward(
404
+ self,
405
+ noisy_latents,
406
+ timesteps,
407
+ ref_image_latents,
408
+ clip_image_embeds,
409
+ seed_img = None,
410
+ pose_img = None,
411
+ uncond_fwd: bool = False,
412
+ ):
413
+ if seed_img is not None:
414
+ seed_cond_tensor = seed_img.to(device="cuda")
415
+ seed_fea = self.seed_guider(seed_cond_tensor)
416
+ else:
417
+ seed_fea = None
418
+
419
+ if pose_img is not None:
420
+ pose_cond_tensor = pose_img.to(device="cuda")
421
+ pose_fea = self.pose_guider(pose_cond_tensor)
422
+ if seed_fea is None:
423
+ pose_fea = pose_fea
424
+ else:
425
+ pose_fea = seed_fea + pose_fea
426
+ else:
427
+ pose_fea = seed_fea
428
+
429
+ if not uncond_fwd:
430
+ # print(timesteps.shape)
431
+ ref_image_latents = rearrange(
432
+ ref_image_latents, "b c f h w -> (b f) c h w"
433
+ )
434
+ ref_timesteps = torch.zeros(ref_image_latents.shape[0]).to(device="cuda")
435
+ # print(ref_timesteps.shape, ref_image_latents.shape, clip_image_embeds.shape)
436
+ self.reference_unet(
437
+ ref_image_latents,
438
+ ref_timesteps,
439
+ encoder_hidden_states=clip_image_embeds,
440
+ return_dict=False,
441
+ )
442
+ self.reference_control_reader.update(self.reference_control_writer)
443
+
444
+ model_pred = self.denoising_unet(
445
+ noisy_latents,
446
+ timesteps,
447
+ guidance_fea=pose_fea,
448
+ encoder_hidden_states=clip_image_embeds,
449
+ ).sample
450
+
451
+ return model_pred
452
+
453
+ from einops import rearrange
454
+ class VFIMultiRefModel_v4_dup(nn.Module):
455
+ def __init__(
456
+ self,
457
+ reference_unet: UNet2DConditionModel,
458
+ denoising_unet: UNet3DConditionModel,
459
+ seed_guider,
460
+ pose_guider: PoseGuider,
461
+ reference_control_writer,
462
+ reference_control_reader,
463
+ ):
464
+ super().__init__()
465
+ self.reference_unet = reference_unet
466
+ self.denoising_unet = denoising_unet
467
+ self.pose_guider = pose_guider
468
+ self.seed_guider = seed_guider
469
+ self.reference_control_writer = reference_control_writer
470
+ self.reference_control_reader = reference_control_reader
471
+
472
+ def forward(
473
+ self,
474
+ noisy_latents,
475
+ timesteps,
476
+ ref_image_latents,
477
+ clip_image_embeds,
478
+ seed_img = None,
479
+ pose_img = None,
480
+ uncond_fwd: bool = False,
481
+ ):
482
+ if seed_img is not None:
483
+ seed_cond_tensor = seed_img.to(device="cuda")
484
+ seed_fea = self.seed_guider(seed_cond_tensor)
485
+ else:
486
+ seed_fea = None
487
+
488
+ if pose_img is not None:
489
+ pose_cond_tensor = pose_img.to(device="cuda")
490
+ pose_fea = self.pose_guider(pose_cond_tensor)
491
+ if seed_fea is None:
492
+ pose_fea = pose_fea
493
+ else:
494
+ pose_fea = seed_fea + pose_fea
495
+ else:
496
+ pose_fea = seed_fea
497
+
498
+ if not uncond_fwd:
499
+ # print(ref_image_latents.shape)
500
+ ref_image_latents = rearrange(
501
+ ref_image_latents, "b c f h w -> (b f) c h w"
502
+ )
503
+ clip_image_embeds_a = clip_image_embeds.repeat(noisy_latents.shape[2], 1, 1)
504
+ # print(clip_image_embeds.shape, clip_image_embeds_a.shape)
505
+ ref_timesteps = torch.zeros(ref_image_latents.shape[0]).to(device="cuda")
506
+ self.reference_unet(
507
+ ref_image_latents,
508
+ ref_timesteps,
509
+ encoder_hidden_states=clip_image_embeds_a,
510
+ return_dict=False,
511
+ )
512
+ self.reference_control_reader.update(self.reference_control_writer)
513
+
514
+ model_pred = self.denoising_unet(
515
+ noisy_latents,
516
+ timesteps,
517
+ guidance_fea=pose_fea,
518
+ encoder_hidden_states=clip_image_embeds,
519
+ ).sample
520
+
521
+ return model_pred
522
+
523
+ class VFIMultiRefModel_v5_dup(nn.Module):
524
+ def __init__(
525
+ self,
526
+ reference_unet: UNet2DConditionModel,
527
+ denoising_unet: UNet3DConditionModel,
528
+ seed_guider,
529
+ pose_guider: PoseGuider,
530
+ reference_control_writer,
531
+ reference_control_reader,
532
+ ):
533
+ super().__init__()
534
+ self.reference_unet = reference_unet
535
+ self.denoising_unet = denoising_unet
536
+ self.pose_guider = pose_guider
537
+ self.seed_guider = seed_guider
538
+ self.reference_control_writer = reference_control_writer
539
+ self.reference_control_reader = reference_control_reader
540
+
541
+ def forward(
542
+ self,
543
+ noisy_latents,
544
+ timesteps,
545
+ ref_image_latents,
546
+ clip_image_embeds,
547
+ seed_img = None,
548
+ pose_img = None,
549
+ uncond_fwd: bool = False,
550
+ ):
551
+ if pose_img is not None:
552
+ pose_cond_tensor = pose_img.to(device="cuda")
553
+ pose_fea = self.pose_guider(pose_cond_tensor)
554
+ else:
555
+ pose_fea = None
556
+
557
+ # clip_image_embeds_a = rearrange(
558
+ # clip_image_embeds, "(b a) c f -> b a c f", a=noisy_latents.shape[2],
559
+ # ) # 2 14 1 768
560
+ # clip_image_embeds_a = clip_image_embeds_a[:, 2]
561
+ # clip_image_embeds_b = clip_image_embeds_a.repeat(1, noisy_latents.shape[2], 1, 1)
562
+ # clip_image_embeds_b = rearrange(
563
+ # clip_image_embeds_b, "b a c f -> (b a) c f",
564
+ # )
565
+
566
+ if not uncond_fwd:
567
+ ref_image_latents = rearrange(
568
+ ref_image_latents, "b c f h w -> (b f) c h w"
569
+ )
570
+ ref_timesteps = torch.zeros(ref_image_latents.shape[0]).to(device="cuda")
571
+ self.reference_unet(
572
+ ref_image_latents,
573
+ ref_timesteps,
574
+ encoder_hidden_states=clip_image_embeds,
575
+ return_dict=False,
576
+ )
577
+ self.reference_control_reader.update(self.reference_control_writer)
578
+
579
+ model_pred = self.denoising_unet(
580
+ noisy_latents,
581
+ timesteps,
582
+ guidance_fea=pose_fea,
583
+ encoder_hidden_states=clip_image_embeds,
584
+ ).sample
585
+
586
+ return model_pred
587
+
588
+ class VFIMultiRefModelv2(nn.Module):
589
+ def __init__(
590
+ self,
591
+ reference_unet: UNet2DConditionModel,
592
+ denoising_unet: UNet3DConditionModel,
593
+ seed_guider,
594
+ pose_guider: PoseGuider,
595
+ reference_control_writer,
596
+ reference_control_reader,
597
+ ):
598
+ super().__init__()
599
+ self.reference_unet = reference_unet
600
+ self.denoising_unet = denoising_unet
601
+ self.pose_guider = pose_guider
602
+ self.seed_guider = seed_guider
603
+ self.reference_control_writer = reference_control_writer
604
+ self.reference_control_reader = reference_control_reader
605
+
606
+ def forward(
607
+ self,
608
+ noisy_latents,
609
+ timesteps,
610
+ ref_image_latents,
611
+ clip_image_embeds,
612
+ seed_img = None,
613
+ pose_img = None,
614
+ uncond_fwd: bool = False,
615
+ ):
616
+ if pose_img is not None:
617
+ pose_cond_tensor = pose_img.to(device="cuda")
618
+ pose_fea = self.pose_guider(pose_cond_tensor)
619
+ else:
620
+ pose_fea = None
621
+
622
+ if not uncond_fwd:
623
+ # print(timesteps.shape)
624
+ ref_image_latents = rearrange(
625
+ ref_image_latents, "b c f h w -> (b f) c h w"
626
+ )
627
+ ref_timesteps = torch.zeros(ref_image_latents.shape[0]).to(device="cuda")
628
+ print(ref_timesteps.shape, ref_image_latents.shape, clip_image_embeds.shape)
629
+ self.reference_unet(
630
+ ref_image_latents,
631
+ ref_timesteps,
632
+ encoder_hidden_states=clip_image_embeds,
633
+ return_dict=False,
634
+ )
635
+ self.reference_control_reader.update(self.reference_control_writer)
636
+
637
+ model_pred = self.denoising_unet(
638
+ noisy_latents,
639
+ timesteps,
640
+ guidance_fea=pose_fea,
641
+ encoder_hidden_states=clip_image_embeds,
642
+ ).sample
643
+
644
+ return model_pred
645
+
646
+ class VFIMultiRefModel_v8(nn.Module):
647
+ def __init__(
648
+ self,
649
+ reference_unet: UNet2DConditionModel,
650
+ denoising_unet: UNet3DConditionModel,
651
+ seed_guider: PoseGuider,
652
+ pose_guider: PoseGuider,
653
+ reference_control_writer,
654
+ reference_control_reader,
655
+ ):
656
+ super().__init__()
657
+ self.reference_unet = reference_unet
658
+ self.denoising_unet = denoising_unet
659
+ self.pose_guider = pose_guider
660
+ self.seed_guider = seed_guider
661
+ self.reference_control_writer = reference_control_writer
662
+ self.reference_control_reader = reference_control_reader
663
+
664
+ def forward(
665
+ self,
666
+ noisy_latents,
667
+ timesteps,
668
+ ref_image_latents,
669
+ clip_image_embeds,
670
+ seed_img = None,
671
+ pose_img = None,
672
+ uncond_fwd: bool = False,
673
+ ):
674
+ if seed_img is not None:
675
+ seed_cond_tensor = seed_img.to(device="cuda")
676
+ seed_fea = self.seed_guider(seed_cond_tensor)
677
+ else:
678
+ seed_fea = None
679
+
680
+ if pose_img is not None:
681
+ pose_cond_tensor = pose_img.to(device="cuda")
682
+ pose_fea = self.pose_guider(pose_cond_tensor)
683
+ if seed_fea is None:
684
+ pose_fea = pose_fea
685
+ else:
686
+ pose_fea = seed_fea + pose_fea
687
+ else:
688
+ pose_fea = seed_fea
689
+
690
+ # random pick two
691
+ idx_1 = 2
692
+ idx_2 = 11
693
+ ref_image_latents_1 = ref_image_latents[:, :, idx_1]
694
+ ref_image_latents_2 = ref_image_latents[:, :, idx_2]
695
+
696
+ length = noisy_latents.shape[2]
697
+ confidence_zero_to_one = torch.linspace(0, 1, steps=length).to(device="cuda")
698
+ confidence_one_to_zero = torch.linspace(1, 0, steps=length).to(device="cuda")
699
+ confidence_1 = torch.cat([confidence_zero_to_one[-idx_1-1:],confidence_one_to_zero[1:-idx_1]])
700
+ confidence_2 = torch.cat([confidence_zero_to_one[-idx_2-1:],confidence_one_to_zero[1:-idx_2]])
701
+
702
+ if True: #not uncond_fwd:
703
+ ref_timesteps = torch.zeros_like(timesteps)
704
+ self.reference_unet(
705
+ ref_image_latents_1,
706
+ ref_timesteps,
707
+ encoder_hidden_states=clip_image_embeds,
708
+ return_dict=False,
709
+ )
710
+ self.reference_control_reader.update(self.reference_control_writer, confidence_1)
711
+
712
+ self.reference_unet(
713
+ ref_image_latents_2,
714
+ ref_timesteps,
715
+ encoder_hidden_states=clip_image_embeds,
716
+ return_dict=False,
717
+ )
718
+ self.reference_control_reader.update(self.reference_control_writer, confidence_2)
719
+
720
+ model_pred = self.denoising_unet(
721
+ noisy_latents,
722
+ timesteps,
723
+ guidance_fea=pose_fea,
724
+ encoder_hidden_states=clip_image_embeds,
725
+ ).sample
726
+
727
+ return model_pred
728
+
729
+
730
+ class VFIMultiRefModel_16frames(nn.Module):
731
+ def __init__(
732
+ self,
733
+ reference_unet: UNet2DConditionModel,
734
+ denoising_unet: UNet3DConditionModel,
735
+ seed_guider: PoseGuider,
736
+ pose_guider: PoseGuider,
737
+ reference_control_writer,
738
+ reference_control_reader,
739
+ ):
740
+ super().__init__()
741
+ self.reference_unet = reference_unet
742
+ self.denoising_unet = denoising_unet
743
+ self.pose_guider = pose_guider
744
+ self.seed_guider = seed_guider
745
+ self.reference_control_writer = reference_control_writer
746
+ self.reference_control_reader = reference_control_reader
747
+
748
+ def forward(
749
+ self,
750
+ noisy_latents,
751
+ timesteps,
752
+ ref_image_latents,
753
+ clip_image_embeds,
754
+ seed_img = None,
755
+ pose_img = None,
756
+ uncond_fwd: bool = False,
757
+ ):
758
+ if seed_img is not None:
759
+ seed_cond_tensor = seed_img.to(device="cuda")
760
+ seed_fea = self.seed_guider(seed_cond_tensor)
761
+ else:
762
+ seed_fea = None
763
+
764
+ if pose_img is not None:
765
+ pose_cond_tensor = pose_img.to(device="cuda")
766
+ pose_fea = self.pose_guider(pose_cond_tensor)
767
+ if seed_fea is None:
768
+ pose_fea = pose_fea
769
+ else:
770
+ pose_fea = seed_fea + pose_fea
771
+ else:
772
+ pose_fea = seed_fea
773
+
774
+ # random pick two
775
+ idx_1 = 1
776
+ idx_2 = -1
777
+ ref_image_latents_1 = ref_image_latents[:, :, idx_1]
778
+ ref_image_latents_2 = ref_image_latents[:, :, idx_2]
779
+
780
+ length = noisy_latents.shape[2]
781
+ confidence_zero_to_one = torch.linspace(0, 1, steps=length).to(device="cuda")
782
+ confidence_one_to_zero = torch.linspace(1, 0, steps=length).to(device="cuda")
783
+ confidence_1 = confidence_one_to_zero
784
+ confidence_2 = confidence_zero_to_one
785
+
786
+ if True: #not uncond_fwd:
787
+ ref_timesteps = torch.zeros_like(timesteps)
788
+ self.reference_unet(
789
+ ref_image_latents_1,
790
+ ref_timesteps,
791
+ encoder_hidden_states=clip_image_embeds,
792
+ return_dict=False,
793
+ )
794
+ self.reference_control_reader.update(self.reference_control_writer, confidence_1)
795
+
796
+ self.reference_unet(
797
+ ref_image_latents_2,
798
+ ref_timesteps,
799
+ encoder_hidden_states=clip_image_embeds,
800
+ return_dict=False,
801
+ )
802
+ self.reference_control_reader.update(self.reference_control_writer, confidence_2)
803
+
804
+ model_pred = self.denoising_unet(
805
+ noisy_latents,
806
+ timesteps,
807
+ guidance_fea=pose_fea,
808
+ encoder_hidden_states=clip_image_embeds,
809
+ ).sample
810
+
811
+ return model_pred
812
+
813
+
814
+
815
+ class VFIMultiRefModel_8Time(nn.Module):
816
+ def __init__(
817
+ self,
818
+ reference_unet: UNet2DConditionModel,
819
+ denoising_unet: UNet3DConditionModel,
820
+ seed_guider: PoseGuider,
821
+ pose_guider: PoseGuider,
822
+ reference_control_writer,
823
+ reference_control_reader,
824
+ ):
825
+ super().__init__()
826
+ self.reference_unet = reference_unet
827
+ self.denoising_unet = denoising_unet
828
+ self.pose_guider = pose_guider
829
+ self.seed_guider = seed_guider
830
+ self.reference_control_writer = reference_control_writer
831
+ self.reference_control_reader = reference_control_reader
832
+
833
+ def forward(
834
+ self,
835
+ noisy_latents,
836
+ timesteps,
837
+ ref_image_latents,
838
+ clip_image_embeds,
839
+ seed_img = None,
840
+ pose_img = None,
841
+ uncond_fwd: bool = False,
842
+ ):
843
+ if seed_img is not None:
844
+ seed_cond_tensor = seed_img.to(device="cuda")
845
+ seed_fea = self.seed_guider(seed_cond_tensor)
846
+ else:
847
+ seed_fea = None
848
+
849
+ if pose_img is not None:
850
+ pose_cond_tensor = pose_img.to(device="cuda")
851
+ pose_fea = self.pose_guider(pose_cond_tensor)
852
+ if seed_fea is None:
853
+ pose_fea = pose_fea
854
+ else:
855
+ pose_fea = seed_fea + pose_fea
856
+ else:
857
+ pose_fea = seed_fea
858
+
859
+
860
+ length = ref_image_latents.shape[2]
861
+ confidence_zero_to_one = torch.linspace(0, 1, steps=length).to(
862
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
863
+ )
864
+ confidence_one_to_zero = torch.linspace(1, 0, steps=length).to(
865
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
866
+ )
867
+ confidence_lst = []
868
+ confidence_lst.append(confidence_one_to_zero.to(
869
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
870
+ ))
871
+ for idx_1 in range(1,length-1):
872
+ confidence_lst.append(torch.cat([confidence_zero_to_one[-idx_1-1:],confidence_one_to_zero[1:-idx_1]]).to(
873
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
874
+ ))
875
+ confidence_lst.append(confidence_one_to_zero.to(
876
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
877
+ ))
878
+ # confidence_lst = [
879
+ # x.view(1,length,1,1) for x in confidence_lst
880
+ # ]
881
+
882
+ if True: #not uncond_fwd:
883
+ ref_timesteps = torch.zeros_like(timesteps)
884
+ for ref_id in [0, 1, 2, 3, 12, 13, 14, 15]:
885
+ self.reference_unet(
886
+ ref_image_latents[:, :, ref_id],
887
+ ref_timesteps,
888
+ encoder_hidden_states=clip_image_embeds,
889
+ return_dict=False,
890
+ )
891
+ self.reference_control_reader.update(self.reference_control_writer, confidence_lst[ref_id])
892
+
893
+ model_pred = self.denoising_unet(
894
+ noisy_latents,
895
+ timesteps,
896
+ guidance_fea=pose_fea,
897
+ encoder_hidden_states=clip_image_embeds,
898
+ ).sample
899
+
900
+ return model_pred
901
+
902
+ class VFIMultiRefModel_1Time(nn.Module):
903
+ def __init__(
904
+ self,
905
+ reference_unet: UNet2DConditionModel,
906
+ denoising_unet: UNet3DConditionModel,
907
+ seed_guider: PoseGuider,
908
+ pose_guider: PoseGuider,
909
+ reference_control_writer,
910
+ reference_control_reader,
911
+ ):
912
+ super().__init__()
913
+ self.reference_unet = reference_unet
914
+ self.denoising_unet = denoising_unet
915
+ self.pose_guider = pose_guider
916
+ self.seed_guider = seed_guider
917
+ self.reference_control_writer = reference_control_writer
918
+ self.reference_control_reader = reference_control_reader
919
+
920
+ def forward(
921
+ self,
922
+ noisy_latents,
923
+ timesteps,
924
+ ref_image_latents,
925
+ clip_image_embeds,
926
+ seed_img = None,
927
+ pose_img = None,
928
+ uncond_fwd: bool = False,
929
+ ):
930
+ if seed_img is not None:
931
+ seed_cond_tensor = seed_img.to(device="cuda")
932
+ seed_fea = self.seed_guider(seed_cond_tensor)
933
+ else:
934
+ seed_fea = None
935
+
936
+ if pose_img is not None:
937
+ pose_cond_tensor = pose_img.to(device="cuda")
938
+ pose_fea = self.pose_guider(pose_cond_tensor)
939
+ if seed_fea is None:
940
+ pose_fea = pose_fea
941
+ else:
942
+ pose_fea = seed_fea + pose_fea
943
+ else:
944
+ pose_fea = seed_fea
945
+
946
+
947
+ length = ref_image_latents.shape[2]
948
+ confidence_zero_to_one = torch.linspace(0, 1, steps=length).to(
949
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
950
+ )
951
+ confidence_one_to_zero = torch.linspace(1, 0, steps=length).to(
952
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
953
+ )
954
+ confidence_lst = []
955
+ confidence_lst.append(confidence_one_to_zero.to(
956
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
957
+ ))
958
+ for idx_1 in range(1,length-1):
959
+ confidence_lst.append(torch.cat([confidence_zero_to_one[-idx_1-1:],confidence_one_to_zero[1:-idx_1]]).to(
960
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
961
+ ))
962
+ confidence_lst.append(confidence_one_to_zero.to(
963
+ dtype=ref_image_latents.dtype, device=ref_image_latents.device
964
+ ))
965
+ # confidence_lst = [
966
+ # x.view(1,length,1,1) for x in confidence_lst
967
+ # ]
968
+
969
+ if True: #not uncond_fwd:
970
+ ref_timesteps = torch.zeros_like(timesteps)
971
+ for ref_id in [0, 1, 2, 3, 12, 13, 14, 15]:
972
+ self.reference_unet(
973
+ ref_image_latents[:, :, ref_id],
974
+ ref_timesteps,
975
+ encoder_hidden_states=clip_image_embeds,
976
+ return_dict=False,
977
+ )
978
+ self.reference_control_reader.update(self.reference_control_writer, confidence_lst[ref_id])
979
+
980
+ model_pred = self.denoising_unet(
981
+ noisy_latents,
982
+ timesteps,
983
+ guidance_fea=pose_fea,
984
+ encoder_hidden_states=clip_image_embeds,
985
+ ).sample
986
+
987
+ return model_pred
2610_variant_runtime/diffusion/models/motion_module.py ADDED
@@ -0,0 +1,390 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapt from https://github.com/guoyww/AnimateDiff/blob/main/animatediff/models/motion_module.py
2
+ import math
3
+ from dataclasses import dataclass
4
+ from typing import Callable, Optional
5
+
6
+ import torch
7
+ from diffusers.models.attention import FeedForward
8
+ from diffusers.models.attention_processor import Attention, AttnProcessor
9
+ from diffusers.utils import BaseOutput
10
+ from diffusers.utils.import_utils import is_xformers_available
11
+ from einops import rearrange, repeat
12
+ from torch import nn
13
+
14
+
15
+ def zero_module(module):
16
+ # Zero out the parameters of a module and return it.
17
+ for p in module.parameters():
18
+ p.detach().zero_()
19
+ return module
20
+
21
+
22
+ @dataclass
23
+ class TemporalTransformer3DModelOutput(BaseOutput):
24
+ sample: torch.FloatTensor
25
+
26
+
27
+ if is_xformers_available():
28
+ import xformers
29
+ import xformers.ops
30
+ else:
31
+ xformers = None
32
+
33
+
34
+ def get_motion_module(in_channels, motion_module_type: str, motion_module_kwargs: dict):
35
+ if motion_module_type == "Vanilla":
36
+ return VanillaTemporalModule(
37
+ in_channels=in_channels,
38
+ **motion_module_kwargs,
39
+ )
40
+ else:
41
+ raise ValueError
42
+
43
+
44
+ class VanillaTemporalModule(nn.Module):
45
+ def __init__(
46
+ self,
47
+ in_channels,
48
+ num_attention_heads=8,
49
+ num_transformer_block=2,
50
+ attention_block_types=("Temporal_Self", "Temporal_Self"),
51
+ cross_frame_attention_mode=None,
52
+ temporal_position_encoding=False,
53
+ temporal_position_encoding_max_len=24,
54
+ temporal_attention_dim_div=1,
55
+ zero_initialize=True,
56
+ ):
57
+ super().__init__()
58
+
59
+ self.temporal_transformer = TemporalTransformer3DModel(
60
+ in_channels=in_channels,
61
+ num_attention_heads=num_attention_heads,
62
+ attention_head_dim=in_channels
63
+ // num_attention_heads
64
+ // temporal_attention_dim_div,
65
+ num_layers=num_transformer_block,
66
+ attention_block_types=attention_block_types,
67
+ cross_frame_attention_mode=cross_frame_attention_mode,
68
+ temporal_position_encoding=temporal_position_encoding,
69
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
70
+ )
71
+
72
+ if zero_initialize:
73
+ self.temporal_transformer.proj_out = zero_module(
74
+ self.temporal_transformer.proj_out
75
+ )
76
+
77
+ def forward(
78
+ self,
79
+ input_tensor,
80
+ temb,
81
+ encoder_hidden_states,
82
+ attention_mask=None,
83
+ anchor_frame_idx=None,
84
+ ):
85
+ hidden_states = input_tensor
86
+ hidden_states = self.temporal_transformer(
87
+ hidden_states, encoder_hidden_states, attention_mask
88
+ )
89
+
90
+ output = hidden_states
91
+ return output
92
+
93
+
94
+ class TemporalTransformer3DModel(nn.Module):
95
+ def __init__(
96
+ self,
97
+ in_channels,
98
+ num_attention_heads,
99
+ attention_head_dim,
100
+ num_layers,
101
+ attention_block_types=(
102
+ "Temporal_Self",
103
+ "Temporal_Self",
104
+ ),
105
+ dropout=0.0,
106
+ norm_num_groups=32,
107
+ cross_attention_dim=768,
108
+ activation_fn="geglu",
109
+ attention_bias=False,
110
+ upcast_attention=False,
111
+ cross_frame_attention_mode=None,
112
+ temporal_position_encoding=False,
113
+ temporal_position_encoding_max_len=24,
114
+ ):
115
+ super().__init__()
116
+
117
+ inner_dim = num_attention_heads * attention_head_dim
118
+
119
+ self.norm = torch.nn.GroupNorm(
120
+ num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True
121
+ )
122
+ self.proj_in = nn.Linear(in_channels, inner_dim)
123
+
124
+ self.transformer_blocks = nn.ModuleList(
125
+ [
126
+ TemporalTransformerBlock(
127
+ dim=inner_dim,
128
+ num_attention_heads=num_attention_heads,
129
+ attention_head_dim=attention_head_dim,
130
+ attention_block_types=attention_block_types,
131
+ dropout=dropout,
132
+ norm_num_groups=norm_num_groups,
133
+ cross_attention_dim=cross_attention_dim,
134
+ activation_fn=activation_fn,
135
+ attention_bias=attention_bias,
136
+ upcast_attention=upcast_attention,
137
+ cross_frame_attention_mode=cross_frame_attention_mode,
138
+ temporal_position_encoding=temporal_position_encoding,
139
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
140
+ )
141
+ for d in range(num_layers)
142
+ ]
143
+ )
144
+ self.proj_out = nn.Linear(inner_dim, in_channels)
145
+
146
+ def forward(self, hidden_states, encoder_hidden_states=None, attention_mask=None):
147
+ assert (
148
+ hidden_states.dim() == 5
149
+ ), f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
150
+ video_length = hidden_states.shape[2]
151
+ hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
152
+
153
+ batch, channel, height, weight = hidden_states.shape
154
+ residual = hidden_states
155
+
156
+ hidden_states = self.norm(hidden_states)
157
+ inner_dim = hidden_states.shape[1]
158
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
159
+ batch, height * weight, inner_dim
160
+ )
161
+ hidden_states = self.proj_in(hidden_states)
162
+
163
+ # Transformer Blocks
164
+ for block in self.transformer_blocks:
165
+ hidden_states = block(
166
+ hidden_states,
167
+ encoder_hidden_states=encoder_hidden_states,
168
+ video_length=video_length,
169
+ )
170
+
171
+ # output
172
+ hidden_states = self.proj_out(hidden_states)
173
+ hidden_states = (
174
+ hidden_states.reshape(batch, height, weight, inner_dim)
175
+ .permute(0, 3, 1, 2)
176
+ .contiguous()
177
+ )
178
+
179
+ output = hidden_states + residual
180
+ output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
181
+
182
+ return output
183
+
184
+
185
+ class TemporalTransformerBlock(nn.Module):
186
+ def __init__(
187
+ self,
188
+ dim,
189
+ num_attention_heads,
190
+ attention_head_dim,
191
+ attention_block_types=(
192
+ "Temporal_Self",
193
+ "Temporal_Self",
194
+ ),
195
+ dropout=0.0,
196
+ norm_num_groups=32,
197
+ cross_attention_dim=768,
198
+ activation_fn="geglu",
199
+ attention_bias=False,
200
+ upcast_attention=False,
201
+ cross_frame_attention_mode=None,
202
+ temporal_position_encoding=False,
203
+ temporal_position_encoding_max_len=24,
204
+ ):
205
+ super().__init__()
206
+
207
+ attention_blocks = []
208
+ norms = []
209
+
210
+ for block_name in attention_block_types:
211
+ attention_blocks.append(
212
+ VersatileAttention(
213
+ attention_mode=block_name.split("_")[0],
214
+ cross_attention_dim=(
215
+ cross_attention_dim if block_name.endswith("_Cross") else None
216
+ ),
217
+ query_dim=dim,
218
+ heads=num_attention_heads,
219
+ dim_head=attention_head_dim,
220
+ dropout=dropout,
221
+ bias=attention_bias,
222
+ upcast_attention=upcast_attention,
223
+ cross_frame_attention_mode=cross_frame_attention_mode,
224
+ temporal_position_encoding=temporal_position_encoding,
225
+ temporal_position_encoding_max_len=temporal_position_encoding_max_len,
226
+ )
227
+ )
228
+ norms.append(nn.LayerNorm(dim))
229
+
230
+ self.attention_blocks = nn.ModuleList(attention_blocks)
231
+ self.norms = nn.ModuleList(norms)
232
+
233
+ self.ff = FeedForward(dim, dropout=dropout, activation_fn=activation_fn)
234
+ self.ff_norm = nn.LayerNorm(dim)
235
+
236
+ def forward(
237
+ self,
238
+ hidden_states,
239
+ encoder_hidden_states=None,
240
+ attention_mask=None,
241
+ video_length=None,
242
+ ):
243
+ for attention_block, norm in zip(self.attention_blocks, self.norms):
244
+ norm_hidden_states = norm(hidden_states)
245
+ hidden_states = (
246
+ attention_block(
247
+ norm_hidden_states,
248
+ encoder_hidden_states=(
249
+ encoder_hidden_states
250
+ if attention_block.is_cross_attention
251
+ else None
252
+ ),
253
+ video_length=video_length,
254
+ )
255
+ + hidden_states
256
+ )
257
+
258
+ hidden_states = self.ff(self.ff_norm(hidden_states)) + hidden_states
259
+
260
+ output = hidden_states
261
+ return output
262
+
263
+
264
+ class PositionalEncoding(nn.Module):
265
+ def __init__(self, d_model, dropout=0.0, max_len=24):
266
+ super().__init__()
267
+ self.dropout = nn.Dropout(p=dropout)
268
+ position = torch.arange(max_len).unsqueeze(1)
269
+ div_term = torch.exp(
270
+ torch.arange(0, d_model, 2) * (-math.log(10000.0) / d_model)
271
+ )
272
+ pe = torch.zeros(1, max_len, d_model)
273
+ pe[0, :, 0::2] = torch.sin(position * div_term)
274
+ pe[0, :, 1::2] = torch.cos(position * div_term)
275
+ self.register_buffer("pe", pe)
276
+
277
+ def forward(self, x):
278
+ x = x + self.pe[:, : x.size(1)]
279
+ return self.dropout(x)
280
+
281
+
282
+ class VersatileAttention(Attention):
283
+ def __init__(
284
+ self,
285
+ attention_mode=None,
286
+ cross_frame_attention_mode=None,
287
+ temporal_position_encoding=False,
288
+ temporal_position_encoding_max_len=24,
289
+ *args,
290
+ **kwargs,
291
+ ):
292
+ super().__init__(*args, **kwargs)
293
+ assert attention_mode == "Temporal"
294
+
295
+ self.attention_mode = attention_mode
296
+ self.is_cross_attention = kwargs["cross_attention_dim"] is not None
297
+
298
+ self.pos_encoder = (
299
+ PositionalEncoding(
300
+ kwargs["query_dim"],
301
+ dropout=0.0,
302
+ max_len=temporal_position_encoding_max_len,
303
+ )
304
+ if (temporal_position_encoding and attention_mode == "Temporal")
305
+ else None
306
+ )
307
+
308
+ def extra_repr(self):
309
+ return f"(Module Info) Attention_Mode: {self.attention_mode}, Is_Cross_Attention: {self.is_cross_attention}"
310
+
311
+ def set_use_memory_efficient_attention_xformers(
312
+ self,
313
+ use_memory_efficient_attention_xformers: bool,
314
+ attention_op: Optional[Callable] = None,
315
+ ):
316
+ if use_memory_efficient_attention_xformers:
317
+ if not is_xformers_available():
318
+ raise ModuleNotFoundError(
319
+ (
320
+ "Refer to https://github.com/facebookresearch/xformers for more information on how to install"
321
+ " xformers"
322
+ ),
323
+ name="xformers",
324
+ )
325
+ elif not torch.cuda.is_available():
326
+ raise ValueError(
327
+ "torch.cuda.is_available() should be True but is False. xformers' memory efficient attention is"
328
+ " only available for GPU "
329
+ )
330
+ else:
331
+ try:
332
+ # Make sure we can run the memory efficient attention
333
+ _ = xformers.ops.memory_efficient_attention(
334
+ torch.randn((1, 2, 40), device="cuda"),
335
+ torch.randn((1, 2, 40), device="cuda"),
336
+ torch.randn((1, 2, 40), device="cuda"),
337
+ )
338
+ except Exception as e:
339
+ raise e
340
+
341
+ # XFormersAttnProcessor corrupts video generation and work with Pytorch 1.13.
342
+ # Pytorch 2.0.1 AttnProcessor works the same as XFormersAttnProcessor in Pytorch 1.13.
343
+ # You don't need XFormersAttnProcessor here.
344
+ # processor = XFormersAttnProcessor(
345
+ # attention_op=attention_op,
346
+ # )
347
+ processor = AttnProcessor()
348
+ else:
349
+ processor = AttnProcessor()
350
+
351
+ self.set_processor(processor)
352
+
353
+ def forward(
354
+ self,
355
+ hidden_states,
356
+ encoder_hidden_states=None,
357
+ attention_mask=None,
358
+ video_length=None,
359
+ **cross_attention_kwargs,
360
+ ):
361
+ if self.attention_mode == "Temporal":
362
+ d = hidden_states.shape[1] # d means HxW
363
+ hidden_states = rearrange(
364
+ hidden_states, "(b f) d c -> (b d) f c", f=video_length
365
+ )
366
+
367
+ if self.pos_encoder is not None:
368
+ hidden_states = self.pos_encoder(hidden_states)
369
+
370
+ encoder_hidden_states = (
371
+ repeat(encoder_hidden_states, "b n c -> (b d) n c", d=d)
372
+ if encoder_hidden_states is not None
373
+ else encoder_hidden_states
374
+ )
375
+
376
+ else:
377
+ raise NotImplementedError
378
+
379
+ hidden_states = self.processor(
380
+ self,
381
+ hidden_states,
382
+ encoder_hidden_states=encoder_hidden_states,
383
+ attention_mask=attention_mask,
384
+ **cross_attention_kwargs,
385
+ )
386
+
387
+ if self.attention_mode == "Temporal":
388
+ hidden_states = rearrange(hidden_states, "(b d) f c -> (b f) d c", d=d)
389
+
390
+ return hidden_states
2610_variant_runtime/diffusion/models/mutual_self_attention.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/magic-research/magic-animate/blob/main/magicanimate/models/mutual_self_attention.py
2
+ from typing import Any, Dict, Optional
3
+
4
+ import torch
5
+ from einops import rearrange
6
+
7
+ from models.attention import TemporalBasicTransformerBlock
8
+
9
+ from .attention import BasicTransformerBlock
10
+
11
+
12
+ def torch_dfs(model: torch.nn.Module):
13
+ result = [model]
14
+ for child in model.children():
15
+ result += torch_dfs(child)
16
+ return result
17
+
18
+
19
+ class ReferenceAttentionControl:
20
+ def __init__(
21
+ self,
22
+ unet,
23
+ mode="write",
24
+ do_classifier_free_guidance=False,
25
+ attention_auto_machine_weight=float("inf"),
26
+ gn_auto_machine_weight=1.0,
27
+ style_fidelity=1.0,
28
+ reference_attn=True,
29
+ reference_adain=False,
30
+ fusion_blocks="midup",
31
+ batch_size=1,
32
+ ) -> None:
33
+ # 10. Modify self attention and group norm
34
+ self.unet = unet
35
+ assert mode in ["read", "write"]
36
+ assert fusion_blocks in ["midup", "full"]
37
+ self.reference_attn = reference_attn
38
+ self.reference_adain = reference_adain
39
+ self.fusion_blocks = fusion_blocks
40
+ self.register_reference_hooks(
41
+ mode,
42
+ do_classifier_free_guidance,
43
+ attention_auto_machine_weight,
44
+ gn_auto_machine_weight,
45
+ style_fidelity,
46
+ reference_attn,
47
+ reference_adain,
48
+ fusion_blocks,
49
+ batch_size=batch_size,
50
+ )
51
+
52
+ def register_reference_hooks(
53
+ self,
54
+ mode,
55
+ do_classifier_free_guidance,
56
+ attention_auto_machine_weight,
57
+ gn_auto_machine_weight,
58
+ style_fidelity,
59
+ reference_attn,
60
+ reference_adain,
61
+ dtype=torch.float16,
62
+ batch_size=1,
63
+ num_images_per_prompt=1,
64
+ device=torch.device("cpu"),
65
+ fusion_blocks="midup",
66
+ ):
67
+ MODE = mode
68
+ do_classifier_free_guidance = do_classifier_free_guidance
69
+ attention_auto_machine_weight = attention_auto_machine_weight
70
+ gn_auto_machine_weight = gn_auto_machine_weight
71
+ style_fidelity = style_fidelity
72
+ reference_attn = reference_attn
73
+ reference_adain = reference_adain
74
+ fusion_blocks = fusion_blocks
75
+ num_images_per_prompt = num_images_per_prompt
76
+ dtype = dtype
77
+ if do_classifier_free_guidance:
78
+ uc_mask = (
79
+ torch.Tensor(
80
+ [1] * batch_size * num_images_per_prompt * 16
81
+ + [0] * batch_size * num_images_per_prompt * 16
82
+ )
83
+ .to(device)
84
+ .bool()
85
+ )
86
+ else:
87
+ uc_mask = (
88
+ torch.Tensor([0] * batch_size * num_images_per_prompt * 2)
89
+ .to(device)
90
+ .bool()
91
+ )
92
+
93
+ def hacked_basic_transformer_inner_forward(
94
+ self,
95
+ hidden_states: torch.FloatTensor,
96
+ attention_mask: Optional[torch.FloatTensor] = None,
97
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
98
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
99
+ timestep: Optional[torch.LongTensor] = None,
100
+ cross_attention_kwargs: Dict[str, Any] = None,
101
+ class_labels: Optional[torch.LongTensor] = None,
102
+ video_length=None,
103
+ ):
104
+ if self.use_ada_layer_norm: # False
105
+ norm_hidden_states = self.norm1(hidden_states, timestep)
106
+ elif self.use_ada_layer_norm_zero:
107
+ (
108
+ norm_hidden_states,
109
+ gate_msa,
110
+ shift_mlp,
111
+ scale_mlp,
112
+ gate_mlp,
113
+ ) = self.norm1(
114
+ hidden_states,
115
+ timestep,
116
+ class_labels,
117
+ hidden_dtype=hidden_states.dtype,
118
+ )
119
+ else:
120
+ norm_hidden_states = self.norm1(hidden_states)
121
+
122
+ # 1. Self-Attention
123
+ # self.only_cross_attention = False
124
+ cross_attention_kwargs = (
125
+ cross_attention_kwargs if cross_attention_kwargs is not None else {}
126
+ )
127
+ if self.only_cross_attention:
128
+ attn_output = self.attn1(
129
+ norm_hidden_states,
130
+ encoder_hidden_states=(
131
+ encoder_hidden_states if self.only_cross_attention else None
132
+ ),
133
+ attention_mask=attention_mask,
134
+ **cross_attention_kwargs,
135
+ )
136
+ else:
137
+ if MODE == "write":
138
+ self.bank.append(norm_hidden_states.clone())
139
+ attn_output = self.attn1(
140
+ norm_hidden_states,
141
+ encoder_hidden_states=(
142
+ encoder_hidden_states if self.only_cross_attention else None
143
+ ),
144
+ attention_mask=attention_mask,
145
+ **cross_attention_kwargs,
146
+ )
147
+ if MODE == "read":
148
+ #print("before: ", self.bank[0].shape)
149
+ bank_fea = [
150
+ rearrange(
151
+ d.unsqueeze(1).repeat(1, video_length, 1, 1),
152
+ "b t l c -> (b t) l c",
153
+ )
154
+ for d in self.bank
155
+ ]
156
+ #print("after: ", bank_fea[0].shape)
157
+ modify_norm_hidden_states = torch.cat(
158
+ [norm_hidden_states] + bank_fea, dim=1
159
+ )
160
+ hidden_states_uc = (
161
+ self.attn1(
162
+ norm_hidden_states,
163
+ encoder_hidden_states=modify_norm_hidden_states,
164
+ attention_mask=attention_mask,
165
+ )
166
+ + hidden_states
167
+ )
168
+ if do_classifier_free_guidance:
169
+ hidden_states_c = hidden_states_uc.clone()
170
+ _uc_mask = uc_mask.clone()
171
+ if hidden_states.shape[0] != _uc_mask.shape[0]:
172
+ _uc_mask = (
173
+ torch.Tensor(
174
+ [1] * (hidden_states.shape[0] // 2)
175
+ + [0] * (hidden_states.shape[0] // 2)
176
+ )
177
+ .to(device)
178
+ .bool()
179
+ )
180
+ hidden_states_c[_uc_mask] = (
181
+ self.attn1(
182
+ norm_hidden_states[_uc_mask],
183
+ encoder_hidden_states=norm_hidden_states[_uc_mask],
184
+ attention_mask=attention_mask,
185
+ )
186
+ + hidden_states[_uc_mask]
187
+ )
188
+ hidden_states = hidden_states_c.clone()
189
+ else:
190
+ hidden_states = hidden_states_uc
191
+
192
+ # self.bank.clear()
193
+ if self.attn2 is not None:
194
+ # Cross-Attention
195
+ norm_hidden_states = (
196
+ self.norm2(hidden_states, timestep)
197
+ if self.use_ada_layer_norm
198
+ else self.norm2(hidden_states)
199
+ )
200
+ hidden_states = (
201
+ self.attn2(
202
+ norm_hidden_states,
203
+ encoder_hidden_states=encoder_hidden_states,
204
+ attention_mask=attention_mask,
205
+ )
206
+ + hidden_states
207
+ )
208
+
209
+ # Feed-forward
210
+ hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
211
+
212
+ # Temporal-Attention
213
+ if self.unet_use_temporal_attention:
214
+ d = hidden_states.shape[1]
215
+ hidden_states = rearrange(
216
+ hidden_states, "(b f) d c -> (b d) f c", f=video_length
217
+ )
218
+ norm_hidden_states = (
219
+ self.norm_temp(hidden_states, timestep)
220
+ if self.use_ada_layer_norm
221
+ else self.norm_temp(hidden_states)
222
+ )
223
+ hidden_states = (
224
+ self.attn_temp(norm_hidden_states) + hidden_states
225
+ )
226
+ hidden_states = rearrange(
227
+ hidden_states, "(b d) f c -> (b f) d c", d=d
228
+ )
229
+
230
+ return hidden_states
231
+
232
+ if self.use_ada_layer_norm_zero:
233
+ attn_output = gate_msa.unsqueeze(1) * attn_output
234
+ hidden_states = attn_output + hidden_states
235
+
236
+ if self.attn2 is not None:
237
+ norm_hidden_states = (
238
+ self.norm2(hidden_states, timestep)
239
+ if self.use_ada_layer_norm
240
+ else self.norm2(hidden_states)
241
+ )
242
+
243
+ # 2. Cross-Attention
244
+ attn_output = self.attn2(
245
+ norm_hidden_states,
246
+ encoder_hidden_states=encoder_hidden_states,
247
+ attention_mask=encoder_attention_mask,
248
+ **cross_attention_kwargs,
249
+ )
250
+ hidden_states = attn_output + hidden_states
251
+
252
+ # 3. Feed-forward
253
+ norm_hidden_states = self.norm3(hidden_states)
254
+
255
+ if self.use_ada_layer_norm_zero:
256
+ norm_hidden_states = (
257
+ norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
258
+ )
259
+
260
+ ff_output = self.ff(norm_hidden_states)
261
+
262
+ if self.use_ada_layer_norm_zero:
263
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
264
+
265
+ hidden_states = ff_output + hidden_states
266
+
267
+ return hidden_states
268
+
269
+ if self.reference_attn:
270
+ if self.fusion_blocks == "midup":
271
+ attn_modules = [
272
+ module
273
+ for module in (
274
+ torch_dfs(self.unet.mid_block) + torch_dfs(self.unet.up_blocks)
275
+ )
276
+ if isinstance(module, BasicTransformerBlock)
277
+ or isinstance(module, TemporalBasicTransformerBlock)
278
+ ]
279
+ elif self.fusion_blocks == "full":
280
+ attn_modules = [
281
+ module
282
+ for module in torch_dfs(self.unet)
283
+ if isinstance(module, BasicTransformerBlock)
284
+ or isinstance(module, TemporalBasicTransformerBlock)
285
+ ]
286
+ attn_modules = sorted(
287
+ attn_modules, key=lambda x: -x.norm1.normalized_shape[0]
288
+ )
289
+
290
+ for i, module in enumerate(attn_modules):
291
+ module._original_inner_forward = module.forward
292
+ if isinstance(module, BasicTransformerBlock):
293
+ module.forward = hacked_basic_transformer_inner_forward.__get__(
294
+ module, BasicTransformerBlock
295
+ )
296
+ if isinstance(module, TemporalBasicTransformerBlock):
297
+ module.forward = hacked_basic_transformer_inner_forward.__get__(
298
+ module, TemporalBasicTransformerBlock
299
+ )
300
+
301
+ module.bank = []
302
+ module.attn_weight = float(i) / float(len(attn_modules))
303
+
304
+ def update(self, writer, dtype=torch.float16):
305
+ if self.reference_attn:
306
+ if self.fusion_blocks == "midup":
307
+ reader_attn_modules = [
308
+ module
309
+ for module in (
310
+ torch_dfs(self.unet.mid_block) + torch_dfs(self.unet.up_blocks)
311
+ )
312
+ if isinstance(module, TemporalBasicTransformerBlock)
313
+ ]
314
+ writer_attn_modules = [
315
+ module
316
+ for module in (
317
+ torch_dfs(writer.unet.mid_block)
318
+ + torch_dfs(writer.unet.up_blocks)
319
+ )
320
+ if isinstance(module, BasicTransformerBlock)
321
+ ]
322
+ elif self.fusion_blocks == "full":
323
+ reader_attn_modules = [
324
+ module
325
+ for module in torch_dfs(self.unet)
326
+ if isinstance(module, TemporalBasicTransformerBlock)
327
+ ]
328
+ writer_attn_modules = [
329
+ module
330
+ for module in torch_dfs(writer.unet)
331
+ if isinstance(module, BasicTransformerBlock)
332
+ ]
333
+ reader_attn_modules = sorted(
334
+ reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]
335
+ )
336
+ writer_attn_modules = sorted(
337
+ writer_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]
338
+ )
339
+ for r, w in zip(reader_attn_modules, writer_attn_modules):
340
+ r.bank = [v.clone().to(dtype) for v in w.bank]
341
+ # w.bank.clear()
342
+
343
+ def clear(self):
344
+ if self.reference_attn:
345
+ if self.fusion_blocks == "midup":
346
+ reader_attn_modules = [
347
+ module
348
+ for module in (
349
+ torch_dfs(self.unet.mid_block) + torch_dfs(self.unet.up_blocks)
350
+ )
351
+ if isinstance(module, BasicTransformerBlock)
352
+ or isinstance(module, TemporalBasicTransformerBlock)
353
+ ]
354
+ elif self.fusion_blocks == "full":
355
+ reader_attn_modules = [
356
+ module
357
+ for module in torch_dfs(self.unet)
358
+ if isinstance(module, BasicTransformerBlock)
359
+ or isinstance(module, TemporalBasicTransformerBlock)
360
+ ]
361
+ reader_attn_modules = sorted(
362
+ reader_attn_modules, key=lambda x: -x.norm1.normalized_shape[0]
363
+ )
364
+ for r in reader_attn_modules:
365
+ r.bank.clear()
2610_variant_runtime/diffusion/models/pose_guider.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Tuple
2
+
3
+ import torch.nn as nn
4
+ import torch.nn.functional as F
5
+ import torch.nn.init as init
6
+ from diffusers.models.modeling_utils import ModelMixin
7
+
8
+ from models.motion_module import zero_module
9
+ from models.resnet import InflatedConv3d
10
+
11
+
12
+ class PoseGuider(ModelMixin):
13
+ def __init__(
14
+ self,
15
+ conditioning_embedding_channels: int,
16
+ conditioning_channels: int = 3,
17
+ block_out_channels: Tuple[int] = (16, 32, 64, 128),
18
+ ):
19
+ super().__init__()
20
+ self.conv_in = InflatedConv3d(
21
+ conditioning_channels, block_out_channels[0], kernel_size=3, padding=1
22
+ )
23
+
24
+ self.blocks = nn.ModuleList([])
25
+
26
+ for i in range(len(block_out_channels) - 1):
27
+ channel_in = block_out_channels[i]
28
+ channel_out = block_out_channels[i + 1]
29
+ self.blocks.append(
30
+ InflatedConv3d(channel_in, channel_in, kernel_size=3, padding=1)
31
+ )
32
+ self.blocks.append(
33
+ InflatedConv3d(
34
+ channel_in, channel_out, kernel_size=3, padding=1, stride=2
35
+ )
36
+ )
37
+
38
+ self.conv_out = zero_module(
39
+ InflatedConv3d(
40
+ block_out_channels[-1],
41
+ conditioning_embedding_channels,
42
+ kernel_size=3,
43
+ padding=1,
44
+ )
45
+ )
46
+
47
+ def forward(self, conditioning):
48
+ embedding = self.conv_in(conditioning)
49
+ embedding = F.silu(embedding)
50
+
51
+ for block in self.blocks:
52
+ embedding = block(embedding)
53
+ embedding = F.silu(embedding)
54
+
55
+ embedding = self.conv_out(embedding)
56
+
57
+ return embedding
2610_variant_runtime/diffusion/models/resnet.py ADDED
@@ -0,0 +1,252 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/resnet.py
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ from einops import rearrange
7
+
8
+
9
+ class InflatedConv3d(nn.Conv2d):
10
+ def forward(self, x):
11
+ video_length = x.shape[2]
12
+
13
+ x = rearrange(x, "b c f h w -> (b f) c h w")
14
+ x = super().forward(x)
15
+ x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
16
+
17
+ return x
18
+
19
+
20
+ class InflatedGroupNorm(nn.GroupNorm):
21
+ def forward(self, x):
22
+ video_length = x.shape[2]
23
+
24
+ x = rearrange(x, "b c f h w -> (b f) c h w")
25
+ x = super().forward(x)
26
+ x = rearrange(x, "(b f) c h w -> b c f h w", f=video_length)
27
+
28
+ return x
29
+
30
+
31
+ class Upsample3D(nn.Module):
32
+ def __init__(
33
+ self,
34
+ channels,
35
+ use_conv=False,
36
+ use_conv_transpose=False,
37
+ out_channels=None,
38
+ name="conv",
39
+ ):
40
+ super().__init__()
41
+ self.channels = channels
42
+ self.out_channels = out_channels or channels
43
+ self.use_conv = use_conv
44
+ self.use_conv_transpose = use_conv_transpose
45
+ self.name = name
46
+
47
+ conv = None
48
+ if use_conv_transpose:
49
+ raise NotImplementedError
50
+ elif use_conv:
51
+ self.conv = InflatedConv3d(self.channels, self.out_channels, 3, padding=1)
52
+
53
+ def forward(self, hidden_states, output_size=None):
54
+ assert hidden_states.shape[1] == self.channels
55
+
56
+ if self.use_conv_transpose:
57
+ raise NotImplementedError
58
+
59
+ # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
60
+ dtype = hidden_states.dtype
61
+ if dtype == torch.bfloat16:
62
+ hidden_states = hidden_states.to(torch.float32)
63
+
64
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
65
+ if hidden_states.shape[0] >= 64:
66
+ hidden_states = hidden_states.contiguous()
67
+
68
+ # if `output_size` is passed we force the interpolation output
69
+ # size and do not make use of `scale_factor=2`
70
+ if output_size is None:
71
+ hidden_states = F.interpolate(
72
+ hidden_states, scale_factor=[1.0, 2.0, 2.0], mode="nearest"
73
+ )
74
+ else:
75
+ hidden_states = F.interpolate(
76
+ hidden_states, size=output_size, mode="nearest"
77
+ )
78
+
79
+ # If the input is bfloat16, we cast back to bfloat16
80
+ if dtype == torch.bfloat16:
81
+ hidden_states = hidden_states.to(dtype)
82
+
83
+ # if self.use_conv:
84
+ # if self.name == "conv":
85
+ # hidden_states = self.conv(hidden_states)
86
+ # else:
87
+ # hidden_states = self.Conv2d_0(hidden_states)
88
+ hidden_states = self.conv(hidden_states)
89
+
90
+ return hidden_states
91
+
92
+
93
+ class Downsample3D(nn.Module):
94
+ def __init__(
95
+ self, channels, use_conv=False, out_channels=None, padding=1, name="conv"
96
+ ):
97
+ super().__init__()
98
+ self.channels = channels
99
+ self.out_channels = out_channels or channels
100
+ self.use_conv = use_conv
101
+ self.padding = padding
102
+ stride = 2
103
+ self.name = name
104
+
105
+ if use_conv:
106
+ self.conv = InflatedConv3d(
107
+ self.channels, self.out_channels, 3, stride=stride, padding=padding
108
+ )
109
+ else:
110
+ raise NotImplementedError
111
+
112
+ def forward(self, hidden_states):
113
+ assert hidden_states.shape[1] == self.channels
114
+ if self.use_conv and self.padding == 0:
115
+ raise NotImplementedError
116
+
117
+ assert hidden_states.shape[1] == self.channels
118
+ hidden_states = self.conv(hidden_states)
119
+
120
+ return hidden_states
121
+
122
+
123
+ class ResnetBlock3D(nn.Module):
124
+ def __init__(
125
+ self,
126
+ *,
127
+ in_channels,
128
+ out_channels=None,
129
+ conv_shortcut=False,
130
+ dropout=0.0,
131
+ temb_channels=512,
132
+ groups=32,
133
+ groups_out=None,
134
+ pre_norm=True,
135
+ eps=1e-6,
136
+ non_linearity="swish",
137
+ time_embedding_norm="default",
138
+ output_scale_factor=1.0,
139
+ use_in_shortcut=None,
140
+ use_inflated_groupnorm=None,
141
+ ):
142
+ super().__init__()
143
+ self.pre_norm = pre_norm
144
+ self.pre_norm = True
145
+ self.in_channels = in_channels
146
+ out_channels = in_channels if out_channels is None else out_channels
147
+ self.out_channels = out_channels
148
+ self.use_conv_shortcut = conv_shortcut
149
+ self.time_embedding_norm = time_embedding_norm
150
+ self.output_scale_factor = output_scale_factor
151
+
152
+ if groups_out is None:
153
+ groups_out = groups
154
+
155
+ assert use_inflated_groupnorm != None
156
+ if use_inflated_groupnorm:
157
+ self.norm1 = InflatedGroupNorm(
158
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
159
+ )
160
+ else:
161
+ self.norm1 = torch.nn.GroupNorm(
162
+ num_groups=groups, num_channels=in_channels, eps=eps, affine=True
163
+ )
164
+
165
+ self.conv1 = InflatedConv3d(
166
+ in_channels, out_channels, kernel_size=3, stride=1, padding=1
167
+ )
168
+
169
+ if temb_channels is not None:
170
+ if self.time_embedding_norm == "default":
171
+ time_emb_proj_out_channels = out_channels
172
+ elif self.time_embedding_norm == "scale_shift":
173
+ time_emb_proj_out_channels = out_channels * 2
174
+ else:
175
+ raise ValueError(
176
+ f"unknown time_embedding_norm : {self.time_embedding_norm} "
177
+ )
178
+
179
+ self.time_emb_proj = torch.nn.Linear(
180
+ temb_channels, time_emb_proj_out_channels
181
+ )
182
+ else:
183
+ self.time_emb_proj = None
184
+
185
+ if use_inflated_groupnorm:
186
+ self.norm2 = InflatedGroupNorm(
187
+ num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True
188
+ )
189
+ else:
190
+ self.norm2 = torch.nn.GroupNorm(
191
+ num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True
192
+ )
193
+ self.dropout = torch.nn.Dropout(dropout)
194
+ self.conv2 = InflatedConv3d(
195
+ out_channels, out_channels, kernel_size=3, stride=1, padding=1
196
+ )
197
+
198
+ if non_linearity == "swish":
199
+ self.nonlinearity = lambda x: F.silu(x)
200
+ elif non_linearity == "mish":
201
+ self.nonlinearity = Mish()
202
+ elif non_linearity == "silu":
203
+ self.nonlinearity = nn.SiLU()
204
+
205
+ self.use_in_shortcut = (
206
+ self.in_channels != self.out_channels
207
+ if use_in_shortcut is None
208
+ else use_in_shortcut
209
+ )
210
+
211
+ self.conv_shortcut = None
212
+ if self.use_in_shortcut:
213
+ self.conv_shortcut = InflatedConv3d(
214
+ in_channels, out_channels, kernel_size=1, stride=1, padding=0
215
+ )
216
+
217
+ def forward(self, input_tensor, temb):
218
+ hidden_states = input_tensor
219
+
220
+ hidden_states = self.norm1(hidden_states)
221
+ hidden_states = self.nonlinearity(hidden_states)
222
+
223
+ hidden_states = self.conv1(hidden_states)
224
+
225
+ if temb is not None:
226
+ temb = self.time_emb_proj(self.nonlinearity(temb))[:, :, None, None, None]
227
+
228
+ if temb is not None and self.time_embedding_norm == "default":
229
+ hidden_states = hidden_states + temb
230
+
231
+ hidden_states = self.norm2(hidden_states)
232
+
233
+ if temb is not None and self.time_embedding_norm == "scale_shift":
234
+ scale, shift = torch.chunk(temb, 2, dim=1)
235
+ hidden_states = hidden_states * (1 + scale) + shift
236
+
237
+ hidden_states = self.nonlinearity(hidden_states)
238
+
239
+ hidden_states = self.dropout(hidden_states)
240
+ hidden_states = self.conv2(hidden_states)
241
+
242
+ if self.conv_shortcut is not None:
243
+ input_tensor = self.conv_shortcut(input_tensor)
244
+
245
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
246
+
247
+ return output_tensor
248
+
249
+
250
+ class Mish(torch.nn.Module):
251
+ def forward(self, hidden_states):
252
+ return hidden_states * torch.tanh(torch.nn.functional.softplus(hidden_states))
2610_variant_runtime/diffusion/models/transformer_2d.py ADDED
@@ -0,0 +1,396 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/transformer_2d.py
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict, Optional
4
+
5
+ import torch
6
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
7
+ from diffusers.models.embeddings import CaptionProjection
8
+ from diffusers.models.lora import LoRACompatibleConv, LoRACompatibleLinear
9
+ from diffusers.models.modeling_utils import ModelMixin
10
+ from diffusers.models.normalization import AdaLayerNormSingle
11
+ from diffusers.utils import USE_PEFT_BACKEND, BaseOutput, deprecate, is_torch_version
12
+ from torch import nn
13
+
14
+ from .attention import BasicTransformerBlock
15
+
16
+
17
+ @dataclass
18
+ class Transformer2DModelOutput(BaseOutput):
19
+ """
20
+ The output of [`Transformer2DModel`].
21
+
22
+ Args:
23
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
24
+ The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
25
+ distributions for the unnoised latent pixels.
26
+ """
27
+
28
+ sample: torch.FloatTensor
29
+ ref_feature: torch.FloatTensor
30
+
31
+
32
+ class Transformer2DModel(ModelMixin, ConfigMixin):
33
+ """
34
+ A 2D Transformer model for image-like data.
35
+
36
+ Parameters:
37
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
38
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
39
+ in_channels (`int`, *optional*):
40
+ The number of channels in the input and output (specify if the input is **continuous**).
41
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
42
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
43
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
44
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
45
+ This is fixed during training since it is used to learn a number of position embeddings.
46
+ num_vector_embeds (`int`, *optional*):
47
+ The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
48
+ Includes the class for the masked latent pixel.
49
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
50
+ num_embeds_ada_norm ( `int`, *optional*):
51
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
52
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
53
+ added to the hidden states.
54
+
55
+ During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
56
+ attention_bias (`bool`, *optional*):
57
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
58
+ """
59
+
60
+ _supports_gradient_checkpointing = True
61
+
62
+ @register_to_config
63
+ def __init__(
64
+ self,
65
+ num_attention_heads: int = 16,
66
+ attention_head_dim: int = 88,
67
+ in_channels: Optional[int] = None,
68
+ out_channels: Optional[int] = None,
69
+ num_layers: int = 1,
70
+ dropout: float = 0.0,
71
+ norm_num_groups: int = 32,
72
+ cross_attention_dim: Optional[int] = None,
73
+ attention_bias: bool = False,
74
+ sample_size: Optional[int] = None,
75
+ num_vector_embeds: Optional[int] = None,
76
+ patch_size: Optional[int] = None,
77
+ activation_fn: str = "geglu",
78
+ num_embeds_ada_norm: Optional[int] = None,
79
+ use_linear_projection: bool = False,
80
+ only_cross_attention: bool = False,
81
+ double_self_attention: bool = False,
82
+ upcast_attention: bool = False,
83
+ norm_type: str = "layer_norm",
84
+ norm_elementwise_affine: bool = True,
85
+ norm_eps: float = 1e-5,
86
+ attention_type: str = "default",
87
+ caption_channels: int = None,
88
+ ):
89
+ super().__init__()
90
+ self.use_linear_projection = use_linear_projection
91
+ self.num_attention_heads = num_attention_heads
92
+ self.attention_head_dim = attention_head_dim
93
+ inner_dim = num_attention_heads * attention_head_dim
94
+
95
+ conv_cls = nn.Conv2d if USE_PEFT_BACKEND else LoRACompatibleConv
96
+ linear_cls = nn.Linear if USE_PEFT_BACKEND else LoRACompatibleLinear
97
+
98
+ # 1. Transformer2DModel can process both standard continuous images of shape `(batch_size, num_channels, width, height)` as well as quantized image embeddings of shape `(batch_size, num_image_vectors)`
99
+ # Define whether input is continuous or discrete depending on configuration
100
+ self.is_input_continuous = (in_channels is not None) and (patch_size is None)
101
+ self.is_input_vectorized = num_vector_embeds is not None
102
+ self.is_input_patches = in_channels is not None and patch_size is not None
103
+
104
+ if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
105
+ deprecation_message = (
106
+ f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
107
+ " incorrectly set to `'layer_norm'`.Make sure to set `norm_type` to `'ada_norm'` in the config."
108
+ " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
109
+ " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
110
+ " would be very nice if you could open a Pull request for the `transformer/config.json` file"
111
+ )
112
+ deprecate(
113
+ "norm_type!=num_embeds_ada_norm",
114
+ "1.0.0",
115
+ deprecation_message,
116
+ standard_warn=False,
117
+ )
118
+ norm_type = "ada_norm"
119
+
120
+ if self.is_input_continuous and self.is_input_vectorized:
121
+ raise ValueError(
122
+ f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
123
+ " sure that either `in_channels` or `num_vector_embeds` is None."
124
+ )
125
+ elif self.is_input_vectorized and self.is_input_patches:
126
+ raise ValueError(
127
+ f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
128
+ " sure that either `num_vector_embeds` or `num_patches` is None."
129
+ )
130
+ elif (
131
+ not self.is_input_continuous
132
+ and not self.is_input_vectorized
133
+ and not self.is_input_patches
134
+ ):
135
+ raise ValueError(
136
+ f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
137
+ f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
138
+ )
139
+
140
+ # 2. Define input layers
141
+ self.in_channels = in_channels
142
+
143
+ self.norm = torch.nn.GroupNorm(
144
+ num_groups=norm_num_groups,
145
+ num_channels=in_channels,
146
+ eps=1e-6,
147
+ affine=True,
148
+ )
149
+ if use_linear_projection:
150
+ self.proj_in = linear_cls(in_channels, inner_dim)
151
+ else:
152
+ self.proj_in = conv_cls(
153
+ in_channels, inner_dim, kernel_size=1, stride=1, padding=0
154
+ )
155
+
156
+ # 3. Define transformers blocks
157
+ self.transformer_blocks = nn.ModuleList(
158
+ [
159
+ BasicTransformerBlock(
160
+ inner_dim,
161
+ num_attention_heads,
162
+ attention_head_dim,
163
+ dropout=dropout,
164
+ cross_attention_dim=cross_attention_dim,
165
+ activation_fn=activation_fn,
166
+ num_embeds_ada_norm=num_embeds_ada_norm,
167
+ attention_bias=attention_bias,
168
+ only_cross_attention=only_cross_attention,
169
+ double_self_attention=double_self_attention,
170
+ upcast_attention=upcast_attention,
171
+ norm_type=norm_type,
172
+ norm_elementwise_affine=norm_elementwise_affine,
173
+ norm_eps=norm_eps,
174
+ attention_type=attention_type,
175
+ )
176
+ for d in range(num_layers)
177
+ ]
178
+ )
179
+
180
+ # 4. Define output layers
181
+ self.out_channels = in_channels if out_channels is None else out_channels
182
+ # TODO: should use out_channels for continuous projections
183
+ if use_linear_projection:
184
+ self.proj_out = linear_cls(inner_dim, in_channels)
185
+ else:
186
+ self.proj_out = conv_cls(
187
+ inner_dim, in_channels, kernel_size=1, stride=1, padding=0
188
+ )
189
+
190
+ # 5. PixArt-Alpha blocks.
191
+ self.adaln_single = None
192
+ self.use_additional_conditions = False
193
+ if norm_type == "ada_norm_single":
194
+ self.use_additional_conditions = self.config.sample_size == 128
195
+ # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
196
+ # additional conditions until we find better name
197
+ self.adaln_single = AdaLayerNormSingle(
198
+ inner_dim, use_additional_conditions=self.use_additional_conditions
199
+ )
200
+
201
+ self.caption_projection = None
202
+ if caption_channels is not None:
203
+ self.caption_projection = CaptionProjection(
204
+ in_features=caption_channels, hidden_size=inner_dim
205
+ )
206
+
207
+ self.gradient_checkpointing = False
208
+
209
+ def _set_gradient_checkpointing(self, module, value=False):
210
+ if hasattr(module, "gradient_checkpointing"):
211
+ module.gradient_checkpointing = value
212
+
213
+ def forward(
214
+ self,
215
+ hidden_states: torch.Tensor,
216
+ encoder_hidden_states: Optional[torch.Tensor] = None,
217
+ timestep: Optional[torch.LongTensor] = None,
218
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
219
+ class_labels: Optional[torch.LongTensor] = None,
220
+ cross_attention_kwargs: Dict[str, Any] = None,
221
+ attention_mask: Optional[torch.Tensor] = None,
222
+ encoder_attention_mask: Optional[torch.Tensor] = None,
223
+ return_dict: bool = True,
224
+ ):
225
+ """
226
+ The [`Transformer2DModel`] forward method.
227
+
228
+ Args:
229
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
230
+ Input `hidden_states`.
231
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
232
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
233
+ self-attention.
234
+ timestep ( `torch.LongTensor`, *optional*):
235
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
236
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
237
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
238
+ `AdaLayerZeroNorm`.
239
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
240
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
241
+ `self.processor` in
242
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
243
+ attention_mask ( `torch.Tensor`, *optional*):
244
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
245
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
246
+ negative values to the attention scores corresponding to "discard" tokens.
247
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
248
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
249
+
250
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
251
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
252
+
253
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
254
+ above. This bias will be added to the cross-attention scores.
255
+ return_dict (`bool`, *optional*, defaults to `True`):
256
+ Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
257
+ tuple.
258
+
259
+ Returns:
260
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
261
+ `tuple` where the first element is the sample tensor.
262
+ """
263
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
264
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
265
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
266
+ # expects mask of shape:
267
+ # [batch, key_tokens]
268
+ # adds singleton query_tokens dimension:
269
+ # [batch, 1, key_tokens]
270
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
271
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
272
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
273
+ if attention_mask is not None and attention_mask.ndim == 2:
274
+ # assume that mask is expressed as:
275
+ # (1 = keep, 0 = discard)
276
+ # convert mask into a bias that can be added to attention scores:
277
+ # (keep = +0, discard = -10000.0)
278
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
279
+ attention_mask = attention_mask.unsqueeze(1)
280
+
281
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
282
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
283
+ encoder_attention_mask = (
284
+ 1 - encoder_attention_mask.to(hidden_states.dtype)
285
+ ) * -10000.0
286
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
287
+
288
+ # Retrieve lora scale.
289
+ lora_scale = (
290
+ cross_attention_kwargs.get("scale", 1.0)
291
+ if cross_attention_kwargs is not None
292
+ else 1.0
293
+ )
294
+
295
+ # 1. Input
296
+ batch, _, height, width = hidden_states.shape
297
+ residual = hidden_states
298
+
299
+ hidden_states = self.norm(hidden_states)
300
+ if not self.use_linear_projection:
301
+ hidden_states = (
302
+ self.proj_in(hidden_states, scale=lora_scale)
303
+ if not USE_PEFT_BACKEND
304
+ else self.proj_in(hidden_states)
305
+ )
306
+ inner_dim = hidden_states.shape[1]
307
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
308
+ batch, height * width, inner_dim
309
+ )
310
+ else:
311
+ inner_dim = hidden_states.shape[1]
312
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
313
+ batch, height * width, inner_dim
314
+ )
315
+ hidden_states = (
316
+ self.proj_in(hidden_states, scale=lora_scale)
317
+ if not USE_PEFT_BACKEND
318
+ else self.proj_in(hidden_states)
319
+ )
320
+
321
+ # 2. Blocks
322
+ if self.caption_projection is not None:
323
+ batch_size = hidden_states.shape[0]
324
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
325
+ encoder_hidden_states = encoder_hidden_states.view(
326
+ batch_size, -1, hidden_states.shape[-1]
327
+ )
328
+
329
+ ref_feature = hidden_states.reshape(batch, height, width, inner_dim)
330
+ for block in self.transformer_blocks:
331
+ if self.training and self.gradient_checkpointing:
332
+
333
+ def create_custom_forward(module, return_dict=None):
334
+ def custom_forward(*inputs):
335
+ if return_dict is not None:
336
+ return module(*inputs, return_dict=return_dict)
337
+ else:
338
+ return module(*inputs)
339
+
340
+ return custom_forward
341
+
342
+ ckpt_kwargs: Dict[str, Any] = (
343
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
344
+ )
345
+ hidden_states = torch.utils.checkpoint.checkpoint(
346
+ create_custom_forward(block),
347
+ hidden_states,
348
+ attention_mask,
349
+ encoder_hidden_states,
350
+ encoder_attention_mask,
351
+ timestep,
352
+ cross_attention_kwargs,
353
+ class_labels,
354
+ **ckpt_kwargs,
355
+ )
356
+ else:
357
+ hidden_states = block(
358
+ hidden_states,
359
+ attention_mask=attention_mask,
360
+ encoder_hidden_states=encoder_hidden_states,
361
+ encoder_attention_mask=encoder_attention_mask,
362
+ timestep=timestep,
363
+ cross_attention_kwargs=cross_attention_kwargs,
364
+ class_labels=class_labels,
365
+ )
366
+
367
+ # 3. Output
368
+ if self.is_input_continuous:
369
+ if not self.use_linear_projection:
370
+ hidden_states = (
371
+ hidden_states.reshape(batch, height, width, inner_dim)
372
+ .permute(0, 3, 1, 2)
373
+ .contiguous()
374
+ )
375
+ hidden_states = (
376
+ self.proj_out(hidden_states, scale=lora_scale)
377
+ if not USE_PEFT_BACKEND
378
+ else self.proj_out(hidden_states)
379
+ )
380
+ else:
381
+ hidden_states = (
382
+ self.proj_out(hidden_states, scale=lora_scale)
383
+ if not USE_PEFT_BACKEND
384
+ else self.proj_out(hidden_states)
385
+ )
386
+ hidden_states = (
387
+ hidden_states.reshape(batch, height, width, inner_dim)
388
+ .permute(0, 3, 1, 2)
389
+ .contiguous()
390
+ )
391
+
392
+ output = hidden_states + residual
393
+ if not return_dict:
394
+ return (output, ref_feature)
395
+
396
+ return Transformer2DModelOutput(sample=output, ref_feature=ref_feature)
2610_variant_runtime/diffusion/models/transformer_3d.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Optional
3
+
4
+ import torch
5
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
6
+ from diffusers.models import ModelMixin
7
+ from diffusers.utils import BaseOutput
8
+ from diffusers.utils.import_utils import is_xformers_available
9
+ from einops import rearrange, repeat
10
+ from torch import nn
11
+
12
+ from .attention import TemporalBasicTransformerBlock
13
+
14
+
15
+ @dataclass
16
+ class Transformer3DModelOutput(BaseOutput):
17
+ sample: torch.FloatTensor
18
+
19
+
20
+ if is_xformers_available():
21
+ import xformers
22
+ import xformers.ops
23
+ else:
24
+ xformers = None
25
+
26
+
27
+ class Transformer3DModel(ModelMixin, ConfigMixin):
28
+ _supports_gradient_checkpointing = True
29
+
30
+ @register_to_config
31
+ def __init__(
32
+ self,
33
+ num_attention_heads: int = 16,
34
+ attention_head_dim: int = 88,
35
+ in_channels: Optional[int] = None,
36
+ num_layers: int = 1,
37
+ dropout: float = 0.0,
38
+ norm_num_groups: int = 32,
39
+ cross_attention_dim: Optional[int] = None,
40
+ attention_bias: bool = False,
41
+ activation_fn: str = "geglu",
42
+ num_embeds_ada_norm: Optional[int] = None,
43
+ use_linear_projection: bool = False,
44
+ only_cross_attention: bool = False,
45
+ upcast_attention: bool = False,
46
+ unet_use_cross_frame_attention=None,
47
+ unet_use_temporal_attention=None,
48
+ ):
49
+ super().__init__()
50
+ self.use_linear_projection = use_linear_projection
51
+ self.num_attention_heads = num_attention_heads
52
+ self.attention_head_dim = attention_head_dim
53
+ inner_dim = num_attention_heads * attention_head_dim
54
+
55
+ # Define input layers
56
+ self.in_channels = in_channels
57
+
58
+ self.norm = torch.nn.GroupNorm(
59
+ num_groups=norm_num_groups, num_channels=in_channels, eps=1e-6, affine=True
60
+ )
61
+ if use_linear_projection:
62
+ self.proj_in = nn.Linear(in_channels, inner_dim)
63
+ else:
64
+ self.proj_in = nn.Conv2d(
65
+ in_channels, inner_dim, kernel_size=1, stride=1, padding=0
66
+ )
67
+
68
+ # Define transformers blocks
69
+ self.transformer_blocks = nn.ModuleList(
70
+ [
71
+ TemporalBasicTransformerBlock(
72
+ inner_dim,
73
+ num_attention_heads,
74
+ attention_head_dim,
75
+ dropout=dropout,
76
+ cross_attention_dim=cross_attention_dim,
77
+ activation_fn=activation_fn,
78
+ num_embeds_ada_norm=num_embeds_ada_norm,
79
+ attention_bias=attention_bias,
80
+ only_cross_attention=only_cross_attention,
81
+ upcast_attention=upcast_attention,
82
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
83
+ unet_use_temporal_attention=unet_use_temporal_attention,
84
+ )
85
+ for d in range(num_layers)
86
+ ]
87
+ )
88
+
89
+ # 4. Define output layers
90
+ if use_linear_projection:
91
+ self.proj_out = nn.Linear(in_channels, inner_dim)
92
+ else:
93
+ self.proj_out = nn.Conv2d(
94
+ inner_dim, in_channels, kernel_size=1, stride=1, padding=0
95
+ )
96
+
97
+ self.gradient_checkpointing = False
98
+
99
+ def _set_gradient_checkpointing(self, module, value=False):
100
+ if hasattr(module, "gradient_checkpointing"):
101
+ module.gradient_checkpointing = value
102
+
103
+ def forward(
104
+ self,
105
+ hidden_states,
106
+ encoder_hidden_states=None,
107
+ timestep=None,
108
+ return_dict: bool = True,
109
+ ):
110
+ # Input
111
+ assert (
112
+ hidden_states.dim() == 5
113
+ ), f"Expected hidden_states to have ndim=5, but got ndim={hidden_states.dim()}."
114
+ video_length = hidden_states.shape[2]
115
+ hidden_states = rearrange(hidden_states, "b c f h w -> (b f) c h w")
116
+ if encoder_hidden_states is not None:
117
+ if encoder_hidden_states.shape[0] != hidden_states.shape[0]:
118
+ encoder_hidden_states = repeat(
119
+ encoder_hidden_states, "b n c -> (b f) n c", f=video_length
120
+ )
121
+
122
+ batch, channel, height, weight = hidden_states.shape
123
+ residual = hidden_states
124
+
125
+ hidden_states = self.norm(hidden_states)
126
+ if not self.use_linear_projection:
127
+ hidden_states = self.proj_in(hidden_states)
128
+ inner_dim = hidden_states.shape[1]
129
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
130
+ batch, height * weight, inner_dim
131
+ )
132
+ else:
133
+ inner_dim = hidden_states.shape[1]
134
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
135
+ batch, height * weight, inner_dim
136
+ )
137
+ hidden_states = self.proj_in(hidden_states)
138
+
139
+ # Blocks
140
+ for i, block in enumerate(self.transformer_blocks):
141
+ hidden_states = block(
142
+ hidden_states,
143
+ encoder_hidden_states=encoder_hidden_states,
144
+ timestep=timestep,
145
+ video_length=video_length,
146
+ )
147
+
148
+ # Output
149
+ if not self.use_linear_projection:
150
+ hidden_states = (
151
+ hidden_states.reshape(batch, height, weight, inner_dim)
152
+ .permute(0, 3, 1, 2)
153
+ .contiguous()
154
+ )
155
+ hidden_states = self.proj_out(hidden_states)
156
+ else:
157
+ hidden_states = self.proj_out(hidden_states)
158
+ hidden_states = (
159
+ hidden_states.reshape(batch, height, weight, inner_dim)
160
+ .permute(0, 3, 1, 2)
161
+ .contiguous()
162
+ )
163
+
164
+ output = hidden_states + residual
165
+
166
+ output = rearrange(output, "(b f) c h w -> b c f h w", f=video_length)
167
+ if not return_dict:
168
+ return (output,)
169
+
170
+ return Transformer3DModelOutput(sample=output)
2610_variant_runtime/diffusion/models/unet_2d_blocks.py ADDED
@@ -0,0 +1,1076 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py
2
+ from typing import Any, Dict, Optional, Tuple, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+ import torch.nn.functional as F
7
+ from diffusers.models.activations import get_activation
8
+ from diffusers.models.attention_processor import Attention
9
+ from diffusers.models.dual_transformer_2d import DualTransformer2DModel
10
+ from diffusers.models.resnet import Downsample2D, ResnetBlock2D, Upsample2D
11
+ from diffusers.utils import is_torch_version, logging
12
+ from diffusers.utils.torch_utils import apply_freeu
13
+ from torch import nn
14
+
15
+ from .transformer_2d import Transformer2DModel
16
+
17
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
18
+
19
+
20
+ def get_down_block(
21
+ down_block_type: str,
22
+ num_layers: int,
23
+ in_channels: int,
24
+ out_channels: int,
25
+ temb_channels: int,
26
+ add_downsample: bool,
27
+ resnet_eps: float,
28
+ resnet_act_fn: str,
29
+ transformer_layers_per_block: int = 1,
30
+ num_attention_heads: Optional[int] = None,
31
+ resnet_groups: Optional[int] = None,
32
+ cross_attention_dim: Optional[int] = None,
33
+ downsample_padding: Optional[int] = None,
34
+ dual_cross_attention: bool = False,
35
+ use_linear_projection: bool = False,
36
+ only_cross_attention: bool = False,
37
+ upcast_attention: bool = False,
38
+ resnet_time_scale_shift: str = "default",
39
+ attention_type: str = "default",
40
+ resnet_skip_time_act: bool = False,
41
+ resnet_out_scale_factor: float = 1.0,
42
+ cross_attention_norm: Optional[str] = None,
43
+ attention_head_dim: Optional[int] = None,
44
+ downsample_type: Optional[str] = None,
45
+ dropout: float = 0.0,
46
+ ):
47
+ # If attn head dim is not defined, we default it to the number of heads
48
+ if attention_head_dim is None:
49
+ logger.warn(
50
+ f"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
51
+ )
52
+ attention_head_dim = num_attention_heads
53
+
54
+ down_block_type = (
55
+ down_block_type[7:]
56
+ if down_block_type.startswith("UNetRes")
57
+ else down_block_type
58
+ )
59
+ if down_block_type == "DownBlock2D":
60
+ return DownBlock2D(
61
+ num_layers=num_layers,
62
+ in_channels=in_channels,
63
+ out_channels=out_channels,
64
+ temb_channels=temb_channels,
65
+ dropout=dropout,
66
+ add_downsample=add_downsample,
67
+ resnet_eps=resnet_eps,
68
+ resnet_act_fn=resnet_act_fn,
69
+ resnet_groups=resnet_groups,
70
+ downsample_padding=downsample_padding,
71
+ resnet_time_scale_shift=resnet_time_scale_shift,
72
+ )
73
+ elif down_block_type == "CrossAttnDownBlock2D":
74
+ if cross_attention_dim is None:
75
+ raise ValueError(
76
+ "cross_attention_dim must be specified for CrossAttnDownBlock2D"
77
+ )
78
+ return CrossAttnDownBlock2D(
79
+ num_layers=num_layers,
80
+ transformer_layers_per_block=transformer_layers_per_block,
81
+ in_channels=in_channels,
82
+ out_channels=out_channels,
83
+ temb_channels=temb_channels,
84
+ dropout=dropout,
85
+ add_downsample=add_downsample,
86
+ resnet_eps=resnet_eps,
87
+ resnet_act_fn=resnet_act_fn,
88
+ resnet_groups=resnet_groups,
89
+ downsample_padding=downsample_padding,
90
+ cross_attention_dim=cross_attention_dim,
91
+ num_attention_heads=num_attention_heads,
92
+ dual_cross_attention=dual_cross_attention,
93
+ use_linear_projection=use_linear_projection,
94
+ only_cross_attention=only_cross_attention,
95
+ upcast_attention=upcast_attention,
96
+ resnet_time_scale_shift=resnet_time_scale_shift,
97
+ attention_type=attention_type,
98
+ )
99
+ raise ValueError(f"{down_block_type} does not exist.")
100
+
101
+
102
+ def get_up_block(
103
+ up_block_type: str,
104
+ num_layers: int,
105
+ in_channels: int,
106
+ out_channels: int,
107
+ prev_output_channel: int,
108
+ temb_channels: int,
109
+ add_upsample: bool,
110
+ resnet_eps: float,
111
+ resnet_act_fn: str,
112
+ resolution_idx: Optional[int] = None,
113
+ transformer_layers_per_block: int = 1,
114
+ num_attention_heads: Optional[int] = None,
115
+ resnet_groups: Optional[int] = None,
116
+ cross_attention_dim: Optional[int] = None,
117
+ dual_cross_attention: bool = False,
118
+ use_linear_projection: bool = False,
119
+ only_cross_attention: bool = False,
120
+ upcast_attention: bool = False,
121
+ resnet_time_scale_shift: str = "default",
122
+ attention_type: str = "default",
123
+ resnet_skip_time_act: bool = False,
124
+ resnet_out_scale_factor: float = 1.0,
125
+ cross_attention_norm: Optional[str] = None,
126
+ attention_head_dim: Optional[int] = None,
127
+ upsample_type: Optional[str] = None,
128
+ dropout: float = 0.0,
129
+ ) -> nn.Module:
130
+ # If attn head dim is not defined, we default it to the number of heads
131
+ if attention_head_dim is None:
132
+ logger.warn(
133
+ f"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
134
+ )
135
+ attention_head_dim = num_attention_heads
136
+
137
+ up_block_type = (
138
+ up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
139
+ )
140
+ if up_block_type == "UpBlock2D":
141
+ return UpBlock2D(
142
+ num_layers=num_layers,
143
+ in_channels=in_channels,
144
+ out_channels=out_channels,
145
+ prev_output_channel=prev_output_channel,
146
+ temb_channels=temb_channels,
147
+ resolution_idx=resolution_idx,
148
+ dropout=dropout,
149
+ add_upsample=add_upsample,
150
+ resnet_eps=resnet_eps,
151
+ resnet_act_fn=resnet_act_fn,
152
+ resnet_groups=resnet_groups,
153
+ resnet_time_scale_shift=resnet_time_scale_shift,
154
+ )
155
+ elif up_block_type == "CrossAttnUpBlock2D":
156
+ if cross_attention_dim is None:
157
+ raise ValueError(
158
+ "cross_attention_dim must be specified for CrossAttnUpBlock2D"
159
+ )
160
+ return CrossAttnUpBlock2D(
161
+ num_layers=num_layers,
162
+ transformer_layers_per_block=transformer_layers_per_block,
163
+ in_channels=in_channels,
164
+ out_channels=out_channels,
165
+ prev_output_channel=prev_output_channel,
166
+ temb_channels=temb_channels,
167
+ resolution_idx=resolution_idx,
168
+ dropout=dropout,
169
+ add_upsample=add_upsample,
170
+ resnet_eps=resnet_eps,
171
+ resnet_act_fn=resnet_act_fn,
172
+ resnet_groups=resnet_groups,
173
+ cross_attention_dim=cross_attention_dim,
174
+ num_attention_heads=num_attention_heads,
175
+ dual_cross_attention=dual_cross_attention,
176
+ use_linear_projection=use_linear_projection,
177
+ only_cross_attention=only_cross_attention,
178
+ upcast_attention=upcast_attention,
179
+ resnet_time_scale_shift=resnet_time_scale_shift,
180
+ attention_type=attention_type,
181
+ )
182
+
183
+ raise ValueError(f"{up_block_type} does not exist.")
184
+
185
+
186
+ class AutoencoderTinyBlock(nn.Module):
187
+ """
188
+ Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU
189
+ blocks.
190
+
191
+ Args:
192
+ in_channels (`int`): The number of input channels.
193
+ out_channels (`int`): The number of output channels.
194
+ act_fn (`str`):
195
+ ` The activation function to use. Supported values are `"swish"`, `"mish"`, `"gelu"`, and `"relu"`.
196
+
197
+ Returns:
198
+ `torch.FloatTensor`: A tensor with the same shape as the input tensor, but with the number of channels equal to
199
+ `out_channels`.
200
+ """
201
+
202
+ def __init__(self, in_channels: int, out_channels: int, act_fn: str):
203
+ super().__init__()
204
+ act_fn = get_activation(act_fn)
205
+ self.conv = nn.Sequential(
206
+ nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
207
+ act_fn,
208
+ nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
209
+ act_fn,
210
+ nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
211
+ )
212
+ self.skip = (
213
+ nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
214
+ if in_channels != out_channels
215
+ else nn.Identity()
216
+ )
217
+ self.fuse = nn.ReLU()
218
+
219
+ def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
220
+ return self.fuse(self.conv(x) + self.skip(x))
221
+
222
+
223
+ class UNetMidBlock2D(nn.Module):
224
+ """
225
+ A 2D UNet mid-block [`UNetMidBlock2D`] with multiple residual blocks and optional attention blocks.
226
+
227
+ Args:
228
+ in_channels (`int`): The number of input channels.
229
+ temb_channels (`int`): The number of temporal embedding channels.
230
+ dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
231
+ num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
232
+ resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
233
+ resnet_time_scale_shift (`str`, *optional*, defaults to `default`):
234
+ The type of normalization to apply to the time embeddings. This can help to improve the performance of the
235
+ model on tasks with long-range temporal dependencies.
236
+ resnet_act_fn (`str`, *optional*, defaults to `swish`): The activation function for the resnet blocks.
237
+ resnet_groups (`int`, *optional*, defaults to 32):
238
+ The number of groups to use in the group normalization layers of the resnet blocks.
239
+ attn_groups (`Optional[int]`, *optional*, defaults to None): The number of groups for the attention blocks.
240
+ resnet_pre_norm (`bool`, *optional*, defaults to `True`):
241
+ Whether to use pre-normalization for the resnet blocks.
242
+ add_attention (`bool`, *optional*, defaults to `True`): Whether to add attention blocks.
243
+ attention_head_dim (`int`, *optional*, defaults to 1):
244
+ Dimension of a single attention head. The number of attention heads is determined based on this value and
245
+ the number of input channels.
246
+ output_scale_factor (`float`, *optional*, defaults to 1.0): The output scale factor.
247
+
248
+ Returns:
249
+ `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
250
+ in_channels, height, width)`.
251
+
252
+ """
253
+
254
+ def __init__(
255
+ self,
256
+ in_channels: int,
257
+ temb_channels: int,
258
+ dropout: float = 0.0,
259
+ num_layers: int = 1,
260
+ resnet_eps: float = 1e-6,
261
+ resnet_time_scale_shift: str = "default", # default, spatial
262
+ resnet_act_fn: str = "swish",
263
+ resnet_groups: int = 32,
264
+ attn_groups: Optional[int] = None,
265
+ resnet_pre_norm: bool = True,
266
+ add_attention: bool = True,
267
+ attention_head_dim: int = 1,
268
+ output_scale_factor: float = 1.0,
269
+ ):
270
+ super().__init__()
271
+ resnet_groups = (
272
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
273
+ )
274
+ self.add_attention = add_attention
275
+
276
+ if attn_groups is None:
277
+ attn_groups = (
278
+ resnet_groups if resnet_time_scale_shift == "default" else None
279
+ )
280
+
281
+ # there is always at least one resnet
282
+ resnets = [
283
+ ResnetBlock2D(
284
+ in_channels=in_channels,
285
+ out_channels=in_channels,
286
+ temb_channels=temb_channels,
287
+ eps=resnet_eps,
288
+ groups=resnet_groups,
289
+ dropout=dropout,
290
+ time_embedding_norm=resnet_time_scale_shift,
291
+ non_linearity=resnet_act_fn,
292
+ output_scale_factor=output_scale_factor,
293
+ pre_norm=resnet_pre_norm,
294
+ )
295
+ ]
296
+ attentions = []
297
+
298
+ if attention_head_dim is None:
299
+ logger.warn(
300
+ f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}."
301
+ )
302
+ attention_head_dim = in_channels
303
+
304
+ for _ in range(num_layers):
305
+ if self.add_attention:
306
+ attentions.append(
307
+ Attention(
308
+ in_channels,
309
+ heads=in_channels // attention_head_dim,
310
+ dim_head=attention_head_dim,
311
+ rescale_output_factor=output_scale_factor,
312
+ eps=resnet_eps,
313
+ norm_num_groups=attn_groups,
314
+ spatial_norm_dim=(
315
+ temb_channels
316
+ if resnet_time_scale_shift == "spatial"
317
+ else None
318
+ ),
319
+ residual_connection=True,
320
+ bias=True,
321
+ upcast_softmax=True,
322
+ _from_deprecated_attn_block=True,
323
+ )
324
+ )
325
+ else:
326
+ attentions.append(None)
327
+
328
+ resnets.append(
329
+ ResnetBlock2D(
330
+ in_channels=in_channels,
331
+ out_channels=in_channels,
332
+ temb_channels=temb_channels,
333
+ eps=resnet_eps,
334
+ groups=resnet_groups,
335
+ dropout=dropout,
336
+ time_embedding_norm=resnet_time_scale_shift,
337
+ non_linearity=resnet_act_fn,
338
+ output_scale_factor=output_scale_factor,
339
+ pre_norm=resnet_pre_norm,
340
+ )
341
+ )
342
+
343
+ self.attentions = nn.ModuleList(attentions)
344
+ self.resnets = nn.ModuleList(resnets)
345
+
346
+ def forward(
347
+ self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None
348
+ ) -> torch.FloatTensor:
349
+ hidden_states = self.resnets[0](hidden_states, temb)
350
+ for attn, resnet in zip(self.attentions, self.resnets[1:]):
351
+ if attn is not None:
352
+ hidden_states = attn(hidden_states, temb=temb)
353
+ hidden_states = resnet(hidden_states, temb)
354
+
355
+ return hidden_states
356
+
357
+
358
+ class UNetMidBlock2DCrossAttn(nn.Module):
359
+ def __init__(
360
+ self,
361
+ in_channels: int,
362
+ temb_channels: int,
363
+ dropout: float = 0.0,
364
+ num_layers: int = 1,
365
+ transformer_layers_per_block: Union[int, Tuple[int]] = 1,
366
+ resnet_eps: float = 1e-6,
367
+ resnet_time_scale_shift: str = "default",
368
+ resnet_act_fn: str = "swish",
369
+ resnet_groups: int = 32,
370
+ resnet_pre_norm: bool = True,
371
+ num_attention_heads: int = 1,
372
+ output_scale_factor: float = 1.0,
373
+ cross_attention_dim: int = 1280,
374
+ dual_cross_attention: bool = False,
375
+ use_linear_projection: bool = False,
376
+ upcast_attention: bool = False,
377
+ attention_type: str = "default",
378
+ ):
379
+ super().__init__()
380
+
381
+ self.has_cross_attention = True
382
+ self.num_attention_heads = num_attention_heads
383
+ resnet_groups = (
384
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
385
+ )
386
+
387
+ # support for variable transformer layers per block
388
+ if isinstance(transformer_layers_per_block, int):
389
+ transformer_layers_per_block = [transformer_layers_per_block] * num_layers
390
+
391
+ # there is always at least one resnet
392
+ resnets = [
393
+ ResnetBlock2D(
394
+ in_channels=in_channels,
395
+ out_channels=in_channels,
396
+ temb_channels=temb_channels,
397
+ eps=resnet_eps,
398
+ groups=resnet_groups,
399
+ dropout=dropout,
400
+ time_embedding_norm=resnet_time_scale_shift,
401
+ non_linearity=resnet_act_fn,
402
+ output_scale_factor=output_scale_factor,
403
+ pre_norm=resnet_pre_norm,
404
+ )
405
+ ]
406
+ attentions = []
407
+
408
+ for i in range(num_layers):
409
+ if not dual_cross_attention:
410
+ attentions.append(
411
+ Transformer2DModel(
412
+ num_attention_heads,
413
+ in_channels // num_attention_heads,
414
+ in_channels=in_channels,
415
+ num_layers=transformer_layers_per_block[i],
416
+ cross_attention_dim=cross_attention_dim,
417
+ norm_num_groups=resnet_groups,
418
+ use_linear_projection=use_linear_projection,
419
+ upcast_attention=upcast_attention,
420
+ attention_type=attention_type,
421
+ )
422
+ )
423
+ else:
424
+ attentions.append(
425
+ DualTransformer2DModel(
426
+ num_attention_heads,
427
+ in_channels // num_attention_heads,
428
+ in_channels=in_channels,
429
+ num_layers=1,
430
+ cross_attention_dim=cross_attention_dim,
431
+ norm_num_groups=resnet_groups,
432
+ )
433
+ )
434
+ resnets.append(
435
+ ResnetBlock2D(
436
+ in_channels=in_channels,
437
+ out_channels=in_channels,
438
+ temb_channels=temb_channels,
439
+ eps=resnet_eps,
440
+ groups=resnet_groups,
441
+ dropout=dropout,
442
+ time_embedding_norm=resnet_time_scale_shift,
443
+ non_linearity=resnet_act_fn,
444
+ output_scale_factor=output_scale_factor,
445
+ pre_norm=resnet_pre_norm,
446
+ )
447
+ )
448
+
449
+ self.attentions = nn.ModuleList(attentions)
450
+ self.resnets = nn.ModuleList(resnets)
451
+
452
+ self.gradient_checkpointing = False
453
+
454
+ def forward(
455
+ self,
456
+ hidden_states: torch.FloatTensor,
457
+ temb: Optional[torch.FloatTensor] = None,
458
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
459
+ attention_mask: Optional[torch.FloatTensor] = None,
460
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
461
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
462
+ ) -> torch.FloatTensor:
463
+ lora_scale = (
464
+ cross_attention_kwargs.get("scale", 1.0)
465
+ if cross_attention_kwargs is not None
466
+ else 1.0
467
+ )
468
+ hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale)
469
+ for attn, resnet in zip(self.attentions, self.resnets[1:]):
470
+ if self.training and self.gradient_checkpointing:
471
+
472
+ def create_custom_forward(module, return_dict=None):
473
+ def custom_forward(*inputs):
474
+ if return_dict is not None:
475
+ return module(*inputs, return_dict=return_dict)
476
+ else:
477
+ return module(*inputs)
478
+
479
+ return custom_forward
480
+
481
+ ckpt_kwargs: Dict[str, Any] = (
482
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
483
+ )
484
+ hidden_states, ref_feature = attn(
485
+ hidden_states,
486
+ encoder_hidden_states=encoder_hidden_states,
487
+ cross_attention_kwargs=cross_attention_kwargs,
488
+ attention_mask=attention_mask,
489
+ encoder_attention_mask=encoder_attention_mask,
490
+ return_dict=False,
491
+ )
492
+ hidden_states = torch.utils.checkpoint.checkpoint(
493
+ create_custom_forward(resnet),
494
+ hidden_states,
495
+ temb,
496
+ **ckpt_kwargs,
497
+ )
498
+ else:
499
+ hidden_states, ref_feature = attn(
500
+ hidden_states,
501
+ encoder_hidden_states=encoder_hidden_states,
502
+ cross_attention_kwargs=cross_attention_kwargs,
503
+ attention_mask=attention_mask,
504
+ encoder_attention_mask=encoder_attention_mask,
505
+ return_dict=False,
506
+ )
507
+ hidden_states = resnet(hidden_states, temb, scale=lora_scale)
508
+
509
+ return hidden_states
510
+
511
+
512
+ class CrossAttnDownBlock2D(nn.Module):
513
+ def __init__(
514
+ self,
515
+ in_channels: int,
516
+ out_channels: int,
517
+ temb_channels: int,
518
+ dropout: float = 0.0,
519
+ num_layers: int = 1,
520
+ transformer_layers_per_block: Union[int, Tuple[int]] = 1,
521
+ resnet_eps: float = 1e-6,
522
+ resnet_time_scale_shift: str = "default",
523
+ resnet_act_fn: str = "swish",
524
+ resnet_groups: int = 32,
525
+ resnet_pre_norm: bool = True,
526
+ num_attention_heads: int = 1,
527
+ cross_attention_dim: int = 1280,
528
+ output_scale_factor: float = 1.0,
529
+ downsample_padding: int = 1,
530
+ add_downsample: bool = True,
531
+ dual_cross_attention: bool = False,
532
+ use_linear_projection: bool = False,
533
+ only_cross_attention: bool = False,
534
+ upcast_attention: bool = False,
535
+ attention_type: str = "default",
536
+ ):
537
+ super().__init__()
538
+ resnets = []
539
+ attentions = []
540
+
541
+ self.has_cross_attention = True
542
+ self.num_attention_heads = num_attention_heads
543
+ if isinstance(transformer_layers_per_block, int):
544
+ transformer_layers_per_block = [transformer_layers_per_block] * num_layers
545
+
546
+ for i in range(num_layers):
547
+ in_channels = in_channels if i == 0 else out_channels
548
+ resnets.append(
549
+ ResnetBlock2D(
550
+ in_channels=in_channels,
551
+ out_channels=out_channels,
552
+ temb_channels=temb_channels,
553
+ eps=resnet_eps,
554
+ groups=resnet_groups,
555
+ dropout=dropout,
556
+ time_embedding_norm=resnet_time_scale_shift,
557
+ non_linearity=resnet_act_fn,
558
+ output_scale_factor=output_scale_factor,
559
+ pre_norm=resnet_pre_norm,
560
+ )
561
+ )
562
+ if not dual_cross_attention:
563
+ attentions.append(
564
+ Transformer2DModel(
565
+ num_attention_heads,
566
+ out_channels // num_attention_heads,
567
+ in_channels=out_channels,
568
+ num_layers=transformer_layers_per_block[i],
569
+ cross_attention_dim=cross_attention_dim,
570
+ norm_num_groups=resnet_groups,
571
+ use_linear_projection=use_linear_projection,
572
+ only_cross_attention=only_cross_attention,
573
+ upcast_attention=upcast_attention,
574
+ attention_type=attention_type,
575
+ )
576
+ )
577
+ else:
578
+ attentions.append(
579
+ DualTransformer2DModel(
580
+ num_attention_heads,
581
+ out_channels // num_attention_heads,
582
+ in_channels=out_channels,
583
+ num_layers=1,
584
+ cross_attention_dim=cross_attention_dim,
585
+ norm_num_groups=resnet_groups,
586
+ )
587
+ )
588
+ self.attentions = nn.ModuleList(attentions)
589
+ self.resnets = nn.ModuleList(resnets)
590
+
591
+ if add_downsample:
592
+ self.downsamplers = nn.ModuleList(
593
+ [
594
+ Downsample2D(
595
+ out_channels,
596
+ use_conv=True,
597
+ out_channels=out_channels,
598
+ padding=downsample_padding,
599
+ name="op",
600
+ )
601
+ ]
602
+ )
603
+ else:
604
+ self.downsamplers = None
605
+
606
+ self.gradient_checkpointing = False
607
+
608
+ def forward(
609
+ self,
610
+ hidden_states: torch.FloatTensor,
611
+ temb: Optional[torch.FloatTensor] = None,
612
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
613
+ attention_mask: Optional[torch.FloatTensor] = None,
614
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
615
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
616
+ additional_residuals: Optional[torch.FloatTensor] = None,
617
+ ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
618
+ output_states = ()
619
+
620
+ lora_scale = (
621
+ cross_attention_kwargs.get("scale", 1.0)
622
+ if cross_attention_kwargs is not None
623
+ else 1.0
624
+ )
625
+
626
+ blocks = list(zip(self.resnets, self.attentions))
627
+
628
+ for i, (resnet, attn) in enumerate(blocks):
629
+ if self.training and self.gradient_checkpointing:
630
+
631
+ def create_custom_forward(module, return_dict=None):
632
+ def custom_forward(*inputs):
633
+ if return_dict is not None:
634
+ return module(*inputs, return_dict=return_dict)
635
+ else:
636
+ return module(*inputs)
637
+
638
+ return custom_forward
639
+
640
+ ckpt_kwargs: Dict[str, Any] = (
641
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
642
+ )
643
+ hidden_states = torch.utils.checkpoint.checkpoint(
644
+ create_custom_forward(resnet),
645
+ hidden_states,
646
+ temb,
647
+ **ckpt_kwargs,
648
+ )
649
+ hidden_states, ref_feature = attn(
650
+ hidden_states,
651
+ encoder_hidden_states=encoder_hidden_states,
652
+ cross_attention_kwargs=cross_attention_kwargs,
653
+ attention_mask=attention_mask,
654
+ encoder_attention_mask=encoder_attention_mask,
655
+ return_dict=False,
656
+ )
657
+ else:
658
+ hidden_states = resnet(hidden_states, temb, scale=lora_scale)
659
+ hidden_states, ref_feature = attn(
660
+ hidden_states,
661
+ encoder_hidden_states=encoder_hidden_states,
662
+ cross_attention_kwargs=cross_attention_kwargs,
663
+ attention_mask=attention_mask,
664
+ encoder_attention_mask=encoder_attention_mask,
665
+ return_dict=False,
666
+ )
667
+
668
+ # apply additional residuals to the output of the last pair of resnet and attention blocks
669
+ if i == len(blocks) - 1 and additional_residuals is not None:
670
+ hidden_states = hidden_states + additional_residuals
671
+
672
+ output_states = output_states + (hidden_states,)
673
+
674
+ if self.downsamplers is not None:
675
+ for downsampler in self.downsamplers:
676
+ hidden_states = downsampler(hidden_states, scale=lora_scale)
677
+
678
+ output_states = output_states + (hidden_states,)
679
+
680
+ return hidden_states, output_states
681
+
682
+
683
+ class DownBlock2D(nn.Module):
684
+ def __init__(
685
+ self,
686
+ in_channels: int,
687
+ out_channels: int,
688
+ temb_channels: int,
689
+ dropout: float = 0.0,
690
+ num_layers: int = 1,
691
+ resnet_eps: float = 1e-6,
692
+ resnet_time_scale_shift: str = "default",
693
+ resnet_act_fn: str = "swish",
694
+ resnet_groups: int = 32,
695
+ resnet_pre_norm: bool = True,
696
+ output_scale_factor: float = 1.0,
697
+ add_downsample: bool = True,
698
+ downsample_padding: int = 1,
699
+ ):
700
+ super().__init__()
701
+ resnets = []
702
+
703
+ for i in range(num_layers):
704
+ in_channels = in_channels if i == 0 else out_channels
705
+ resnets.append(
706
+ ResnetBlock2D(
707
+ in_channels=in_channels,
708
+ out_channels=out_channels,
709
+ temb_channels=temb_channels,
710
+ eps=resnet_eps,
711
+ groups=resnet_groups,
712
+ dropout=dropout,
713
+ time_embedding_norm=resnet_time_scale_shift,
714
+ non_linearity=resnet_act_fn,
715
+ output_scale_factor=output_scale_factor,
716
+ pre_norm=resnet_pre_norm,
717
+ )
718
+ )
719
+
720
+ self.resnets = nn.ModuleList(resnets)
721
+
722
+ if add_downsample:
723
+ self.downsamplers = nn.ModuleList(
724
+ [
725
+ Downsample2D(
726
+ out_channels,
727
+ use_conv=True,
728
+ out_channels=out_channels,
729
+ padding=downsample_padding,
730
+ name="op",
731
+ )
732
+ ]
733
+ )
734
+ else:
735
+ self.downsamplers = None
736
+
737
+ self.gradient_checkpointing = False
738
+
739
+ def forward(
740
+ self,
741
+ hidden_states: torch.FloatTensor,
742
+ temb: Optional[torch.FloatTensor] = None,
743
+ scale: float = 1.0,
744
+ ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
745
+ output_states = ()
746
+
747
+ for resnet in self.resnets:
748
+ if self.training and self.gradient_checkpointing:
749
+
750
+ def create_custom_forward(module):
751
+ def custom_forward(*inputs):
752
+ return module(*inputs)
753
+
754
+ return custom_forward
755
+
756
+ if is_torch_version(">=", "1.11.0"):
757
+ hidden_states = torch.utils.checkpoint.checkpoint(
758
+ create_custom_forward(resnet),
759
+ hidden_states,
760
+ temb,
761
+ use_reentrant=False,
762
+ )
763
+ else:
764
+ hidden_states = torch.utils.checkpoint.checkpoint(
765
+ create_custom_forward(resnet), hidden_states, temb
766
+ )
767
+ else:
768
+ hidden_states = resnet(hidden_states, temb, scale=scale)
769
+
770
+ output_states = output_states + (hidden_states,)
771
+
772
+ if self.downsamplers is not None:
773
+ for downsampler in self.downsamplers:
774
+ hidden_states = downsampler(hidden_states, scale=scale)
775
+
776
+ output_states = output_states + (hidden_states,)
777
+
778
+ return hidden_states, output_states
779
+
780
+
781
+ class CrossAttnUpBlock2D(nn.Module):
782
+ def __init__(
783
+ self,
784
+ in_channels: int,
785
+ out_channels: int,
786
+ prev_output_channel: int,
787
+ temb_channels: int,
788
+ resolution_idx: Optional[int] = None,
789
+ dropout: float = 0.0,
790
+ num_layers: int = 1,
791
+ transformer_layers_per_block: Union[int, Tuple[int]] = 1,
792
+ resnet_eps: float = 1e-6,
793
+ resnet_time_scale_shift: str = "default",
794
+ resnet_act_fn: str = "swish",
795
+ resnet_groups: int = 32,
796
+ resnet_pre_norm: bool = True,
797
+ num_attention_heads: int = 1,
798
+ cross_attention_dim: int = 1280,
799
+ output_scale_factor: float = 1.0,
800
+ add_upsample: bool = True,
801
+ dual_cross_attention: bool = False,
802
+ use_linear_projection: bool = False,
803
+ only_cross_attention: bool = False,
804
+ upcast_attention: bool = False,
805
+ attention_type: str = "default",
806
+ ):
807
+ super().__init__()
808
+ resnets = []
809
+ attentions = []
810
+
811
+ self.has_cross_attention = True
812
+ self.num_attention_heads = num_attention_heads
813
+
814
+ if isinstance(transformer_layers_per_block, int):
815
+ transformer_layers_per_block = [transformer_layers_per_block] * num_layers
816
+
817
+ for i in range(num_layers):
818
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
819
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
820
+
821
+ resnets.append(
822
+ ResnetBlock2D(
823
+ in_channels=resnet_in_channels + res_skip_channels,
824
+ out_channels=out_channels,
825
+ temb_channels=temb_channels,
826
+ eps=resnet_eps,
827
+ groups=resnet_groups,
828
+ dropout=dropout,
829
+ time_embedding_norm=resnet_time_scale_shift,
830
+ non_linearity=resnet_act_fn,
831
+ output_scale_factor=output_scale_factor,
832
+ pre_norm=resnet_pre_norm,
833
+ )
834
+ )
835
+ if not dual_cross_attention:
836
+ attentions.append(
837
+ Transformer2DModel(
838
+ num_attention_heads,
839
+ out_channels // num_attention_heads,
840
+ in_channels=out_channels,
841
+ num_layers=transformer_layers_per_block[i],
842
+ cross_attention_dim=cross_attention_dim,
843
+ norm_num_groups=resnet_groups,
844
+ use_linear_projection=use_linear_projection,
845
+ only_cross_attention=only_cross_attention,
846
+ upcast_attention=upcast_attention,
847
+ attention_type=attention_type,
848
+ )
849
+ )
850
+ else:
851
+ attentions.append(
852
+ DualTransformer2DModel(
853
+ num_attention_heads,
854
+ out_channels // num_attention_heads,
855
+ in_channels=out_channels,
856
+ num_layers=1,
857
+ cross_attention_dim=cross_attention_dim,
858
+ norm_num_groups=resnet_groups,
859
+ )
860
+ )
861
+ self.attentions = nn.ModuleList(attentions)
862
+ self.resnets = nn.ModuleList(resnets)
863
+
864
+ if add_upsample:
865
+ self.upsamplers = nn.ModuleList(
866
+ [Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]
867
+ )
868
+ else:
869
+ self.upsamplers = None
870
+
871
+ self.gradient_checkpointing = False
872
+ self.resolution_idx = resolution_idx
873
+
874
+ def forward(
875
+ self,
876
+ hidden_states: torch.FloatTensor,
877
+ res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
878
+ temb: Optional[torch.FloatTensor] = None,
879
+ encoder_hidden_states: Optional[torch.FloatTensor] = None,
880
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
881
+ upsample_size: Optional[int] = None,
882
+ attention_mask: Optional[torch.FloatTensor] = None,
883
+ encoder_attention_mask: Optional[torch.FloatTensor] = None,
884
+ ) -> torch.FloatTensor:
885
+ lora_scale = (
886
+ cross_attention_kwargs.get("scale", 1.0)
887
+ if cross_attention_kwargs is not None
888
+ else 1.0
889
+ )
890
+ is_freeu_enabled = (
891
+ getattr(self, "s1", None)
892
+ and getattr(self, "s2", None)
893
+ and getattr(self, "b1", None)
894
+ and getattr(self, "b2", None)
895
+ )
896
+
897
+ for resnet, attn in zip(self.resnets, self.attentions):
898
+ # pop res hidden states
899
+ res_hidden_states = res_hidden_states_tuple[-1]
900
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
901
+
902
+ # FreeU: Only operate on the first two stages
903
+ if is_freeu_enabled:
904
+ hidden_states, res_hidden_states = apply_freeu(
905
+ self.resolution_idx,
906
+ hidden_states,
907
+ res_hidden_states,
908
+ s1=self.s1,
909
+ s2=self.s2,
910
+ b1=self.b1,
911
+ b2=self.b2,
912
+ )
913
+
914
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
915
+
916
+ if self.training and self.gradient_checkpointing:
917
+
918
+ def create_custom_forward(module, return_dict=None):
919
+ def custom_forward(*inputs):
920
+ if return_dict is not None:
921
+ return module(*inputs, return_dict=return_dict)
922
+ else:
923
+ return module(*inputs)
924
+
925
+ return custom_forward
926
+
927
+ ckpt_kwargs: Dict[str, Any] = (
928
+ {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
929
+ )
930
+ hidden_states = torch.utils.checkpoint.checkpoint(
931
+ create_custom_forward(resnet),
932
+ hidden_states,
933
+ temb,
934
+ **ckpt_kwargs,
935
+ )
936
+ hidden_states, ref_feature = attn(
937
+ hidden_states,
938
+ encoder_hidden_states=encoder_hidden_states,
939
+ cross_attention_kwargs=cross_attention_kwargs,
940
+ attention_mask=attention_mask,
941
+ encoder_attention_mask=encoder_attention_mask,
942
+ return_dict=False,
943
+ )
944
+ else:
945
+ hidden_states = resnet(hidden_states, temb, scale=lora_scale)
946
+ hidden_states, ref_feature = attn(
947
+ hidden_states,
948
+ encoder_hidden_states=encoder_hidden_states,
949
+ cross_attention_kwargs=cross_attention_kwargs,
950
+ attention_mask=attention_mask,
951
+ encoder_attention_mask=encoder_attention_mask,
952
+ return_dict=False,
953
+ )
954
+
955
+ if self.upsamplers is not None:
956
+ for upsampler in self.upsamplers:
957
+ hidden_states = upsampler(
958
+ hidden_states, upsample_size, scale=lora_scale
959
+ )
960
+
961
+ return hidden_states
962
+
963
+
964
+ class UpBlock2D(nn.Module):
965
+ def __init__(
966
+ self,
967
+ in_channels: int,
968
+ prev_output_channel: int,
969
+ out_channels: int,
970
+ temb_channels: int,
971
+ resolution_idx: Optional[int] = None,
972
+ dropout: float = 0.0,
973
+ num_layers: int = 1,
974
+ resnet_eps: float = 1e-6,
975
+ resnet_time_scale_shift: str = "default",
976
+ resnet_act_fn: str = "swish",
977
+ resnet_groups: int = 32,
978
+ resnet_pre_norm: bool = True,
979
+ output_scale_factor: float = 1.0,
980
+ add_upsample: bool = True,
981
+ ):
982
+ super().__init__()
983
+ resnets = []
984
+
985
+ for i in range(num_layers):
986
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
987
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
988
+
989
+ resnets.append(
990
+ ResnetBlock2D(
991
+ in_channels=resnet_in_channels + res_skip_channels,
992
+ out_channels=out_channels,
993
+ temb_channels=temb_channels,
994
+ eps=resnet_eps,
995
+ groups=resnet_groups,
996
+ dropout=dropout,
997
+ time_embedding_norm=resnet_time_scale_shift,
998
+ non_linearity=resnet_act_fn,
999
+ output_scale_factor=output_scale_factor,
1000
+ pre_norm=resnet_pre_norm,
1001
+ )
1002
+ )
1003
+
1004
+ self.resnets = nn.ModuleList(resnets)
1005
+
1006
+ if add_upsample:
1007
+ self.upsamplers = nn.ModuleList(
1008
+ [Upsample2D(out_channels, use_conv=True, out_channels=out_channels)]
1009
+ )
1010
+ else:
1011
+ self.upsamplers = None
1012
+
1013
+ self.gradient_checkpointing = False
1014
+ self.resolution_idx = resolution_idx
1015
+
1016
+ def forward(
1017
+ self,
1018
+ hidden_states: torch.FloatTensor,
1019
+ res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
1020
+ temb: Optional[torch.FloatTensor] = None,
1021
+ upsample_size: Optional[int] = None,
1022
+ scale: float = 1.0,
1023
+ ) -> torch.FloatTensor:
1024
+ is_freeu_enabled = (
1025
+ getattr(self, "s1", None)
1026
+ and getattr(self, "s2", None)
1027
+ and getattr(self, "b1", None)
1028
+ and getattr(self, "b2", None)
1029
+ )
1030
+
1031
+ for resnet in self.resnets:
1032
+ # pop res hidden states
1033
+ res_hidden_states = res_hidden_states_tuple[-1]
1034
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
1035
+
1036
+ # FreeU: Only operate on the first two stages
1037
+ if is_freeu_enabled:
1038
+ hidden_states, res_hidden_states = apply_freeu(
1039
+ self.resolution_idx,
1040
+ hidden_states,
1041
+ res_hidden_states,
1042
+ s1=self.s1,
1043
+ s2=self.s2,
1044
+ b1=self.b1,
1045
+ b2=self.b2,
1046
+ )
1047
+
1048
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
1049
+
1050
+ if self.training and self.gradient_checkpointing:
1051
+
1052
+ def create_custom_forward(module):
1053
+ def custom_forward(*inputs):
1054
+ return module(*inputs)
1055
+
1056
+ return custom_forward
1057
+
1058
+ if is_torch_version(">=", "1.11.0"):
1059
+ hidden_states = torch.utils.checkpoint.checkpoint(
1060
+ create_custom_forward(resnet),
1061
+ hidden_states,
1062
+ temb,
1063
+ use_reentrant=False,
1064
+ )
1065
+ else:
1066
+ hidden_states = torch.utils.checkpoint.checkpoint(
1067
+ create_custom_forward(resnet), hidden_states, temb
1068
+ )
1069
+ else:
1070
+ hidden_states = resnet(hidden_states, temb, scale=scale)
1071
+
1072
+ if self.upsamplers is not None:
1073
+ for upsampler in self.upsamplers:
1074
+ hidden_states = upsampler(hidden_states, upsample_size, scale=scale)
1075
+
1076
+ return hidden_states
2610_variant_runtime/diffusion/models/unet_2d_condition.py ADDED
@@ -0,0 +1,1313 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_condition.py
2
+ from dataclasses import dataclass
3
+ from typing import Any, Dict, List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.utils.checkpoint
8
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
9
+ from diffusers.loaders import UNet2DConditionLoadersMixin
10
+ from diffusers.models.activations import get_activation
11
+ from diffusers.models.attention_processor import (
12
+ ADDED_KV_ATTENTION_PROCESSORS,
13
+ CROSS_ATTENTION_PROCESSORS,
14
+ AttentionProcessor,
15
+ AttnAddedKVProcessor,
16
+ AttnProcessor,
17
+ )
18
+ from diffusers.models.embeddings import (
19
+ GaussianFourierProjection,
20
+ ImageHintTimeEmbedding,
21
+ ImageProjection,
22
+ ImageTimeEmbedding,
23
+ PositionNet,
24
+ TextImageProjection,
25
+ TextImageTimeEmbedding,
26
+ TextTimeEmbedding,
27
+ TimestepEmbedding,
28
+ Timesteps,
29
+ )
30
+ from diffusers.models.modeling_utils import ModelMixin
31
+ from diffusers.utils import (
32
+ USE_PEFT_BACKEND,
33
+ BaseOutput,
34
+ deprecate,
35
+ logging,
36
+ scale_lora_layers,
37
+ unscale_lora_layers,
38
+ )
39
+
40
+ from .unet_2d_blocks import (
41
+ UNetMidBlock2D,
42
+ UNetMidBlock2DCrossAttn,
43
+ get_down_block,
44
+ get_up_block,
45
+ )
46
+
47
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
48
+
49
+
50
+ @dataclass
51
+ class UNet2DConditionOutput(BaseOutput):
52
+ """
53
+ The output of [`UNet2DConditionModel`].
54
+
55
+ Args:
56
+ sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)`):
57
+ The hidden states output conditioned on `encoder_hidden_states` input. Output of last layer of model.
58
+ """
59
+
60
+ sample: torch.FloatTensor = None
61
+ ref_features: Tuple[torch.FloatTensor] = None
62
+
63
+
64
+ class UNet2DConditionModel(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin):
65
+ r"""
66
+ A conditional 2D UNet model that takes a noisy sample, conditional state, and a timestep and returns a sample
67
+ shaped output.
68
+
69
+ This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
70
+ for all models (such as downloading or saving).
71
+
72
+ Parameters:
73
+ sample_size (`int` or `Tuple[int, int]`, *optional*, defaults to `None`):
74
+ Height and width of input/output sample.
75
+ in_channels (`int`, *optional*, defaults to 4): Number of channels in the input sample.
76
+ out_channels (`int`, *optional*, defaults to 4): Number of channels in the output.
77
+ center_input_sample (`bool`, *optional*, defaults to `False`): Whether to center the input sample.
78
+ flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
79
+ Whether to flip the sin to cos in the time embedding.
80
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
81
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
82
+ The tuple of downsample blocks to use.
83
+ mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock2DCrossAttn"`):
84
+ Block type for middle of UNet, it can be one of `UNetMidBlock2DCrossAttn`, `UNetMidBlock2D`, or
85
+ `UNetMidBlock2DSimpleCrossAttn`. If `None`, the mid block layer is skipped.
86
+ up_block_types (`Tuple[str]`, *optional*, defaults to `("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D")`):
87
+ The tuple of upsample blocks to use.
88
+ only_cross_attention(`bool` or `Tuple[bool]`, *optional*, default to `False`):
89
+ Whether to include self-attention in the basic transformer blocks, see
90
+ [`~models.attention.BasicTransformerBlock`].
91
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
92
+ The tuple of output channels for each block.
93
+ layers_per_block (`int`, *optional*, defaults to 2): The number of layers per block.
94
+ downsample_padding (`int`, *optional*, defaults to 1): The padding to use for the downsampling convolution.
95
+ mid_block_scale_factor (`float`, *optional*, defaults to 1.0): The scale factor to use for the mid block.
96
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
97
+ act_fn (`str`, *optional*, defaults to `"silu"`): The activation function to use.
98
+ norm_num_groups (`int`, *optional*, defaults to 32): The number of groups to use for the normalization.
99
+ If `None`, normalization and activation layers is skipped in post-processing.
100
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon to use for the normalization.
101
+ cross_attention_dim (`int` or `Tuple[int]`, *optional*, defaults to 1280):
102
+ The dimension of the cross attention features.
103
+ transformer_layers_per_block (`int`, `Tuple[int]`, or `Tuple[Tuple]` , *optional*, defaults to 1):
104
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
105
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
106
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
107
+ reverse_transformer_layers_per_block : (`Tuple[Tuple]`, *optional*, defaults to None):
108
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`], in the upsampling
109
+ blocks of the U-Net. Only relevant if `transformer_layers_per_block` is of type `Tuple[Tuple]` and for
110
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
111
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
112
+ encoder_hid_dim (`int`, *optional*, defaults to None):
113
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
114
+ dimension to `cross_attention_dim`.
115
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
116
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
117
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
118
+ attention_head_dim (`int`, *optional*, defaults to 8): The dimension of the attention heads.
119
+ num_attention_heads (`int`, *optional*):
120
+ The number of attention heads. If not defined, defaults to `attention_head_dim`
121
+ resnet_time_scale_shift (`str`, *optional*, defaults to `"default"`): Time scale shift config
122
+ for ResNet blocks (see [`~models.resnet.ResnetBlock2D`]). Choose from `default` or `scale_shift`.
123
+ class_embed_type (`str`, *optional*, defaults to `None`):
124
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from `None`,
125
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
126
+ addition_embed_type (`str`, *optional*, defaults to `None`):
127
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
128
+ "text". "text" will use the `TextTimeEmbedding` layer.
129
+ addition_time_embed_dim: (`int`, *optional*, defaults to `None`):
130
+ Dimension for the timestep embeddings.
131
+ num_class_embeds (`int`, *optional*, defaults to `None`):
132
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
133
+ class conditioning with `class_embed_type` equal to `None`.
134
+ time_embedding_type (`str`, *optional*, defaults to `positional`):
135
+ The type of position embedding to use for timesteps. Choose from `positional` or `fourier`.
136
+ time_embedding_dim (`int`, *optional*, defaults to `None`):
137
+ An optional override for the dimension of the projected time embedding.
138
+ time_embedding_act_fn (`str`, *optional*, defaults to `None`):
139
+ Optional activation function to use only once on the time embeddings before they are passed to the rest of
140
+ the UNet. Choose from `silu`, `mish`, `gelu`, and `swish`.
141
+ timestep_post_act (`str`, *optional*, defaults to `None`):
142
+ The second activation function to use in timestep embedding. Choose from `silu`, `mish` and `gelu`.
143
+ time_cond_proj_dim (`int`, *optional*, defaults to `None`):
144
+ The dimension of `cond_proj` layer in the timestep embedding.
145
+ conv_in_kernel (`int`, *optional*, default to `3`): The kernel size of `conv_in` layer. conv_out_kernel (`int`,
146
+ *optional*, default to `3`): The kernel size of `conv_out` layer. projection_class_embeddings_input_dim (`int`,
147
+ *optional*): The dimension of the `class_labels` input when
148
+ `class_embed_type="projection"`. Required when `class_embed_type="projection"`.
149
+ class_embeddings_concat (`bool`, *optional*, defaults to `False`): Whether to concatenate the time
150
+ embeddings with the class embeddings.
151
+ mid_block_only_cross_attention (`bool`, *optional*, defaults to `None`):
152
+ Whether to use cross attention with the mid block when using the `UNetMidBlock2DSimpleCrossAttn`. If
153
+ `only_cross_attention` is given as a single boolean and `mid_block_only_cross_attention` is `None`, the
154
+ `only_cross_attention` value is used as the value for `mid_block_only_cross_attention`. Default to `False`
155
+ otherwise.
156
+ """
157
+
158
+ _supports_gradient_checkpointing = True
159
+
160
+ @register_to_config
161
+ def __init__(
162
+ self,
163
+ sample_size: Optional[int] = None,
164
+ in_channels: int = 4,
165
+ out_channels: int = 4,
166
+ center_input_sample: bool = False,
167
+ flip_sin_to_cos: bool = True,
168
+ freq_shift: int = 0,
169
+ down_block_types: Tuple[str] = (
170
+ "CrossAttnDownBlock2D",
171
+ "CrossAttnDownBlock2D",
172
+ "CrossAttnDownBlock2D",
173
+ "DownBlock2D",
174
+ ),
175
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
176
+ up_block_types: Tuple[str] = (
177
+ "UpBlock2D",
178
+ "CrossAttnUpBlock2D",
179
+ "CrossAttnUpBlock2D",
180
+ "CrossAttnUpBlock2D",
181
+ ),
182
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
183
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
184
+ layers_per_block: Union[int, Tuple[int]] = 2,
185
+ downsample_padding: int = 1,
186
+ mid_block_scale_factor: float = 1,
187
+ dropout: float = 0.0,
188
+ act_fn: str = "silu",
189
+ norm_num_groups: Optional[int] = 32,
190
+ norm_eps: float = 1e-5,
191
+ cross_attention_dim: Union[int, Tuple[int]] = 1280,
192
+ transformer_layers_per_block: Union[int, Tuple[int], Tuple[Tuple]] = 1,
193
+ reverse_transformer_layers_per_block: Optional[Tuple[Tuple[int]]] = None,
194
+ encoder_hid_dim: Optional[int] = None,
195
+ encoder_hid_dim_type: Optional[str] = None,
196
+ attention_head_dim: Union[int, Tuple[int]] = 8,
197
+ num_attention_heads: Optional[Union[int, Tuple[int]]] = None,
198
+ dual_cross_attention: bool = False,
199
+ use_linear_projection: bool = False,
200
+ class_embed_type: Optional[str] = None,
201
+ addition_embed_type: Optional[str] = None,
202
+ addition_time_embed_dim: Optional[int] = None,
203
+ num_class_embeds: Optional[int] = None,
204
+ upcast_attention: bool = False,
205
+ resnet_time_scale_shift: str = "default",
206
+ resnet_skip_time_act: bool = False,
207
+ resnet_out_scale_factor: int = 1.0,
208
+ time_embedding_type: str = "positional",
209
+ time_embedding_dim: Optional[int] = None,
210
+ time_embedding_act_fn: Optional[str] = None,
211
+ timestep_post_act: Optional[str] = None,
212
+ time_cond_proj_dim: Optional[int] = None,
213
+ conv_in_kernel: int = 3,
214
+ conv_out_kernel: int = 3,
215
+ projection_class_embeddings_input_dim: Optional[int] = None,
216
+ attention_type: str = "default",
217
+ class_embeddings_concat: bool = False,
218
+ mid_block_only_cross_attention: Optional[bool] = None,
219
+ cross_attention_norm: Optional[str] = None,
220
+ addition_embed_type_num_heads=64,
221
+ ):
222
+ super().__init__()
223
+
224
+ self.sample_size = sample_size
225
+
226
+ if num_attention_heads is not None:
227
+ raise ValueError(
228
+ "At the moment it is not possible to define the number of attention heads via `num_attention_heads` because of a naming issue as described in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131. Passing `num_attention_heads` will only be supported in diffusers v0.19."
229
+ )
230
+
231
+ # If `num_attention_heads` is not defined (which is the case for most models)
232
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
233
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
234
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
235
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
236
+ # which is why we correct for the naming here.
237
+ num_attention_heads = num_attention_heads or attention_head_dim
238
+
239
+ # Check inputs
240
+ if len(down_block_types) != len(up_block_types):
241
+ raise ValueError(
242
+ f"Must provide the same number of `down_block_types` as `up_block_types`. `down_block_types`: {down_block_types}. `up_block_types`: {up_block_types}."
243
+ )
244
+
245
+ if len(block_out_channels) != len(down_block_types):
246
+ raise ValueError(
247
+ f"Must provide the same number of `block_out_channels` as `down_block_types`. `block_out_channels`: {block_out_channels}. `down_block_types`: {down_block_types}."
248
+ )
249
+
250
+ if not isinstance(only_cross_attention, bool) and len(
251
+ only_cross_attention
252
+ ) != len(down_block_types):
253
+ raise ValueError(
254
+ f"Must provide the same number of `only_cross_attention` as `down_block_types`. `only_cross_attention`: {only_cross_attention}. `down_block_types`: {down_block_types}."
255
+ )
256
+
257
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(
258
+ down_block_types
259
+ ):
260
+ raise ValueError(
261
+ f"Must provide the same number of `num_attention_heads` as `down_block_types`. `num_attention_heads`: {num_attention_heads}. `down_block_types`: {down_block_types}."
262
+ )
263
+
264
+ if not isinstance(attention_head_dim, int) and len(attention_head_dim) != len(
265
+ down_block_types
266
+ ):
267
+ raise ValueError(
268
+ f"Must provide the same number of `attention_head_dim` as `down_block_types`. `attention_head_dim`: {attention_head_dim}. `down_block_types`: {down_block_types}."
269
+ )
270
+
271
+ if isinstance(cross_attention_dim, list) and len(cross_attention_dim) != len(
272
+ down_block_types
273
+ ):
274
+ raise ValueError(
275
+ f"Must provide the same number of `cross_attention_dim` as `down_block_types`. `cross_attention_dim`: {cross_attention_dim}. `down_block_types`: {down_block_types}."
276
+ )
277
+
278
+ if not isinstance(layers_per_block, int) and len(layers_per_block) != len(
279
+ down_block_types
280
+ ):
281
+ raise ValueError(
282
+ f"Must provide the same number of `layers_per_block` as `down_block_types`. `layers_per_block`: {layers_per_block}. `down_block_types`: {down_block_types}."
283
+ )
284
+ if (
285
+ isinstance(transformer_layers_per_block, list)
286
+ and reverse_transformer_layers_per_block is None
287
+ ):
288
+ for layer_number_per_block in transformer_layers_per_block:
289
+ if isinstance(layer_number_per_block, list):
290
+ raise ValueError(
291
+ "Must provide 'reverse_transformer_layers_per_block` if using asymmetrical UNet."
292
+ )
293
+
294
+ # input
295
+ conv_in_padding = (conv_in_kernel - 1) // 2
296
+ self.conv_in = nn.Conv2d(
297
+ in_channels,
298
+ block_out_channels[0],
299
+ kernel_size=conv_in_kernel,
300
+ padding=conv_in_padding,
301
+ )
302
+
303
+ # time
304
+ if time_embedding_type == "fourier":
305
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 2
306
+ if time_embed_dim % 2 != 0:
307
+ raise ValueError(
308
+ f"`time_embed_dim` should be divisible by 2, but is {time_embed_dim}."
309
+ )
310
+ self.time_proj = GaussianFourierProjection(
311
+ time_embed_dim // 2,
312
+ set_W_to_weight=False,
313
+ log=False,
314
+ flip_sin_to_cos=flip_sin_to_cos,
315
+ )
316
+ timestep_input_dim = time_embed_dim
317
+ elif time_embedding_type == "positional":
318
+ time_embed_dim = time_embedding_dim or block_out_channels[0] * 4
319
+
320
+ self.time_proj = Timesteps(
321
+ block_out_channels[0], flip_sin_to_cos, freq_shift
322
+ )
323
+ timestep_input_dim = block_out_channels[0]
324
+ else:
325
+ raise ValueError(
326
+ f"{time_embedding_type} does not exist. Please make sure to use one of `fourier` or `positional`."
327
+ )
328
+
329
+ self.time_embedding = TimestepEmbedding(
330
+ timestep_input_dim,
331
+ time_embed_dim,
332
+ act_fn=act_fn,
333
+ post_act_fn=timestep_post_act,
334
+ cond_proj_dim=time_cond_proj_dim,
335
+ )
336
+
337
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
338
+ encoder_hid_dim_type = "text_proj"
339
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
340
+ logger.info(
341
+ "encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined."
342
+ )
343
+
344
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
345
+ raise ValueError(
346
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
347
+ )
348
+
349
+ if encoder_hid_dim_type == "text_proj":
350
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
351
+ elif encoder_hid_dim_type == "text_image_proj":
352
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
353
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
354
+ # case when `addition_embed_type == "text_image_proj"` (Kadinsky 2.1)`
355
+ self.encoder_hid_proj = TextImageProjection(
356
+ text_embed_dim=encoder_hid_dim,
357
+ image_embed_dim=cross_attention_dim,
358
+ cross_attention_dim=cross_attention_dim,
359
+ )
360
+ elif encoder_hid_dim_type == "image_proj":
361
+ # Kandinsky 2.2
362
+ self.encoder_hid_proj = ImageProjection(
363
+ image_embed_dim=encoder_hid_dim,
364
+ cross_attention_dim=cross_attention_dim,
365
+ )
366
+ elif encoder_hid_dim_type is not None:
367
+ raise ValueError(
368
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
369
+ )
370
+ else:
371
+ self.encoder_hid_proj = None
372
+
373
+ # class embedding
374
+ if class_embed_type is None and num_class_embeds is not None:
375
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
376
+ elif class_embed_type == "timestep":
377
+ self.class_embedding = TimestepEmbedding(
378
+ timestep_input_dim, time_embed_dim, act_fn=act_fn
379
+ )
380
+ elif class_embed_type == "identity":
381
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
382
+ elif class_embed_type == "projection":
383
+ if projection_class_embeddings_input_dim is None:
384
+ raise ValueError(
385
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
386
+ )
387
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
388
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
389
+ # 2. it projects from an arbitrary input dimension.
390
+ #
391
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
392
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
393
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
394
+ self.class_embedding = TimestepEmbedding(
395
+ projection_class_embeddings_input_dim, time_embed_dim
396
+ )
397
+ elif class_embed_type == "simple_projection":
398
+ if projection_class_embeddings_input_dim is None:
399
+ raise ValueError(
400
+ "`class_embed_type`: 'simple_projection' requires `projection_class_embeddings_input_dim` be set"
401
+ )
402
+ self.class_embedding = nn.Linear(
403
+ projection_class_embeddings_input_dim, time_embed_dim
404
+ )
405
+ else:
406
+ self.class_embedding = None
407
+
408
+ if addition_embed_type == "text":
409
+ if encoder_hid_dim is not None:
410
+ text_time_embedding_from_dim = encoder_hid_dim
411
+ else:
412
+ text_time_embedding_from_dim = cross_attention_dim
413
+
414
+ self.add_embedding = TextTimeEmbedding(
415
+ text_time_embedding_from_dim,
416
+ time_embed_dim,
417
+ num_heads=addition_embed_type_num_heads,
418
+ )
419
+ elif addition_embed_type == "text_image":
420
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
421
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
422
+ # case when `addition_embed_type == "text_image"` (Kadinsky 2.1)`
423
+ self.add_embedding = TextImageTimeEmbedding(
424
+ text_embed_dim=cross_attention_dim,
425
+ image_embed_dim=cross_attention_dim,
426
+ time_embed_dim=time_embed_dim,
427
+ )
428
+ elif addition_embed_type == "text_time":
429
+ self.add_time_proj = Timesteps(
430
+ addition_time_embed_dim, flip_sin_to_cos, freq_shift
431
+ )
432
+ self.add_embedding = TimestepEmbedding(
433
+ projection_class_embeddings_input_dim, time_embed_dim
434
+ )
435
+ elif addition_embed_type == "image":
436
+ # Kandinsky 2.2
437
+ self.add_embedding = ImageTimeEmbedding(
438
+ image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim
439
+ )
440
+ elif addition_embed_type == "image_hint":
441
+ # Kandinsky 2.2 ControlNet
442
+ self.add_embedding = ImageHintTimeEmbedding(
443
+ image_embed_dim=encoder_hid_dim, time_embed_dim=time_embed_dim
444
+ )
445
+ elif addition_embed_type is not None:
446
+ raise ValueError(
447
+ f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'."
448
+ )
449
+
450
+ if time_embedding_act_fn is None:
451
+ self.time_embed_act = None
452
+ else:
453
+ self.time_embed_act = get_activation(time_embedding_act_fn)
454
+
455
+ self.down_blocks = nn.ModuleList([])
456
+ self.up_blocks = nn.ModuleList([])
457
+
458
+ if isinstance(only_cross_attention, bool):
459
+ if mid_block_only_cross_attention is None:
460
+ mid_block_only_cross_attention = only_cross_attention
461
+
462
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
463
+
464
+ if mid_block_only_cross_attention is None:
465
+ mid_block_only_cross_attention = False
466
+
467
+ if isinstance(num_attention_heads, int):
468
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
469
+
470
+ if isinstance(attention_head_dim, int):
471
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
472
+
473
+ if isinstance(cross_attention_dim, int):
474
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
475
+
476
+ if isinstance(layers_per_block, int):
477
+ layers_per_block = [layers_per_block] * len(down_block_types)
478
+
479
+ if isinstance(transformer_layers_per_block, int):
480
+ transformer_layers_per_block = [transformer_layers_per_block] * len(
481
+ down_block_types
482
+ )
483
+
484
+ if class_embeddings_concat:
485
+ # The time embeddings are concatenated with the class embeddings. The dimension of the
486
+ # time embeddings passed to the down, middle, and up blocks is twice the dimension of the
487
+ # regular time embeddings
488
+ blocks_time_embed_dim = time_embed_dim * 2
489
+ else:
490
+ blocks_time_embed_dim = time_embed_dim
491
+
492
+ # down
493
+ output_channel = block_out_channels[0]
494
+ for i, down_block_type in enumerate(down_block_types):
495
+ input_channel = output_channel
496
+ output_channel = block_out_channels[i]
497
+ is_final_block = i == len(block_out_channels) - 1
498
+
499
+ down_block = get_down_block(
500
+ down_block_type,
501
+ num_layers=layers_per_block[i],
502
+ transformer_layers_per_block=transformer_layers_per_block[i],
503
+ in_channels=input_channel,
504
+ out_channels=output_channel,
505
+ temb_channels=blocks_time_embed_dim,
506
+ add_downsample=not is_final_block,
507
+ resnet_eps=norm_eps,
508
+ resnet_act_fn=act_fn,
509
+ resnet_groups=norm_num_groups,
510
+ cross_attention_dim=cross_attention_dim[i],
511
+ num_attention_heads=num_attention_heads[i],
512
+ downsample_padding=downsample_padding,
513
+ dual_cross_attention=dual_cross_attention,
514
+ use_linear_projection=use_linear_projection,
515
+ only_cross_attention=only_cross_attention[i],
516
+ upcast_attention=upcast_attention,
517
+ resnet_time_scale_shift=resnet_time_scale_shift,
518
+ attention_type=attention_type,
519
+ resnet_skip_time_act=resnet_skip_time_act,
520
+ resnet_out_scale_factor=resnet_out_scale_factor,
521
+ cross_attention_norm=cross_attention_norm,
522
+ attention_head_dim=(
523
+ attention_head_dim[i]
524
+ if attention_head_dim[i] is not None
525
+ else output_channel
526
+ ),
527
+ dropout=dropout,
528
+ )
529
+ self.down_blocks.append(down_block)
530
+
531
+ # mid
532
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
533
+ self.mid_block = UNetMidBlock2DCrossAttn(
534
+ transformer_layers_per_block=transformer_layers_per_block[-1],
535
+ in_channels=block_out_channels[-1],
536
+ temb_channels=blocks_time_embed_dim,
537
+ dropout=dropout,
538
+ resnet_eps=norm_eps,
539
+ resnet_act_fn=act_fn,
540
+ output_scale_factor=mid_block_scale_factor,
541
+ resnet_time_scale_shift=resnet_time_scale_shift,
542
+ cross_attention_dim=cross_attention_dim[-1],
543
+ num_attention_heads=num_attention_heads[-1],
544
+ resnet_groups=norm_num_groups,
545
+ dual_cross_attention=dual_cross_attention,
546
+ use_linear_projection=use_linear_projection,
547
+ upcast_attention=upcast_attention,
548
+ attention_type=attention_type,
549
+ )
550
+ elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
551
+ raise NotImplementedError(f"Unsupport mid_block_type: {mid_block_type}")
552
+ elif mid_block_type == "UNetMidBlock2D":
553
+ self.mid_block = UNetMidBlock2D(
554
+ in_channels=block_out_channels[-1],
555
+ temb_channels=blocks_time_embed_dim,
556
+ dropout=dropout,
557
+ num_layers=0,
558
+ resnet_eps=norm_eps,
559
+ resnet_act_fn=act_fn,
560
+ output_scale_factor=mid_block_scale_factor,
561
+ resnet_groups=norm_num_groups,
562
+ resnet_time_scale_shift=resnet_time_scale_shift,
563
+ add_attention=False,
564
+ )
565
+ elif mid_block_type is None:
566
+ self.mid_block = None
567
+ else:
568
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
569
+
570
+ # count how many layers upsample the images
571
+ self.num_upsamplers = 0
572
+
573
+ # up
574
+ reversed_block_out_channels = list(reversed(block_out_channels))
575
+ reversed_num_attention_heads = list(reversed(num_attention_heads))
576
+ reversed_layers_per_block = list(reversed(layers_per_block))
577
+ reversed_cross_attention_dim = list(reversed(cross_attention_dim))
578
+ reversed_transformer_layers_per_block = (
579
+ list(reversed(transformer_layers_per_block))
580
+ if reverse_transformer_layers_per_block is None
581
+ else reverse_transformer_layers_per_block
582
+ )
583
+ only_cross_attention = list(reversed(only_cross_attention))
584
+
585
+ output_channel = reversed_block_out_channels[0]
586
+ for i, up_block_type in enumerate(up_block_types):
587
+ is_final_block = i == len(block_out_channels) - 1
588
+
589
+ prev_output_channel = output_channel
590
+ output_channel = reversed_block_out_channels[i]
591
+ input_channel = reversed_block_out_channels[
592
+ min(i + 1, len(block_out_channels) - 1)
593
+ ]
594
+
595
+ # add upsample block for all BUT final layer
596
+ if not is_final_block:
597
+ add_upsample = True
598
+ self.num_upsamplers += 1
599
+ else:
600
+ add_upsample = False
601
+
602
+ up_block = get_up_block(
603
+ up_block_type,
604
+ num_layers=reversed_layers_per_block[i] + 1,
605
+ transformer_layers_per_block=reversed_transformer_layers_per_block[i],
606
+ in_channels=input_channel,
607
+ out_channels=output_channel,
608
+ prev_output_channel=prev_output_channel,
609
+ temb_channels=blocks_time_embed_dim,
610
+ add_upsample=add_upsample,
611
+ resnet_eps=norm_eps,
612
+ resnet_act_fn=act_fn,
613
+ resolution_idx=i,
614
+ resnet_groups=norm_num_groups,
615
+ cross_attention_dim=reversed_cross_attention_dim[i],
616
+ num_attention_heads=reversed_num_attention_heads[i],
617
+ dual_cross_attention=dual_cross_attention,
618
+ use_linear_projection=use_linear_projection,
619
+ only_cross_attention=only_cross_attention[i],
620
+ upcast_attention=upcast_attention,
621
+ resnet_time_scale_shift=resnet_time_scale_shift,
622
+ attention_type=attention_type,
623
+ resnet_skip_time_act=resnet_skip_time_act,
624
+ resnet_out_scale_factor=resnet_out_scale_factor,
625
+ cross_attention_norm=cross_attention_norm,
626
+ attention_head_dim=(
627
+ attention_head_dim[i]
628
+ if attention_head_dim[i] is not None
629
+ else output_channel
630
+ ),
631
+ dropout=dropout,
632
+ )
633
+ self.up_blocks.append(up_block)
634
+ prev_output_channel = output_channel
635
+
636
+ # out
637
+ if norm_num_groups is not None:
638
+ self.conv_norm_out = nn.GroupNorm(
639
+ num_channels=block_out_channels[0],
640
+ num_groups=norm_num_groups,
641
+ eps=norm_eps,
642
+ )
643
+
644
+ self.conv_act = get_activation(act_fn)
645
+
646
+ else:
647
+ self.conv_norm_out = None
648
+ self.conv_act = None
649
+ self.conv_norm_out = None
650
+
651
+ conv_out_padding = (conv_out_kernel - 1) // 2
652
+ # self.conv_out = nn.Conv2d(
653
+ # block_out_channels[0],
654
+ # out_channels,
655
+ # kernel_size=conv_out_kernel,
656
+ # padding=conv_out_padding,
657
+ # )
658
+
659
+ if attention_type in ["gated", "gated-text-image"]:
660
+ positive_len = 768
661
+ if isinstance(cross_attention_dim, int):
662
+ positive_len = cross_attention_dim
663
+ elif isinstance(cross_attention_dim, tuple) or isinstance(
664
+ cross_attention_dim, list
665
+ ):
666
+ positive_len = cross_attention_dim[0]
667
+
668
+ feature_type = "text-only" if attention_type == "gated" else "text-image"
669
+ self.position_net = PositionNet(
670
+ positive_len=positive_len,
671
+ out_dim=cross_attention_dim,
672
+ feature_type=feature_type,
673
+ )
674
+
675
+ @property
676
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
677
+ r"""
678
+ Returns:
679
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
680
+ indexed by its weight name.
681
+ """
682
+ # set recursively
683
+ processors = {}
684
+
685
+ def fn_recursive_add_processors(
686
+ name: str,
687
+ module: torch.nn.Module,
688
+ processors: Dict[str, AttentionProcessor],
689
+ ):
690
+ if hasattr(module, "get_processor"):
691
+ processors[f"{name}.processor"] = module.get_processor(
692
+ return_deprecated_lora=True
693
+ )
694
+
695
+ for sub_name, child in module.named_children():
696
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
697
+
698
+ return processors
699
+
700
+ for name, module in self.named_children():
701
+ fn_recursive_add_processors(name, module, processors)
702
+
703
+ return processors
704
+
705
+ def set_attn_processor(
706
+ self,
707
+ processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]],
708
+ _remove_lora=False,
709
+ ):
710
+ r"""
711
+ Sets the attention processor to use to compute attention.
712
+
713
+ Parameters:
714
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
715
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
716
+ for **all** `Attention` layers.
717
+
718
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
719
+ processor. This is strongly recommended when setting trainable attention processors.
720
+
721
+ """
722
+ count = len(self.attn_processors.keys())
723
+
724
+ if isinstance(processor, dict) and len(processor) != count:
725
+ raise ValueError(
726
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
727
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
728
+ )
729
+
730
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
731
+ if hasattr(module, "set_processor"):
732
+ if not isinstance(processor, dict):
733
+ module.set_processor(processor, _remove_lora=_remove_lora)
734
+ else:
735
+ module.set_processor(
736
+ processor.pop(f"{name}.processor"), _remove_lora=_remove_lora
737
+ )
738
+
739
+ for sub_name, child in module.named_children():
740
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
741
+
742
+ for name, module in self.named_children():
743
+ fn_recursive_attn_processor(name, module, processor)
744
+
745
+ def set_default_attn_processor(self):
746
+ """
747
+ Disables custom attention processors and sets the default attention implementation.
748
+ """
749
+ if all(
750
+ proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS
751
+ for proc in self.attn_processors.values()
752
+ ):
753
+ processor = AttnAddedKVProcessor()
754
+ elif all(
755
+ proc.__class__ in CROSS_ATTENTION_PROCESSORS
756
+ for proc in self.attn_processors.values()
757
+ ):
758
+ processor = AttnProcessor()
759
+ else:
760
+ raise ValueError(
761
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
762
+ )
763
+
764
+ self.set_attn_processor(processor, _remove_lora=True)
765
+
766
+ def set_attention_slice(self, slice_size):
767
+ r"""
768
+ Enable sliced attention computation.
769
+
770
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
771
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
772
+
773
+ Args:
774
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
775
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
776
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
777
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
778
+ must be a multiple of `slice_size`.
779
+ """
780
+ sliceable_head_dims = []
781
+
782
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
783
+ if hasattr(module, "set_attention_slice"):
784
+ sliceable_head_dims.append(module.sliceable_head_dim)
785
+
786
+ for child in module.children():
787
+ fn_recursive_retrieve_sliceable_dims(child)
788
+
789
+ # retrieve number of attention layers
790
+ for module in self.children():
791
+ fn_recursive_retrieve_sliceable_dims(module)
792
+
793
+ num_sliceable_layers = len(sliceable_head_dims)
794
+
795
+ if slice_size == "auto":
796
+ # half the attention head size is usually a good trade-off between
797
+ # speed and memory
798
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
799
+ elif slice_size == "max":
800
+ # make smallest slice possible
801
+ slice_size = num_sliceable_layers * [1]
802
+
803
+ slice_size = (
804
+ num_sliceable_layers * [slice_size]
805
+ if not isinstance(slice_size, list)
806
+ else slice_size
807
+ )
808
+
809
+ if len(slice_size) != len(sliceable_head_dims):
810
+ raise ValueError(
811
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
812
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
813
+ )
814
+
815
+ for i in range(len(slice_size)):
816
+ size = slice_size[i]
817
+ dim = sliceable_head_dims[i]
818
+ if size is not None and size > dim:
819
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
820
+
821
+ # Recursively walk through all the children.
822
+ # Any children which exposes the set_attention_slice method
823
+ # gets the message
824
+ def fn_recursive_set_attention_slice(
825
+ module: torch.nn.Module, slice_size: List[int]
826
+ ):
827
+ if hasattr(module, "set_attention_slice"):
828
+ module.set_attention_slice(slice_size.pop())
829
+
830
+ for child in module.children():
831
+ fn_recursive_set_attention_slice(child, slice_size)
832
+
833
+ reversed_slice_size = list(reversed(slice_size))
834
+ for module in self.children():
835
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
836
+
837
+ def _set_gradient_checkpointing(self, module, value=False):
838
+ if hasattr(module, "gradient_checkpointing"):
839
+ module.gradient_checkpointing = value
840
+
841
+ def enable_freeu(self, s1, s2, b1, b2):
842
+ r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
843
+
844
+ The suffixes after the scaling factors represent the stage blocks where they are being applied.
845
+
846
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
847
+ are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
848
+
849
+ Args:
850
+ s1 (`float`):
851
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
852
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
853
+ s2 (`float`):
854
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
855
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
856
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
857
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
858
+ """
859
+ for i, upsample_block in enumerate(self.up_blocks):
860
+ setattr(upsample_block, "s1", s1)
861
+ setattr(upsample_block, "s2", s2)
862
+ setattr(upsample_block, "b1", b1)
863
+ setattr(upsample_block, "b2", b2)
864
+
865
+ def disable_freeu(self):
866
+ """Disables the FreeU mechanism."""
867
+ freeu_keys = {"s1", "s2", "b1", "b2"}
868
+ for i, upsample_block in enumerate(self.up_blocks):
869
+ for k in freeu_keys:
870
+ if (
871
+ hasattr(upsample_block, k)
872
+ or getattr(upsample_block, k, None) is not None
873
+ ):
874
+ setattr(upsample_block, k, None)
875
+
876
+ def forward(
877
+ self,
878
+ sample: torch.FloatTensor,
879
+ timestep: Union[torch.Tensor, float, int],
880
+ encoder_hidden_states: torch.Tensor,
881
+ class_labels: Optional[torch.Tensor] = None,
882
+ timestep_cond: Optional[torch.Tensor] = None,
883
+ attention_mask: Optional[torch.Tensor] = None,
884
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
885
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
886
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
887
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
888
+ down_intrablock_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
889
+ encoder_attention_mask: Optional[torch.Tensor] = None,
890
+ return_dict: bool = True,
891
+ ) -> Union[UNet2DConditionOutput, Tuple]:
892
+ r"""
893
+ The [`UNet2DConditionModel`] forward method.
894
+
895
+ Args:
896
+ sample (`torch.FloatTensor`):
897
+ The noisy input tensor with the following shape `(batch, channel, height, width)`.
898
+ timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
899
+ encoder_hidden_states (`torch.FloatTensor`):
900
+ The encoder hidden states with shape `(batch, sequence_length, feature_dim)`.
901
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
902
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
903
+ timestep_cond: (`torch.Tensor`, *optional*, defaults to `None`):
904
+ Conditional embeddings for timestep. If provided, the embeddings will be summed with the samples passed
905
+ through the `self.time_embedding` layer to obtain the timestep embeddings.
906
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
907
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
908
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
909
+ negative values to the attention scores corresponding to "discard" tokens.
910
+ cross_attention_kwargs (`dict`, *optional*):
911
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
912
+ `self.processor` in
913
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
914
+ added_cond_kwargs: (`dict`, *optional*):
915
+ A kwargs dictionary containing additional embeddings that if specified are added to the embeddings that
916
+ are passed along to the UNet blocks.
917
+ down_block_additional_residuals: (`tuple` of `torch.Tensor`, *optional*):
918
+ A tuple of tensors that if specified are added to the residuals of down unet blocks.
919
+ mid_block_additional_residual: (`torch.Tensor`, *optional*):
920
+ A tensor that if specified is added to the residual of the middle unet block.
921
+ encoder_attention_mask (`torch.Tensor`):
922
+ A cross-attention mask of shape `(batch, sequence_length)` is applied to `encoder_hidden_states`. If
923
+ `True` the mask is kept, otherwise if `False` it is discarded. Mask will be converted into a bias,
924
+ which adds large negative values to the attention scores corresponding to "discard" tokens.
925
+ return_dict (`bool`, *optional*, defaults to `True`):
926
+ Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
927
+ tuple.
928
+ cross_attention_kwargs (`dict`, *optional*):
929
+ A kwargs dictionary that if specified is passed along to the [`AttnProcessor`].
930
+ added_cond_kwargs: (`dict`, *optional*):
931
+ A kwargs dictionary containin additional embeddings that if specified are added to the embeddings that
932
+ are passed along to the UNet blocks.
933
+ down_block_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
934
+ additional residuals to be added to UNet long skip connections from down blocks to up blocks for
935
+ example from ControlNet side model(s)
936
+ mid_block_additional_residual (`torch.Tensor`, *optional*):
937
+ additional residual to be added to UNet mid block output, for example from ControlNet side model
938
+ down_intrablock_additional_residuals (`tuple` of `torch.Tensor`, *optional*):
939
+ additional residuals to be added within UNet down blocks, for example from T2I-Adapter side model(s)
940
+
941
+ Returns:
942
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
943
+ If `return_dict` is True, an [`~models.unet_2d_condition.UNet2DConditionOutput`] is returned, otherwise
944
+ a `tuple` is returned where the first element is the sample tensor.
945
+ """
946
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
947
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layers).
948
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
949
+ # on the fly if necessary.
950
+ default_overall_up_factor = 2**self.num_upsamplers
951
+
952
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
953
+ forward_upsample_size = False
954
+ upsample_size = None
955
+
956
+ for dim in sample.shape[-2:]:
957
+ if dim % default_overall_up_factor != 0:
958
+ # Forward upsample size to force interpolation output size.
959
+ forward_upsample_size = True
960
+ break
961
+
962
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension
963
+ # expects mask of shape:
964
+ # [batch, key_tokens]
965
+ # adds singleton query_tokens dimension:
966
+ # [batch, 1, key_tokens]
967
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
968
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
969
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
970
+ if attention_mask is not None:
971
+ # assume that mask is expressed as:
972
+ # (1 = keep, 0 = discard)
973
+ # convert mask into a bias that can be added to attention scores:
974
+ # (keep = +0, discard = -10000.0)
975
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
976
+ attention_mask = attention_mask.unsqueeze(1)
977
+
978
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
979
+ if encoder_attention_mask is not None:
980
+ encoder_attention_mask = (
981
+ 1 - encoder_attention_mask.to(sample.dtype)
982
+ ) * -10000.0
983
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
984
+
985
+ # 0. center input if necessary
986
+ if self.config.center_input_sample:
987
+ sample = 2 * sample - 1.0
988
+
989
+ # 1. time
990
+ timesteps = timestep
991
+ if not torch.is_tensor(timesteps):
992
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
993
+ # This would be a good case for the `match` statement (Python 3.10+)
994
+ is_mps = sample.device.type == "mps"
995
+ if isinstance(timestep, float):
996
+ dtype = torch.float32 if is_mps else torch.float64
997
+ else:
998
+ dtype = torch.int32 if is_mps else torch.int64
999
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
1000
+ elif len(timesteps.shape) == 0:
1001
+ timesteps = timesteps[None].to(sample.device)
1002
+
1003
+
1004
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1005
+ timesteps = timesteps.expand(sample.shape[0])
1006
+
1007
+ t_emb = self.time_proj(timesteps)
1008
+
1009
+ # `Timesteps` does not contain any weights and will always return f32 tensors
1010
+ # but time_embedding might actually be running in fp16. so we need to cast here.
1011
+ # there might be better ways to encapsulate this.
1012
+ t_emb = t_emb.to(dtype=sample.dtype)
1013
+
1014
+ emb = self.time_embedding(t_emb, timestep_cond)
1015
+ aug_emb = None
1016
+
1017
+ if self.class_embedding is not None:
1018
+ if class_labels is None:
1019
+ raise ValueError(
1020
+ "class_labels should be provided when num_class_embeds > 0"
1021
+ )
1022
+
1023
+ if self.config.class_embed_type == "timestep":
1024
+ class_labels = self.time_proj(class_labels)
1025
+
1026
+ # `Timesteps` does not contain any weights and will always return f32 tensors
1027
+ # there might be better ways to encapsulate this.
1028
+ class_labels = class_labels.to(dtype=sample.dtype)
1029
+
1030
+ class_emb = self.class_embedding(class_labels).to(dtype=sample.dtype)
1031
+
1032
+ if self.config.class_embeddings_concat:
1033
+ emb = torch.cat([emb, class_emb], dim=-1)
1034
+ else:
1035
+ emb = emb + class_emb
1036
+
1037
+ if self.config.addition_embed_type == "text":
1038
+ aug_emb = self.add_embedding(encoder_hidden_states)
1039
+ elif self.config.addition_embed_type == "text_image":
1040
+ # Kandinsky 2.1 - style
1041
+ if "image_embeds" not in added_cond_kwargs:
1042
+ raise ValueError(
1043
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
1044
+ )
1045
+
1046
+ image_embs = added_cond_kwargs.get("image_embeds")
1047
+ text_embs = added_cond_kwargs.get("text_embeds", encoder_hidden_states)
1048
+ aug_emb = self.add_embedding(text_embs, image_embs)
1049
+ elif self.config.addition_embed_type == "text_time":
1050
+ # SDXL - style
1051
+ if "text_embeds" not in added_cond_kwargs:
1052
+ raise ValueError(
1053
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `text_embeds` to be passed in `added_cond_kwargs`"
1054
+ )
1055
+ text_embeds = added_cond_kwargs.get("text_embeds")
1056
+ if "time_ids" not in added_cond_kwargs:
1057
+ raise ValueError(
1058
+ f"{self.__class__} has the config param `addition_embed_type` set to 'text_time' which requires the keyword argument `time_ids` to be passed in `added_cond_kwargs`"
1059
+ )
1060
+ time_ids = added_cond_kwargs.get("time_ids")
1061
+ time_embeds = self.add_time_proj(time_ids.flatten())
1062
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1063
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1064
+ add_embeds = add_embeds.to(emb.dtype)
1065
+ aug_emb = self.add_embedding(add_embeds)
1066
+ elif self.config.addition_embed_type == "image":
1067
+ # Kandinsky 2.2 - style
1068
+ if "image_embeds" not in added_cond_kwargs:
1069
+ raise ValueError(
1070
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image' which requires the keyword argument `image_embeds` to be passed in `added_cond_kwargs`"
1071
+ )
1072
+ image_embs = added_cond_kwargs.get("image_embeds")
1073
+ aug_emb = self.add_embedding(image_embs)
1074
+ elif self.config.addition_embed_type == "image_hint":
1075
+ # Kandinsky 2.2 - style
1076
+ if (
1077
+ "image_embeds" not in added_cond_kwargs
1078
+ or "hint" not in added_cond_kwargs
1079
+ ):
1080
+ raise ValueError(
1081
+ f"{self.__class__} has the config param `addition_embed_type` set to 'image_hint' which requires the keyword arguments `image_embeds` and `hint` to be passed in `added_cond_kwargs`"
1082
+ )
1083
+ image_embs = added_cond_kwargs.get("image_embeds")
1084
+ hint = added_cond_kwargs.get("hint")
1085
+ aug_emb, hint = self.add_embedding(image_embs, hint)
1086
+ sample = torch.cat([sample, hint], dim=1)
1087
+
1088
+ emb = emb + aug_emb if aug_emb is not None else emb
1089
+
1090
+ if self.time_embed_act is not None:
1091
+ emb = self.time_embed_act(emb)
1092
+
1093
+ if (
1094
+ self.encoder_hid_proj is not None
1095
+ and self.config.encoder_hid_dim_type == "text_proj"
1096
+ ):
1097
+ encoder_hidden_states = self.encoder_hid_proj(encoder_hidden_states)
1098
+ elif (
1099
+ self.encoder_hid_proj is not None
1100
+ and self.config.encoder_hid_dim_type == "text_image_proj"
1101
+ ):
1102
+ # Kadinsky 2.1 - style
1103
+ if "image_embeds" not in added_cond_kwargs:
1104
+ raise ValueError(
1105
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'text_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1106
+ )
1107
+
1108
+ image_embeds = added_cond_kwargs.get("image_embeds")
1109
+ encoder_hidden_states = self.encoder_hid_proj(
1110
+ encoder_hidden_states, image_embeds
1111
+ )
1112
+ elif (
1113
+ self.encoder_hid_proj is not None
1114
+ and self.config.encoder_hid_dim_type == "image_proj"
1115
+ ):
1116
+ # Kandinsky 2.2 - style
1117
+ if "image_embeds" not in added_cond_kwargs:
1118
+ raise ValueError(
1119
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1120
+ )
1121
+ image_embeds = added_cond_kwargs.get("image_embeds")
1122
+ encoder_hidden_states = self.encoder_hid_proj(image_embeds)
1123
+ elif (
1124
+ self.encoder_hid_proj is not None
1125
+ and self.config.encoder_hid_dim_type == "ip_image_proj"
1126
+ ):
1127
+ if "image_embeds" not in added_cond_kwargs:
1128
+ raise ValueError(
1129
+ f"{self.__class__} has the config param `encoder_hid_dim_type` set to 'ip_image_proj' which requires the keyword argument `image_embeds` to be passed in `added_conditions`"
1130
+ )
1131
+ image_embeds = added_cond_kwargs.get("image_embeds")
1132
+ image_embeds = self.encoder_hid_proj(image_embeds).to(
1133
+ encoder_hidden_states.dtype
1134
+ )
1135
+ encoder_hidden_states = torch.cat(
1136
+ [encoder_hidden_states, image_embeds], dim=1
1137
+ )
1138
+
1139
+ # 2. pre-process
1140
+ sample = self.conv_in(sample)
1141
+
1142
+ # 2.5 GLIGEN position net
1143
+ if (
1144
+ cross_attention_kwargs is not None
1145
+ and cross_attention_kwargs.get("gligen", None) is not None
1146
+ ):
1147
+ cross_attention_kwargs = cross_attention_kwargs.copy()
1148
+ gligen_args = cross_attention_kwargs.pop("gligen")
1149
+ cross_attention_kwargs["gligen"] = {
1150
+ "objs": self.position_net(**gligen_args)
1151
+ }
1152
+
1153
+ # 3. down
1154
+ lora_scale = (
1155
+ cross_attention_kwargs.get("scale", 1.0)
1156
+ if cross_attention_kwargs is not None
1157
+ else 1.0
1158
+ )
1159
+ if USE_PEFT_BACKEND:
1160
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1161
+ scale_lora_layers(self, lora_scale)
1162
+
1163
+ is_controlnet = (
1164
+ mid_block_additional_residual is not None
1165
+ and down_block_additional_residuals is not None
1166
+ )
1167
+ # using new arg down_intrablock_additional_residuals for T2I-Adapters, to distinguish from controlnets
1168
+ is_adapter = down_intrablock_additional_residuals is not None
1169
+ # maintain backward compatibility for legacy usage, where
1170
+ # T2I-Adapter and ControlNet both use down_block_additional_residuals arg
1171
+ # but can only use one or the other
1172
+ if (
1173
+ not is_adapter
1174
+ and mid_block_additional_residual is None
1175
+ and down_block_additional_residuals is not None
1176
+ ):
1177
+ deprecate(
1178
+ "T2I should not use down_block_additional_residuals",
1179
+ "1.3.0",
1180
+ "Passing intrablock residual connections with `down_block_additional_residuals` is deprecated \
1181
+ and will be removed in diffusers 1.3.0. `down_block_additional_residuals` should only be used \
1182
+ for ControlNet. Please make sure use `down_intrablock_additional_residuals` instead. ",
1183
+ standard_warn=False,
1184
+ )
1185
+ down_intrablock_additional_residuals = down_block_additional_residuals
1186
+ is_adapter = True
1187
+
1188
+ down_block_res_samples = (sample,)
1189
+ tot_referece_features = ()
1190
+ for downsample_block in self.down_blocks:
1191
+ if (
1192
+ hasattr(downsample_block, "has_cross_attention")
1193
+ and downsample_block.has_cross_attention
1194
+ ):
1195
+ # For t2i-adapter CrossAttnDownBlock2D
1196
+ additional_residuals = {}
1197
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1198
+ additional_residuals["additional_residuals"] = (
1199
+ down_intrablock_additional_residuals.pop(0)
1200
+ )
1201
+
1202
+ sample, res_samples = downsample_block(
1203
+ hidden_states=sample,
1204
+ temb=emb,
1205
+ encoder_hidden_states=encoder_hidden_states,
1206
+ attention_mask=attention_mask,
1207
+ cross_attention_kwargs=cross_attention_kwargs,
1208
+ encoder_attention_mask=encoder_attention_mask,
1209
+ **additional_residuals,
1210
+ )
1211
+ else:
1212
+ sample, res_samples = downsample_block(
1213
+ hidden_states=sample, temb=emb, scale=lora_scale
1214
+ )
1215
+ if is_adapter and len(down_intrablock_additional_residuals) > 0:
1216
+ sample += down_intrablock_additional_residuals.pop(0)
1217
+
1218
+ down_block_res_samples += res_samples
1219
+
1220
+ if is_controlnet:
1221
+ new_down_block_res_samples = ()
1222
+
1223
+ for down_block_res_sample, down_block_additional_residual in zip(
1224
+ down_block_res_samples, down_block_additional_residuals
1225
+ ):
1226
+ down_block_res_sample = (
1227
+ down_block_res_sample + down_block_additional_residual
1228
+ )
1229
+ new_down_block_res_samples = new_down_block_res_samples + (
1230
+ down_block_res_sample,
1231
+ )
1232
+
1233
+ down_block_res_samples = new_down_block_res_samples
1234
+
1235
+ # 4. mid
1236
+ if self.mid_block is not None:
1237
+ if (
1238
+ hasattr(self.mid_block, "has_cross_attention")
1239
+ and self.mid_block.has_cross_attention
1240
+ ):
1241
+ sample = self.mid_block(
1242
+ sample,
1243
+ emb,
1244
+ encoder_hidden_states=encoder_hidden_states,
1245
+ attention_mask=attention_mask,
1246
+ cross_attention_kwargs=cross_attention_kwargs,
1247
+ encoder_attention_mask=encoder_attention_mask,
1248
+ )
1249
+ else:
1250
+ sample = self.mid_block(sample, emb)
1251
+
1252
+ # To support T2I-Adapter-XL
1253
+ if (
1254
+ is_adapter
1255
+ and len(down_intrablock_additional_residuals) > 0
1256
+ and sample.shape == down_intrablock_additional_residuals[0].shape
1257
+ ):
1258
+ sample += down_intrablock_additional_residuals.pop(0)
1259
+
1260
+ if is_controlnet:
1261
+ sample = sample + mid_block_additional_residual
1262
+
1263
+ # 5. up
1264
+ for i, upsample_block in enumerate(self.up_blocks):
1265
+ is_final_block = i == len(self.up_blocks) - 1
1266
+
1267
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
1268
+ down_block_res_samples = down_block_res_samples[
1269
+ : -len(upsample_block.resnets)
1270
+ ]
1271
+
1272
+ # if we have not reached the final block and need to forward the
1273
+ # upsample size, we do it here
1274
+ if not is_final_block and forward_upsample_size:
1275
+ upsample_size = down_block_res_samples[-1].shape[2:]
1276
+
1277
+ if (
1278
+ hasattr(upsample_block, "has_cross_attention")
1279
+ and upsample_block.has_cross_attention
1280
+ ):
1281
+ sample = upsample_block(
1282
+ hidden_states=sample,
1283
+ temb=emb,
1284
+ res_hidden_states_tuple=res_samples,
1285
+ encoder_hidden_states=encoder_hidden_states,
1286
+ cross_attention_kwargs=cross_attention_kwargs,
1287
+ upsample_size=upsample_size,
1288
+ attention_mask=attention_mask,
1289
+ encoder_attention_mask=encoder_attention_mask,
1290
+ )
1291
+ else:
1292
+ sample = upsample_block(
1293
+ hidden_states=sample,
1294
+ temb=emb,
1295
+ res_hidden_states_tuple=res_samples,
1296
+ upsample_size=upsample_size,
1297
+ scale=lora_scale,
1298
+ )
1299
+
1300
+ # 6. post-process
1301
+ # if self.conv_norm_out:
1302
+ # sample = self.conv_norm_out(sample)
1303
+ # sample = self.conv_act(sample)
1304
+ # sample = self.conv_out(sample)
1305
+
1306
+ if USE_PEFT_BACKEND:
1307
+ # remove `lora_scale` from each PEFT layer
1308
+ unscale_lora_layers(self, lora_scale)
1309
+
1310
+ if not return_dict:
1311
+ return (sample,)
1312
+
1313
+ return UNet2DConditionOutput(sample=sample)
2610_variant_runtime/diffusion/models/unet_3d.py ADDED
@@ -0,0 +1,668 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/guoyww/AnimateDiff/blob/main/animatediff/models/unet_blocks.py
2
+
3
+ from collections import OrderedDict
4
+ from dataclasses import dataclass
5
+ from os import PathLike
6
+ from pathlib import Path
7
+ from typing import Dict, List, Optional, Tuple, Union
8
+
9
+ import torch
10
+ import torch.nn as nn
11
+ import torch.utils.checkpoint
12
+ from diffusers.configuration_utils import ConfigMixin, register_to_config
13
+ from diffusers.models.attention_processor import AttentionProcessor
14
+ from diffusers.models.embeddings import TimestepEmbedding, Timesteps
15
+ from diffusers.models.modeling_utils import ModelMixin
16
+ from diffusers.utils import SAFETENSORS_WEIGHTS_NAME, WEIGHTS_NAME, BaseOutput, logging
17
+ from safetensors.torch import load_file
18
+
19
+ from .resnet import InflatedConv3d, InflatedGroupNorm
20
+ from .unet_3d_blocks import UNetMidBlock3DCrossAttn, get_down_block, get_up_block
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+
25
+ @dataclass
26
+ class UNet3DConditionOutput(BaseOutput):
27
+ sample: torch.FloatTensor
28
+
29
+
30
+ class UNet3DConditionModel(ModelMixin, ConfigMixin):
31
+ _supports_gradient_checkpointing = True
32
+
33
+ @register_to_config
34
+ def __init__(
35
+ self,
36
+ sample_size: Optional[int] = None,
37
+ in_channels: int = 4,
38
+ out_channels: int = 4,
39
+ center_input_sample: bool = False,
40
+ flip_sin_to_cos: bool = True,
41
+ freq_shift: int = 0,
42
+ down_block_types: Tuple[str] = (
43
+ "CrossAttnDownBlock3D",
44
+ "CrossAttnDownBlock3D",
45
+ "CrossAttnDownBlock3D",
46
+ "DownBlock3D",
47
+ ),
48
+ mid_block_type: str = "UNetMidBlock3DCrossAttn",
49
+ up_block_types: Tuple[str] = (
50
+ "UpBlock3D",
51
+ "CrossAttnUpBlock3D",
52
+ "CrossAttnUpBlock3D",
53
+ "CrossAttnUpBlock3D",
54
+ ),
55
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
56
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
57
+ layers_per_block: int = 2,
58
+ downsample_padding: int = 1,
59
+ mid_block_scale_factor: float = 1,
60
+ act_fn: str = "silu",
61
+ norm_num_groups: int = 32,
62
+ norm_eps: float = 1e-5,
63
+ cross_attention_dim: int = 1280,
64
+ attention_head_dim: Union[int, Tuple[int]] = 8,
65
+ dual_cross_attention: bool = False,
66
+ use_linear_projection: bool = False,
67
+ class_embed_type: Optional[str] = None,
68
+ num_class_embeds: Optional[int] = None,
69
+ upcast_attention: bool = False,
70
+ resnet_time_scale_shift: str = "default",
71
+ use_inflated_groupnorm=False,
72
+ # Additional
73
+ use_motion_module=False,
74
+ motion_module_resolutions=(1, 2, 4, 8),
75
+ motion_module_mid_block=False,
76
+ motion_module_decoder_only=False,
77
+ motion_module_type=None,
78
+ motion_module_kwargs={},
79
+ unet_use_cross_frame_attention=None,
80
+ unet_use_temporal_attention=None,
81
+ ):
82
+ super().__init__()
83
+
84
+ self.sample_size = sample_size
85
+ time_embed_dim = block_out_channels[0] * 4
86
+
87
+ # input
88
+ self.conv_in = InflatedConv3d(
89
+ in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)
90
+ )
91
+
92
+ # time
93
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
94
+ timestep_input_dim = block_out_channels[0]
95
+
96
+ self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
97
+
98
+ # class embedding
99
+ if class_embed_type is None and num_class_embeds is not None:
100
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
101
+ elif class_embed_type == "timestep":
102
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
103
+ elif class_embed_type == "identity":
104
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
105
+ else:
106
+ self.class_embedding = None
107
+
108
+ self.down_blocks = nn.ModuleList([])
109
+ self.mid_block = None
110
+ self.up_blocks = nn.ModuleList([])
111
+
112
+ if isinstance(only_cross_attention, bool):
113
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
114
+
115
+ if isinstance(attention_head_dim, int):
116
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
117
+
118
+ # down
119
+ output_channel = block_out_channels[0]
120
+ for i, down_block_type in enumerate(down_block_types):
121
+ res = 2**i
122
+ input_channel = output_channel
123
+ output_channel = block_out_channels[i]
124
+ is_final_block = i == len(block_out_channels) - 1
125
+
126
+ down_block = get_down_block(
127
+ down_block_type,
128
+ num_layers=layers_per_block,
129
+ in_channels=input_channel,
130
+ out_channels=output_channel,
131
+ temb_channels=time_embed_dim,
132
+ add_downsample=not is_final_block,
133
+ resnet_eps=norm_eps,
134
+ resnet_act_fn=act_fn,
135
+ resnet_groups=norm_num_groups,
136
+ cross_attention_dim=cross_attention_dim,
137
+ attn_num_head_channels=attention_head_dim[i],
138
+ downsample_padding=downsample_padding,
139
+ dual_cross_attention=dual_cross_attention,
140
+ use_linear_projection=use_linear_projection,
141
+ only_cross_attention=only_cross_attention[i],
142
+ upcast_attention=upcast_attention,
143
+ resnet_time_scale_shift=resnet_time_scale_shift,
144
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
145
+ unet_use_temporal_attention=unet_use_temporal_attention,
146
+ use_inflated_groupnorm=use_inflated_groupnorm,
147
+ use_motion_module=use_motion_module
148
+ and (res in motion_module_resolutions)
149
+ and (not motion_module_decoder_only),
150
+ motion_module_type=motion_module_type,
151
+ motion_module_kwargs=motion_module_kwargs,
152
+ )
153
+ self.down_blocks.append(down_block)
154
+
155
+ # mid
156
+ if mid_block_type == "UNetMidBlock3DCrossAttn":
157
+ self.mid_block = UNetMidBlock3DCrossAttn(
158
+ in_channels=block_out_channels[-1],
159
+ temb_channels=time_embed_dim,
160
+ resnet_eps=norm_eps,
161
+ resnet_act_fn=act_fn,
162
+ output_scale_factor=mid_block_scale_factor,
163
+ resnet_time_scale_shift=resnet_time_scale_shift,
164
+ cross_attention_dim=cross_attention_dim,
165
+ attn_num_head_channels=attention_head_dim[-1],
166
+ resnet_groups=norm_num_groups,
167
+ dual_cross_attention=dual_cross_attention,
168
+ use_linear_projection=use_linear_projection,
169
+ upcast_attention=upcast_attention,
170
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
171
+ unet_use_temporal_attention=unet_use_temporal_attention,
172
+ use_inflated_groupnorm=use_inflated_groupnorm,
173
+ use_motion_module=use_motion_module and motion_module_mid_block,
174
+ motion_module_type=motion_module_type,
175
+ motion_module_kwargs=motion_module_kwargs,
176
+ )
177
+ else:
178
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
179
+
180
+ # count how many layers upsample the videos
181
+ self.num_upsamplers = 0
182
+
183
+ # up
184
+ reversed_block_out_channels = list(reversed(block_out_channels))
185
+ reversed_attention_head_dim = list(reversed(attention_head_dim))
186
+ only_cross_attention = list(reversed(only_cross_attention))
187
+ output_channel = reversed_block_out_channels[0]
188
+ for i, up_block_type in enumerate(up_block_types):
189
+ res = 2 ** (3 - i)
190
+ is_final_block = i == len(block_out_channels) - 1
191
+
192
+ prev_output_channel = output_channel
193
+ output_channel = reversed_block_out_channels[i]
194
+ input_channel = reversed_block_out_channels[
195
+ min(i + 1, len(block_out_channels) - 1)
196
+ ]
197
+
198
+ # add upsample block for all BUT final layer
199
+ if not is_final_block:
200
+ add_upsample = True
201
+ self.num_upsamplers += 1
202
+ else:
203
+ add_upsample = False
204
+
205
+ up_block = get_up_block(
206
+ up_block_type,
207
+ num_layers=layers_per_block + 1,
208
+ in_channels=input_channel,
209
+ out_channels=output_channel,
210
+ prev_output_channel=prev_output_channel,
211
+ temb_channels=time_embed_dim,
212
+ add_upsample=add_upsample,
213
+ resnet_eps=norm_eps,
214
+ resnet_act_fn=act_fn,
215
+ resnet_groups=norm_num_groups,
216
+ cross_attention_dim=cross_attention_dim,
217
+ attn_num_head_channels=reversed_attention_head_dim[i],
218
+ dual_cross_attention=dual_cross_attention,
219
+ use_linear_projection=use_linear_projection,
220
+ only_cross_attention=only_cross_attention[i],
221
+ upcast_attention=upcast_attention,
222
+ resnet_time_scale_shift=resnet_time_scale_shift,
223
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
224
+ unet_use_temporal_attention=unet_use_temporal_attention,
225
+ use_inflated_groupnorm=use_inflated_groupnorm,
226
+ use_motion_module=use_motion_module
227
+ and (res in motion_module_resolutions),
228
+ motion_module_type=motion_module_type,
229
+ motion_module_kwargs=motion_module_kwargs,
230
+ )
231
+ self.up_blocks.append(up_block)
232
+ prev_output_channel = output_channel
233
+
234
+ # out
235
+ if use_inflated_groupnorm:
236
+ self.conv_norm_out = InflatedGroupNorm(
237
+ num_channels=block_out_channels[0],
238
+ num_groups=norm_num_groups,
239
+ eps=norm_eps,
240
+ )
241
+ else:
242
+ self.conv_norm_out = nn.GroupNorm(
243
+ num_channels=block_out_channels[0],
244
+ num_groups=norm_num_groups,
245
+ eps=norm_eps,
246
+ )
247
+ self.conv_act = nn.SiLU()
248
+ self.conv_out = InflatedConv3d(
249
+ block_out_channels[0], out_channels, kernel_size=3, padding=1
250
+ )
251
+
252
+ @property
253
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
254
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
255
+ r"""
256
+ Returns:
257
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
258
+ indexed by its weight name.
259
+ """
260
+ # set recursively
261
+ processors = {}
262
+
263
+ def fn_recursive_add_processors(
264
+ name: str,
265
+ module: torch.nn.Module,
266
+ processors: Dict[str, AttentionProcessor],
267
+ ):
268
+ if hasattr(module, "set_processor"):
269
+ processors[f"{name}.processor"] = module.processor
270
+
271
+ for sub_name, child in module.named_children():
272
+ if "temporal_transformer" not in sub_name:
273
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
274
+
275
+ return processors
276
+
277
+ for name, module in self.named_children():
278
+ if "temporal_transformer" not in name:
279
+ fn_recursive_add_processors(name, module, processors)
280
+
281
+ return processors
282
+
283
+ def set_attention_slice(self, slice_size):
284
+ r"""
285
+ Enable sliced attention computation.
286
+
287
+ When this option is enabled, the attention module will split the input tensor in slices, to compute attention
288
+ in several steps. This is useful to save some memory in exchange for a small speed decrease.
289
+
290
+ Args:
291
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
292
+ When `"auto"`, halves the input to the attention heads, so attention will be computed in two steps. If
293
+ `"max"`, maxium amount of memory will be saved by running only one slice at a time. If a number is
294
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
295
+ must be a multiple of `slice_size`.
296
+ """
297
+ sliceable_head_dims = []
298
+
299
+ def fn_recursive_retrieve_slicable_dims(module: torch.nn.Module):
300
+ if hasattr(module, "set_attention_slice"):
301
+ sliceable_head_dims.append(module.sliceable_head_dim)
302
+
303
+ for child in module.children():
304
+ fn_recursive_retrieve_slicable_dims(child)
305
+
306
+ # retrieve number of attention layers
307
+ for module in self.children():
308
+ fn_recursive_retrieve_slicable_dims(module)
309
+
310
+ num_slicable_layers = len(sliceable_head_dims)
311
+
312
+ if slice_size == "auto":
313
+ # half the attention head size is usually a good trade-off between
314
+ # speed and memory
315
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
316
+ elif slice_size == "max":
317
+ # make smallest slice possible
318
+ slice_size = num_slicable_layers * [1]
319
+
320
+ slice_size = (
321
+ num_slicable_layers * [slice_size]
322
+ if not isinstance(slice_size, list)
323
+ else slice_size
324
+ )
325
+
326
+ if len(slice_size) != len(sliceable_head_dims):
327
+ raise ValueError(
328
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
329
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
330
+ )
331
+
332
+ for i in range(len(slice_size)):
333
+ size = slice_size[i]
334
+ dim = sliceable_head_dims[i]
335
+ if size is not None and size > dim:
336
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
337
+
338
+ # Recursively walk through all the children.
339
+ # Any children which exposes the set_attention_slice method
340
+ # gets the message
341
+ def fn_recursive_set_attention_slice(
342
+ module: torch.nn.Module, slice_size: List[int]
343
+ ):
344
+ if hasattr(module, "set_attention_slice"):
345
+ module.set_attention_slice(slice_size.pop())
346
+
347
+ for child in module.children():
348
+ fn_recursive_set_attention_slice(child, slice_size)
349
+
350
+ reversed_slice_size = list(reversed(slice_size))
351
+ for module in self.children():
352
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
353
+
354
+ def _set_gradient_checkpointing(self, module, value=False):
355
+ if hasattr(module, "gradient_checkpointing"):
356
+ module.gradient_checkpointing = value
357
+
358
+ # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.set_attn_processor
359
+ def set_attn_processor(
360
+ self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]
361
+ ):
362
+ r"""
363
+ Sets the attention processor to use to compute attention.
364
+
365
+ Parameters:
366
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
367
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
368
+ for **all** `Attention` layers.
369
+
370
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
371
+ processor. This is strongly recommended when setting trainable attention processors.
372
+
373
+ """
374
+ count = len(self.attn_processors.keys())
375
+
376
+ if isinstance(processor, dict) and len(processor) != count:
377
+ raise ValueError(
378
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
379
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
380
+ )
381
+
382
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
383
+ if hasattr(module, "set_processor"):
384
+ if not isinstance(processor, dict):
385
+ module.set_processor(processor)
386
+ else:
387
+ module.set_processor(processor.pop(f"{name}.processor"))
388
+
389
+ for sub_name, child in module.named_children():
390
+ if "temporal_transformer" not in sub_name:
391
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
392
+
393
+ for name, module in self.named_children():
394
+ if "temporal_transformer" not in name:
395
+ fn_recursive_attn_processor(name, module, processor)
396
+
397
+ def forward(
398
+ self,
399
+ sample: torch.FloatTensor,
400
+ timestep: Union[torch.Tensor, float, int],
401
+ encoder_hidden_states: torch.Tensor,
402
+ class_labels: Optional[torch.Tensor] = None,
403
+ guidance_fea: Optional[torch.Tensor] = None,
404
+ attention_mask: Optional[torch.Tensor] = None,
405
+ down_block_additional_residuals: Optional[Tuple[torch.Tensor]] = None,
406
+ mid_block_additional_residual: Optional[torch.Tensor] = None,
407
+ return_dict: bool = True,
408
+ ) -> Union[UNet3DConditionOutput, Tuple]:
409
+ r"""
410
+ Args:
411
+ sample (`torch.FloatTensor`): (batch, channel, height, width) noisy inputs tensor
412
+ timestep (`torch.FloatTensor` or `float` or `int`): (batch) timesteps
413
+ encoder_hidden_states (`torch.FloatTensor`): (batch, sequence_length, feature_dim) encoder hidden states
414
+ return_dict (`bool`, *optional*, defaults to `True`):
415
+ Whether or not to return a [`models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain tuple.
416
+
417
+ Returns:
418
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] or `tuple`:
419
+ [`~models.unet_2d_condition.UNet2DConditionOutput`] if `return_dict` is True, otherwise a `tuple`. When
420
+ returning a tuple, the first element is the sample tensor.
421
+ """
422
+ # By default samples have to be AT least a multiple of the overall upsampling factor.
423
+ # The overall upsampling factor is equal to 2 ** (# num of upsampling layears).
424
+ # However, the upsampling interpolation output size can be forced to fit any upsampling size
425
+ # on the fly if necessary.
426
+ default_overall_up_factor = 2**self.num_upsamplers
427
+
428
+ # upsample size should be forwarded when sample is not a multiple of `default_overall_up_factor`
429
+ forward_upsample_size = False
430
+ upsample_size = None
431
+
432
+ if any(s % default_overall_up_factor != 0 for s in sample.shape[-2:]):
433
+ logger.info("Forward upsample size to force interpolation output size.")
434
+ forward_upsample_size = True
435
+
436
+ # prepare attention_mask
437
+ if attention_mask is not None:
438
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
439
+ attention_mask = attention_mask.unsqueeze(1)
440
+
441
+ # center input if necessary
442
+ if self.config.center_input_sample:
443
+ sample = 2 * sample - 1.0
444
+
445
+ # time
446
+ timesteps = timestep
447
+ if not torch.is_tensor(timesteps):
448
+ # This would be a good case for the `match` statement (Python 3.10+)
449
+ is_mps = sample.device.type == "mps"
450
+ if isinstance(timestep, float):
451
+ dtype = torch.float32 if is_mps else torch.float64
452
+ else:
453
+ dtype = torch.int32 if is_mps else torch.int64
454
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
455
+ elif len(timesteps.shape) == 0:
456
+ timesteps = timesteps[None].to(sample.device)
457
+
458
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
459
+ timesteps = timesteps.expand(sample.shape[0])
460
+
461
+ t_emb = self.time_proj(timesteps)
462
+
463
+ # timesteps does not contain any weights and will always return f32 tensors
464
+ # but time_embedding might actually be running in fp16. so we need to cast here.
465
+ # there might be better ways to encapsulate this.
466
+ t_emb = t_emb.to(dtype=self.dtype)
467
+ emb = self.time_embedding(t_emb)
468
+
469
+ if self.class_embedding is not None:
470
+ if class_labels is None:
471
+ raise ValueError(
472
+ "class_labels should be provided when num_class_embeds > 0"
473
+ )
474
+
475
+ if self.config.class_embed_type == "timestep":
476
+ class_labels = self.time_proj(class_labels)
477
+
478
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
479
+ emb = emb + class_emb
480
+
481
+ # pre-process
482
+ sample = self.conv_in(sample)
483
+ if guidance_fea is not None:
484
+ sample = sample + guidance_fea
485
+
486
+ # down
487
+ down_block_res_samples = (sample,)
488
+ for downsample_block in self.down_blocks:
489
+ if (
490
+ hasattr(downsample_block, "has_cross_attention")
491
+ and downsample_block.has_cross_attention
492
+ ):
493
+ sample, res_samples = downsample_block(
494
+ hidden_states=sample,
495
+ temb=emb,
496
+ encoder_hidden_states=encoder_hidden_states,
497
+ attention_mask=attention_mask,
498
+ )
499
+ else:
500
+ sample, res_samples = downsample_block(
501
+ hidden_states=sample,
502
+ temb=emb,
503
+ encoder_hidden_states=encoder_hidden_states,
504
+ )
505
+
506
+ down_block_res_samples += res_samples
507
+
508
+ if down_block_additional_residuals is not None:
509
+ new_down_block_res_samples = ()
510
+
511
+ for down_block_res_sample, down_block_additional_residual in zip(
512
+ down_block_res_samples, down_block_additional_residuals
513
+ ):
514
+ down_block_res_sample = (
515
+ down_block_res_sample + down_block_additional_residual
516
+ )
517
+ new_down_block_res_samples += (down_block_res_sample,)
518
+
519
+ down_block_res_samples = new_down_block_res_samples
520
+
521
+ # mid
522
+ sample = self.mid_block(
523
+ sample,
524
+ emb,
525
+ encoder_hidden_states=encoder_hidden_states,
526
+ attention_mask=attention_mask,
527
+ )
528
+
529
+ if mid_block_additional_residual is not None:
530
+ sample = sample + mid_block_additional_residual
531
+
532
+ # up
533
+ for i, upsample_block in enumerate(self.up_blocks):
534
+ is_final_block = i == len(self.up_blocks) - 1
535
+
536
+ res_samples = down_block_res_samples[-len(upsample_block.resnets) :]
537
+ down_block_res_samples = down_block_res_samples[
538
+ : -len(upsample_block.resnets)
539
+ ]
540
+
541
+ # if we have not reached the final block and need to forward the
542
+ # upsample size, we do it here
543
+ if not is_final_block and forward_upsample_size:
544
+ upsample_size = down_block_res_samples[-1].shape[2:]
545
+
546
+ if (
547
+ hasattr(upsample_block, "has_cross_attention")
548
+ and upsample_block.has_cross_attention
549
+ ):
550
+ sample = upsample_block(
551
+ hidden_states=sample,
552
+ temb=emb,
553
+ res_hidden_states_tuple=res_samples,
554
+ encoder_hidden_states=encoder_hidden_states,
555
+ upsample_size=upsample_size,
556
+ attention_mask=attention_mask,
557
+ )
558
+ else:
559
+ sample = upsample_block(
560
+ hidden_states=sample,
561
+ temb=emb,
562
+ res_hidden_states_tuple=res_samples,
563
+ upsample_size=upsample_size,
564
+ encoder_hidden_states=encoder_hidden_states,
565
+ )
566
+
567
+ # post-process
568
+ sample = self.conv_norm_out(sample)
569
+ sample = self.conv_act(sample)
570
+ sample = self.conv_out(sample)
571
+
572
+ if not return_dict:
573
+ return (sample,)
574
+
575
+ return UNet3DConditionOutput(sample=sample)
576
+
577
+ @classmethod
578
+ def from_pretrained_2d(
579
+ cls,
580
+ pretrained_model_path: PathLike,
581
+ motion_module_path: PathLike,
582
+ subfolder=None,
583
+ unet_additional_kwargs=None,
584
+ mm_zero_proj_out=False,
585
+ ):
586
+ pretrained_model_path = Path(pretrained_model_path)
587
+ motion_module_path = Path(motion_module_path)
588
+ if subfolder is not None:
589
+ pretrained_model_path = pretrained_model_path.joinpath(subfolder)
590
+ logger.info(
591
+ f"loaded temporal unet's pretrained weights from {pretrained_model_path} ..."
592
+ )
593
+
594
+ config_file = pretrained_model_path / "config.json"
595
+ if not (config_file.exists() and config_file.is_file()):
596
+ raise RuntimeError(f"{config_file} does not exist or is not a file")
597
+
598
+ unet_config = cls.load_config(config_file)
599
+ unet_config["_class_name"] = cls.__name__
600
+ unet_config["down_block_types"] = [
601
+ "CrossAttnDownBlock3D",
602
+ "CrossAttnDownBlock3D",
603
+ "CrossAttnDownBlock3D",
604
+ "DownBlock3D",
605
+ ]
606
+ unet_config["up_block_types"] = [
607
+ "UpBlock3D",
608
+ "CrossAttnUpBlock3D",
609
+ "CrossAttnUpBlock3D",
610
+ "CrossAttnUpBlock3D",
611
+ ]
612
+ unet_config["mid_block_type"] = "UNetMidBlock3DCrossAttn"
613
+
614
+ model = cls.from_config(unet_config, **unet_additional_kwargs)
615
+ # load the vanilla weights
616
+ if pretrained_model_path.joinpath(SAFETENSORS_WEIGHTS_NAME).exists():
617
+ logger.debug(
618
+ f"loading safeTensors weights from {pretrained_model_path} ..."
619
+ )
620
+ state_dict = load_file(
621
+ pretrained_model_path.joinpath(SAFETENSORS_WEIGHTS_NAME), device="cpu"
622
+ )
623
+
624
+ elif pretrained_model_path.joinpath(WEIGHTS_NAME).exists():
625
+ logger.debug(f"loading weights from {pretrained_model_path} ...")
626
+ state_dict = torch.load(
627
+ pretrained_model_path.joinpath(WEIGHTS_NAME),
628
+ map_location="cpu",
629
+ weights_only=True,
630
+ )
631
+ else:
632
+ raise FileNotFoundError(f"no weights file found in {pretrained_model_path}")
633
+
634
+ # load the motion module weights
635
+ if motion_module_path.exists() and motion_module_path.is_file():
636
+ if motion_module_path.suffix.lower() in [".pth", ".pt", ".ckpt"]:
637
+ logger.info(f"Load motion module params from {motion_module_path}")
638
+ motion_state_dict = torch.load(
639
+ motion_module_path, map_location="cpu", weights_only=True
640
+ )
641
+ elif motion_module_path.suffix.lower() == ".safetensors":
642
+ motion_state_dict = load_file(motion_module_path, device="cpu")
643
+ else:
644
+ raise RuntimeError(
645
+ f"unknown file format for motion module weights: {motion_module_path.suffix}"
646
+ )
647
+ if mm_zero_proj_out:
648
+ logger.info(f"Zero initialize proj_out layers in motion module...")
649
+ new_motion_state_dict = OrderedDict()
650
+ for k in motion_state_dict:
651
+ if "proj_out" in k:
652
+ continue
653
+ new_motion_state_dict[k] = motion_state_dict[k]
654
+ motion_state_dict = new_motion_state_dict
655
+
656
+ # merge the state dicts
657
+ state_dict.update(motion_state_dict)
658
+
659
+ # load the weights into the model
660
+ m, u = model.load_state_dict(state_dict, strict=False)
661
+ logger.debug(f"### missing keys: {len(m)}; \n### unexpected keys: {len(u)};")
662
+
663
+ params = [
664
+ p.numel() if "temporal" in n else 0 for n, p in model.named_parameters()
665
+ ]
666
+ logger.info(f"Loaded {sum(params) / 1e6}M-parameter motion module")
667
+
668
+ return model
2610_variant_runtime/diffusion/models/unet_3d_blocks.py ADDED
@@ -0,0 +1,863 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Adapted from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/unet_2d_blocks.py
2
+
3
+ import pdb
4
+
5
+ import torch
6
+ from torch import nn
7
+
8
+ from .motion_module import get_motion_module
9
+
10
+ # from .motion_module import get_motion_module
11
+ from .resnet import Downsample3D, ResnetBlock3D, Upsample3D
12
+ from .transformer_3d import Transformer3DModel
13
+
14
+
15
+ def get_down_block(
16
+ down_block_type,
17
+ num_layers,
18
+ in_channels,
19
+ out_channels,
20
+ temb_channels,
21
+ add_downsample,
22
+ resnet_eps,
23
+ resnet_act_fn,
24
+ attn_num_head_channels,
25
+ resnet_groups=None,
26
+ cross_attention_dim=None,
27
+ downsample_padding=None,
28
+ dual_cross_attention=False,
29
+ use_linear_projection=False,
30
+ only_cross_attention=False,
31
+ upcast_attention=False,
32
+ resnet_time_scale_shift="default",
33
+ unet_use_cross_frame_attention=None,
34
+ unet_use_temporal_attention=None,
35
+ use_inflated_groupnorm=None,
36
+ use_motion_module=None,
37
+ motion_module_type=None,
38
+ motion_module_kwargs=None,
39
+ ):
40
+ down_block_type = (
41
+ down_block_type[7:]
42
+ if down_block_type.startswith("UNetRes")
43
+ else down_block_type
44
+ )
45
+ if down_block_type == "DownBlock3D":
46
+ return DownBlock3D(
47
+ num_layers=num_layers,
48
+ in_channels=in_channels,
49
+ out_channels=out_channels,
50
+ temb_channels=temb_channels,
51
+ add_downsample=add_downsample,
52
+ resnet_eps=resnet_eps,
53
+ resnet_act_fn=resnet_act_fn,
54
+ resnet_groups=resnet_groups,
55
+ downsample_padding=downsample_padding,
56
+ resnet_time_scale_shift=resnet_time_scale_shift,
57
+ use_inflated_groupnorm=use_inflated_groupnorm,
58
+ use_motion_module=use_motion_module,
59
+ motion_module_type=motion_module_type,
60
+ motion_module_kwargs=motion_module_kwargs,
61
+ )
62
+ elif down_block_type == "CrossAttnDownBlock3D":
63
+ if cross_attention_dim is None:
64
+ raise ValueError(
65
+ "cross_attention_dim must be specified for CrossAttnDownBlock3D"
66
+ )
67
+ return CrossAttnDownBlock3D(
68
+ num_layers=num_layers,
69
+ in_channels=in_channels,
70
+ out_channels=out_channels,
71
+ temb_channels=temb_channels,
72
+ add_downsample=add_downsample,
73
+ resnet_eps=resnet_eps,
74
+ resnet_act_fn=resnet_act_fn,
75
+ resnet_groups=resnet_groups,
76
+ downsample_padding=downsample_padding,
77
+ cross_attention_dim=cross_attention_dim,
78
+ attn_num_head_channels=attn_num_head_channels,
79
+ dual_cross_attention=dual_cross_attention,
80
+ use_linear_projection=use_linear_projection,
81
+ only_cross_attention=only_cross_attention,
82
+ upcast_attention=upcast_attention,
83
+ resnet_time_scale_shift=resnet_time_scale_shift,
84
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
85
+ unet_use_temporal_attention=unet_use_temporal_attention,
86
+ use_inflated_groupnorm=use_inflated_groupnorm,
87
+ use_motion_module=use_motion_module,
88
+ motion_module_type=motion_module_type,
89
+ motion_module_kwargs=motion_module_kwargs,
90
+ )
91
+ raise ValueError(f"{down_block_type} does not exist.")
92
+
93
+
94
+ def get_up_block(
95
+ up_block_type,
96
+ num_layers,
97
+ in_channels,
98
+ out_channels,
99
+ prev_output_channel,
100
+ temb_channels,
101
+ add_upsample,
102
+ resnet_eps,
103
+ resnet_act_fn,
104
+ attn_num_head_channels,
105
+ resnet_groups=None,
106
+ cross_attention_dim=None,
107
+ dual_cross_attention=False,
108
+ use_linear_projection=False,
109
+ only_cross_attention=False,
110
+ upcast_attention=False,
111
+ resnet_time_scale_shift="default",
112
+ unet_use_cross_frame_attention=None,
113
+ unet_use_temporal_attention=None,
114
+ use_inflated_groupnorm=None,
115
+ use_motion_module=None,
116
+ motion_module_type=None,
117
+ motion_module_kwargs=None,
118
+ ):
119
+ up_block_type = (
120
+ up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
121
+ )
122
+ if up_block_type == "UpBlock3D":
123
+ return UpBlock3D(
124
+ num_layers=num_layers,
125
+ in_channels=in_channels,
126
+ out_channels=out_channels,
127
+ prev_output_channel=prev_output_channel,
128
+ temb_channels=temb_channels,
129
+ add_upsample=add_upsample,
130
+ resnet_eps=resnet_eps,
131
+ resnet_act_fn=resnet_act_fn,
132
+ resnet_groups=resnet_groups,
133
+ resnet_time_scale_shift=resnet_time_scale_shift,
134
+ use_inflated_groupnorm=use_inflated_groupnorm,
135
+ use_motion_module=use_motion_module,
136
+ motion_module_type=motion_module_type,
137
+ motion_module_kwargs=motion_module_kwargs,
138
+ )
139
+ elif up_block_type == "CrossAttnUpBlock3D":
140
+ if cross_attention_dim is None:
141
+ raise ValueError(
142
+ "cross_attention_dim must be specified for CrossAttnUpBlock3D"
143
+ )
144
+ return CrossAttnUpBlock3D(
145
+ num_layers=num_layers,
146
+ in_channels=in_channels,
147
+ out_channels=out_channels,
148
+ prev_output_channel=prev_output_channel,
149
+ temb_channels=temb_channels,
150
+ add_upsample=add_upsample,
151
+ resnet_eps=resnet_eps,
152
+ resnet_act_fn=resnet_act_fn,
153
+ resnet_groups=resnet_groups,
154
+ cross_attention_dim=cross_attention_dim,
155
+ attn_num_head_channels=attn_num_head_channels,
156
+ dual_cross_attention=dual_cross_attention,
157
+ use_linear_projection=use_linear_projection,
158
+ only_cross_attention=only_cross_attention,
159
+ upcast_attention=upcast_attention,
160
+ resnet_time_scale_shift=resnet_time_scale_shift,
161
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
162
+ unet_use_temporal_attention=unet_use_temporal_attention,
163
+ use_inflated_groupnorm=use_inflated_groupnorm,
164
+ use_motion_module=use_motion_module,
165
+ motion_module_type=motion_module_type,
166
+ motion_module_kwargs=motion_module_kwargs,
167
+ )
168
+ raise ValueError(f"{up_block_type} does not exist.")
169
+
170
+
171
+ class UNetMidBlock3DCrossAttn(nn.Module):
172
+ def __init__(
173
+ self,
174
+ in_channels: int,
175
+ temb_channels: int,
176
+ dropout: float = 0.0,
177
+ num_layers: int = 1,
178
+ resnet_eps: float = 1e-6,
179
+ resnet_time_scale_shift: str = "default",
180
+ resnet_act_fn: str = "swish",
181
+ resnet_groups: int = 32,
182
+ resnet_pre_norm: bool = True,
183
+ attn_num_head_channels=1,
184
+ output_scale_factor=1.0,
185
+ cross_attention_dim=1280,
186
+ dual_cross_attention=False,
187
+ use_linear_projection=False,
188
+ upcast_attention=False,
189
+ unet_use_cross_frame_attention=None,
190
+ unet_use_temporal_attention=None,
191
+ use_inflated_groupnorm=None,
192
+ use_motion_module=None,
193
+ motion_module_type=None,
194
+ motion_module_kwargs=None,
195
+ ):
196
+ super().__init__()
197
+
198
+ self.has_cross_attention = True
199
+ self.attn_num_head_channels = attn_num_head_channels
200
+ resnet_groups = (
201
+ resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
202
+ )
203
+
204
+ # there is always at least one resnet
205
+ resnets = [
206
+ ResnetBlock3D(
207
+ in_channels=in_channels,
208
+ out_channels=in_channels,
209
+ temb_channels=temb_channels,
210
+ eps=resnet_eps,
211
+ groups=resnet_groups,
212
+ dropout=dropout,
213
+ time_embedding_norm=resnet_time_scale_shift,
214
+ non_linearity=resnet_act_fn,
215
+ output_scale_factor=output_scale_factor,
216
+ pre_norm=resnet_pre_norm,
217
+ use_inflated_groupnorm=use_inflated_groupnorm,
218
+ )
219
+ ]
220
+ attentions = []
221
+ motion_modules = []
222
+
223
+ for _ in range(num_layers):
224
+ if dual_cross_attention:
225
+ raise NotImplementedError
226
+ attentions.append(
227
+ Transformer3DModel(
228
+ attn_num_head_channels,
229
+ in_channels // attn_num_head_channels,
230
+ in_channels=in_channels,
231
+ num_layers=1,
232
+ cross_attention_dim=cross_attention_dim,
233
+ norm_num_groups=resnet_groups,
234
+ use_linear_projection=use_linear_projection,
235
+ upcast_attention=upcast_attention,
236
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
237
+ unet_use_temporal_attention=unet_use_temporal_attention,
238
+ )
239
+ )
240
+ motion_modules.append(
241
+ get_motion_module(
242
+ in_channels=in_channels,
243
+ motion_module_type=motion_module_type,
244
+ motion_module_kwargs=motion_module_kwargs,
245
+ )
246
+ if use_motion_module
247
+ else None
248
+ )
249
+ resnets.append(
250
+ ResnetBlock3D(
251
+ in_channels=in_channels,
252
+ out_channels=in_channels,
253
+ temb_channels=temb_channels,
254
+ eps=resnet_eps,
255
+ groups=resnet_groups,
256
+ dropout=dropout,
257
+ time_embedding_norm=resnet_time_scale_shift,
258
+ non_linearity=resnet_act_fn,
259
+ output_scale_factor=output_scale_factor,
260
+ pre_norm=resnet_pre_norm,
261
+ use_inflated_groupnorm=use_inflated_groupnorm,
262
+ )
263
+ )
264
+
265
+ self.attentions = nn.ModuleList(attentions)
266
+ self.resnets = nn.ModuleList(resnets)
267
+ self.motion_modules = nn.ModuleList(motion_modules)
268
+
269
+ def forward(
270
+ self,
271
+ hidden_states,
272
+ temb=None,
273
+ encoder_hidden_states=None,
274
+ attention_mask=None,
275
+ ):
276
+ hidden_states = self.resnets[0](hidden_states, temb)
277
+ for attn, resnet, motion_module in zip(
278
+ self.attentions, self.resnets[1:], self.motion_modules
279
+ ):
280
+ hidden_states = attn(
281
+ hidden_states,
282
+ encoder_hidden_states=encoder_hidden_states,
283
+ ).sample
284
+ hidden_states = (
285
+ motion_module(
286
+ hidden_states, temb, encoder_hidden_states=encoder_hidden_states
287
+ )
288
+ if motion_module is not None
289
+ else hidden_states
290
+ )
291
+ hidden_states = resnet(hidden_states, temb)
292
+
293
+ return hidden_states
294
+
295
+
296
+ class CrossAttnDownBlock3D(nn.Module):
297
+ def __init__(
298
+ self,
299
+ in_channels: int,
300
+ out_channels: int,
301
+ temb_channels: int,
302
+ dropout: float = 0.0,
303
+ num_layers: int = 1,
304
+ resnet_eps: float = 1e-6,
305
+ resnet_time_scale_shift: str = "default",
306
+ resnet_act_fn: str = "swish",
307
+ resnet_groups: int = 32,
308
+ resnet_pre_norm: bool = True,
309
+ attn_num_head_channels=1,
310
+ cross_attention_dim=1280,
311
+ output_scale_factor=1.0,
312
+ downsample_padding=1,
313
+ add_downsample=True,
314
+ dual_cross_attention=False,
315
+ use_linear_projection=False,
316
+ only_cross_attention=False,
317
+ upcast_attention=False,
318
+ unet_use_cross_frame_attention=None,
319
+ unet_use_temporal_attention=None,
320
+ use_inflated_groupnorm=None,
321
+ use_motion_module=None,
322
+ motion_module_type=None,
323
+ motion_module_kwargs=None,
324
+ ):
325
+ super().__init__()
326
+ resnets = []
327
+ attentions = []
328
+ motion_modules = []
329
+
330
+ self.has_cross_attention = True
331
+ self.attn_num_head_channels = attn_num_head_channels
332
+
333
+ for i in range(num_layers):
334
+ in_channels = in_channels if i == 0 else out_channels
335
+ resnets.append(
336
+ ResnetBlock3D(
337
+ in_channels=in_channels,
338
+ out_channels=out_channels,
339
+ temb_channels=temb_channels,
340
+ eps=resnet_eps,
341
+ groups=resnet_groups,
342
+ dropout=dropout,
343
+ time_embedding_norm=resnet_time_scale_shift,
344
+ non_linearity=resnet_act_fn,
345
+ output_scale_factor=output_scale_factor,
346
+ pre_norm=resnet_pre_norm,
347
+ use_inflated_groupnorm=use_inflated_groupnorm,
348
+ )
349
+ )
350
+ if dual_cross_attention:
351
+ raise NotImplementedError
352
+ attentions.append(
353
+ Transformer3DModel(
354
+ attn_num_head_channels,
355
+ out_channels // attn_num_head_channels,
356
+ in_channels=out_channels,
357
+ num_layers=1,
358
+ cross_attention_dim=cross_attention_dim,
359
+ norm_num_groups=resnet_groups,
360
+ use_linear_projection=use_linear_projection,
361
+ only_cross_attention=only_cross_attention,
362
+ upcast_attention=upcast_attention,
363
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
364
+ unet_use_temporal_attention=unet_use_temporal_attention,
365
+ )
366
+ )
367
+ motion_modules.append(
368
+ get_motion_module(
369
+ in_channels=out_channels,
370
+ motion_module_type=motion_module_type,
371
+ motion_module_kwargs=motion_module_kwargs,
372
+ )
373
+ if use_motion_module
374
+ else None
375
+ )
376
+
377
+ self.attentions = nn.ModuleList(attentions)
378
+ self.resnets = nn.ModuleList(resnets)
379
+ self.motion_modules = nn.ModuleList(motion_modules)
380
+
381
+ if add_downsample:
382
+ self.downsamplers = nn.ModuleList(
383
+ [
384
+ Downsample3D(
385
+ out_channels,
386
+ use_conv=True,
387
+ out_channels=out_channels,
388
+ padding=downsample_padding,
389
+ name="op",
390
+ )
391
+ ]
392
+ )
393
+ else:
394
+ self.downsamplers = None
395
+
396
+ self.gradient_checkpointing = False
397
+
398
+ def forward(
399
+ self,
400
+ hidden_states,
401
+ temb=None,
402
+ encoder_hidden_states=None,
403
+ attention_mask=None,
404
+ ):
405
+ output_states = ()
406
+
407
+ for i, (resnet, attn, motion_module) in enumerate(
408
+ zip(self.resnets, self.attentions, self.motion_modules)
409
+ ):
410
+ # self.gradient_checkpointing = False
411
+ if self.training and self.gradient_checkpointing:
412
+
413
+ def create_custom_forward(module, return_dict=None):
414
+ def custom_forward(*inputs):
415
+ if return_dict is not None:
416
+ return module(*inputs, return_dict=return_dict)
417
+ else:
418
+ return module(*inputs)
419
+
420
+ return custom_forward
421
+
422
+ hidden_states = torch.utils.checkpoint.checkpoint(
423
+ create_custom_forward(resnet), hidden_states, temb
424
+ )
425
+ hidden_states = torch.utils.checkpoint.checkpoint(
426
+ create_custom_forward(attn, return_dict=False),
427
+ hidden_states,
428
+ encoder_hidden_states,
429
+ use_reentrant=False,
430
+ )[0]
431
+
432
+ # add motion module
433
+ hidden_states = (
434
+ motion_module(
435
+ hidden_states, temb, encoder_hidden_states=encoder_hidden_states
436
+ )
437
+ if motion_module is not None
438
+ else hidden_states
439
+ )
440
+
441
+ else:
442
+ hidden_states = resnet(hidden_states, temb)
443
+ hidden_states = attn(
444
+ hidden_states,
445
+ encoder_hidden_states=encoder_hidden_states,
446
+ ).sample
447
+
448
+ # add motion module
449
+ hidden_states = (
450
+ motion_module(
451
+ hidden_states, temb, encoder_hidden_states=encoder_hidden_states
452
+ )
453
+ if motion_module is not None
454
+ else hidden_states
455
+ )
456
+
457
+ output_states += (hidden_states,)
458
+
459
+ if self.downsamplers is not None:
460
+ for downsampler in self.downsamplers:
461
+ hidden_states = downsampler(hidden_states)
462
+
463
+ output_states += (hidden_states,)
464
+
465
+ return hidden_states, output_states
466
+
467
+
468
+ class DownBlock3D(nn.Module):
469
+ def __init__(
470
+ self,
471
+ in_channels: int,
472
+ out_channels: int,
473
+ temb_channels: int,
474
+ dropout: float = 0.0,
475
+ num_layers: int = 1,
476
+ resnet_eps: float = 1e-6,
477
+ resnet_time_scale_shift: str = "default",
478
+ resnet_act_fn: str = "swish",
479
+ resnet_groups: int = 32,
480
+ resnet_pre_norm: bool = True,
481
+ output_scale_factor=1.0,
482
+ add_downsample=True,
483
+ downsample_padding=1,
484
+ use_inflated_groupnorm=None,
485
+ use_motion_module=None,
486
+ motion_module_type=None,
487
+ motion_module_kwargs=None,
488
+ ):
489
+ super().__init__()
490
+ resnets = []
491
+ motion_modules = []
492
+
493
+ # use_motion_module = False
494
+ for i in range(num_layers):
495
+ in_channels = in_channels if i == 0 else out_channels
496
+ resnets.append(
497
+ ResnetBlock3D(
498
+ in_channels=in_channels,
499
+ out_channels=out_channels,
500
+ temb_channels=temb_channels,
501
+ eps=resnet_eps,
502
+ groups=resnet_groups,
503
+ dropout=dropout,
504
+ time_embedding_norm=resnet_time_scale_shift,
505
+ non_linearity=resnet_act_fn,
506
+ output_scale_factor=output_scale_factor,
507
+ pre_norm=resnet_pre_norm,
508
+ use_inflated_groupnorm=use_inflated_groupnorm,
509
+ )
510
+ )
511
+ motion_modules.append(
512
+ get_motion_module(
513
+ in_channels=out_channels,
514
+ motion_module_type=motion_module_type,
515
+ motion_module_kwargs=motion_module_kwargs,
516
+ )
517
+ if use_motion_module
518
+ else None
519
+ )
520
+
521
+ self.resnets = nn.ModuleList(resnets)
522
+ self.motion_modules = nn.ModuleList(motion_modules)
523
+
524
+ if add_downsample:
525
+ self.downsamplers = nn.ModuleList(
526
+ [
527
+ Downsample3D(
528
+ out_channels,
529
+ use_conv=True,
530
+ out_channels=out_channels,
531
+ padding=downsample_padding,
532
+ name="op",
533
+ )
534
+ ]
535
+ )
536
+ else:
537
+ self.downsamplers = None
538
+
539
+ self.gradient_checkpointing = False
540
+
541
+ def forward(self, hidden_states, temb=None, encoder_hidden_states=None):
542
+ output_states = ()
543
+
544
+ for resnet, motion_module in zip(self.resnets, self.motion_modules):
545
+ # print(f"DownBlock3D {self.gradient_checkpointing = }")
546
+ if self.training and self.gradient_checkpointing:
547
+
548
+ def create_custom_forward(module):
549
+ def custom_forward(*inputs):
550
+ return module(*inputs)
551
+
552
+ return custom_forward
553
+
554
+ hidden_states = torch.utils.checkpoint.checkpoint(
555
+ create_custom_forward(resnet), hidden_states, temb
556
+ )
557
+ if motion_module is not None:
558
+ hidden_states = torch.utils.checkpoint.checkpoint(
559
+ create_custom_forward(motion_module),
560
+ hidden_states.requires_grad_(),
561
+ temb,
562
+ encoder_hidden_states,
563
+ )
564
+ else:
565
+ hidden_states = resnet(hidden_states, temb)
566
+
567
+ # add motion module
568
+ hidden_states = (
569
+ motion_module(
570
+ hidden_states, temb, encoder_hidden_states=encoder_hidden_states
571
+ )
572
+ if motion_module is not None
573
+ else hidden_states
574
+ )
575
+
576
+ output_states += (hidden_states,)
577
+
578
+ if self.downsamplers is not None:
579
+ for downsampler in self.downsamplers:
580
+ hidden_states = downsampler(hidden_states)
581
+
582
+ output_states += (hidden_states,)
583
+
584
+ return hidden_states, output_states
585
+
586
+
587
+ class CrossAttnUpBlock3D(nn.Module):
588
+ def __init__(
589
+ self,
590
+ in_channels: int,
591
+ out_channels: int,
592
+ prev_output_channel: int,
593
+ temb_channels: int,
594
+ dropout: float = 0.0,
595
+ num_layers: int = 1,
596
+ resnet_eps: float = 1e-6,
597
+ resnet_time_scale_shift: str = "default",
598
+ resnet_act_fn: str = "swish",
599
+ resnet_groups: int = 32,
600
+ resnet_pre_norm: bool = True,
601
+ attn_num_head_channels=1,
602
+ cross_attention_dim=1280,
603
+ output_scale_factor=1.0,
604
+ add_upsample=True,
605
+ dual_cross_attention=False,
606
+ use_linear_projection=False,
607
+ only_cross_attention=False,
608
+ upcast_attention=False,
609
+ unet_use_cross_frame_attention=None,
610
+ unet_use_temporal_attention=None,
611
+ use_motion_module=None,
612
+ use_inflated_groupnorm=None,
613
+ motion_module_type=None,
614
+ motion_module_kwargs=None,
615
+ ):
616
+ super().__init__()
617
+ resnets = []
618
+ attentions = []
619
+ motion_modules = []
620
+
621
+ self.has_cross_attention = True
622
+ self.attn_num_head_channels = attn_num_head_channels
623
+
624
+ for i in range(num_layers):
625
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
626
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
627
+
628
+ resnets.append(
629
+ ResnetBlock3D(
630
+ in_channels=resnet_in_channels + res_skip_channels,
631
+ out_channels=out_channels,
632
+ temb_channels=temb_channels,
633
+ eps=resnet_eps,
634
+ groups=resnet_groups,
635
+ dropout=dropout,
636
+ time_embedding_norm=resnet_time_scale_shift,
637
+ non_linearity=resnet_act_fn,
638
+ output_scale_factor=output_scale_factor,
639
+ pre_norm=resnet_pre_norm,
640
+ use_inflated_groupnorm=use_inflated_groupnorm,
641
+ )
642
+ )
643
+ if dual_cross_attention:
644
+ raise NotImplementedError
645
+ attentions.append(
646
+ Transformer3DModel(
647
+ attn_num_head_channels,
648
+ out_channels // attn_num_head_channels,
649
+ in_channels=out_channels,
650
+ num_layers=1,
651
+ cross_attention_dim=cross_attention_dim,
652
+ norm_num_groups=resnet_groups,
653
+ use_linear_projection=use_linear_projection,
654
+ only_cross_attention=only_cross_attention,
655
+ upcast_attention=upcast_attention,
656
+ unet_use_cross_frame_attention=unet_use_cross_frame_attention,
657
+ unet_use_temporal_attention=unet_use_temporal_attention,
658
+ )
659
+ )
660
+ motion_modules.append(
661
+ get_motion_module(
662
+ in_channels=out_channels,
663
+ motion_module_type=motion_module_type,
664
+ motion_module_kwargs=motion_module_kwargs,
665
+ )
666
+ if use_motion_module
667
+ else None
668
+ )
669
+
670
+ self.attentions = nn.ModuleList(attentions)
671
+ self.resnets = nn.ModuleList(resnets)
672
+ self.motion_modules = nn.ModuleList(motion_modules)
673
+
674
+ if add_upsample:
675
+ self.upsamplers = nn.ModuleList(
676
+ [Upsample3D(out_channels, use_conv=True, out_channels=out_channels)]
677
+ )
678
+ else:
679
+ self.upsamplers = None
680
+
681
+ self.gradient_checkpointing = False
682
+
683
+ def forward(
684
+ self,
685
+ hidden_states,
686
+ res_hidden_states_tuple,
687
+ temb=None,
688
+ encoder_hidden_states=None,
689
+ upsample_size=None,
690
+ attention_mask=None,
691
+ ):
692
+ for i, (resnet, attn, motion_module) in enumerate(
693
+ zip(self.resnets, self.attentions, self.motion_modules)
694
+ ):
695
+ # pop res hidden states
696
+ res_hidden_states = res_hidden_states_tuple[-1]
697
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
698
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
699
+
700
+ if self.training and self.gradient_checkpointing:
701
+
702
+ def create_custom_forward(module, return_dict=None):
703
+ def custom_forward(*inputs):
704
+ if return_dict is not None:
705
+ return module(*inputs, return_dict=return_dict)
706
+ else:
707
+ return module(*inputs)
708
+
709
+ return custom_forward
710
+
711
+ hidden_states = torch.utils.checkpoint.checkpoint(
712
+ create_custom_forward(resnet), hidden_states, temb
713
+ )
714
+ hidden_states = attn(
715
+ hidden_states,
716
+ encoder_hidden_states=encoder_hidden_states,
717
+ ).sample
718
+ if motion_module is not None:
719
+ hidden_states = torch.utils.checkpoint.checkpoint(
720
+ create_custom_forward(motion_module),
721
+ hidden_states.requires_grad_(),
722
+ temb,
723
+ encoder_hidden_states,
724
+ )
725
+
726
+ else:
727
+ hidden_states = resnet(hidden_states, temb)
728
+ hidden_states = attn(
729
+ hidden_states,
730
+ encoder_hidden_states=encoder_hidden_states,
731
+ ).sample
732
+
733
+ # add motion module
734
+ hidden_states = (
735
+ motion_module(
736
+ hidden_states, temb, encoder_hidden_states=encoder_hidden_states
737
+ )
738
+ if motion_module is not None
739
+ else hidden_states
740
+ )
741
+
742
+ if self.upsamplers is not None:
743
+ for upsampler in self.upsamplers:
744
+ hidden_states = upsampler(hidden_states, upsample_size)
745
+
746
+ return hidden_states
747
+
748
+
749
+ class UpBlock3D(nn.Module):
750
+ def __init__(
751
+ self,
752
+ in_channels: int,
753
+ prev_output_channel: int,
754
+ out_channels: int,
755
+ temb_channels: int,
756
+ dropout: float = 0.0,
757
+ num_layers: int = 1,
758
+ resnet_eps: float = 1e-6,
759
+ resnet_time_scale_shift: str = "default",
760
+ resnet_act_fn: str = "swish",
761
+ resnet_groups: int = 32,
762
+ resnet_pre_norm: bool = True,
763
+ output_scale_factor=1.0,
764
+ add_upsample=True,
765
+ use_inflated_groupnorm=None,
766
+ use_motion_module=None,
767
+ motion_module_type=None,
768
+ motion_module_kwargs=None,
769
+ ):
770
+ super().__init__()
771
+ resnets = []
772
+ motion_modules = []
773
+
774
+ # use_motion_module = False
775
+ for i in range(num_layers):
776
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
777
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
778
+
779
+ resnets.append(
780
+ ResnetBlock3D(
781
+ in_channels=resnet_in_channels + res_skip_channels,
782
+ out_channels=out_channels,
783
+ temb_channels=temb_channels,
784
+ eps=resnet_eps,
785
+ groups=resnet_groups,
786
+ dropout=dropout,
787
+ time_embedding_norm=resnet_time_scale_shift,
788
+ non_linearity=resnet_act_fn,
789
+ output_scale_factor=output_scale_factor,
790
+ pre_norm=resnet_pre_norm,
791
+ use_inflated_groupnorm=use_inflated_groupnorm,
792
+ )
793
+ )
794
+ motion_modules.append(
795
+ get_motion_module(
796
+ in_channels=out_channels,
797
+ motion_module_type=motion_module_type,
798
+ motion_module_kwargs=motion_module_kwargs,
799
+ )
800
+ if use_motion_module
801
+ else None
802
+ )
803
+
804
+ self.resnets = nn.ModuleList(resnets)
805
+ self.motion_modules = nn.ModuleList(motion_modules)
806
+
807
+ if add_upsample:
808
+ self.upsamplers = nn.ModuleList(
809
+ [Upsample3D(out_channels, use_conv=True, out_channels=out_channels)]
810
+ )
811
+ else:
812
+ self.upsamplers = None
813
+
814
+ self.gradient_checkpointing = False
815
+
816
+ def forward(
817
+ self,
818
+ hidden_states,
819
+ res_hidden_states_tuple,
820
+ temb=None,
821
+ upsample_size=None,
822
+ encoder_hidden_states=None,
823
+ ):
824
+ for resnet, motion_module in zip(self.resnets, self.motion_modules):
825
+ # pop res hidden states
826
+ res_hidden_states = res_hidden_states_tuple[-1]
827
+ res_hidden_states_tuple = res_hidden_states_tuple[:-1]
828
+ hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)
829
+
830
+ # print(f"UpBlock3D {self.gradient_checkpointing = }")
831
+ if self.training and self.gradient_checkpointing:
832
+
833
+ def create_custom_forward(module):
834
+ def custom_forward(*inputs):
835
+ return module(*inputs)
836
+
837
+ return custom_forward
838
+
839
+ hidden_states = torch.utils.checkpoint.checkpoint(
840
+ create_custom_forward(resnet), hidden_states, temb
841
+ )
842
+ if motion_module is not None:
843
+ hidden_states = torch.utils.checkpoint.checkpoint(
844
+ create_custom_forward(motion_module),
845
+ hidden_states.requires_grad_(),
846
+ temb,
847
+ encoder_hidden_states,
848
+ )
849
+ else:
850
+ hidden_states = resnet(hidden_states, temb)
851
+ hidden_states = (
852
+ motion_module(
853
+ hidden_states, temb, encoder_hidden_states=encoder_hidden_states
854
+ )
855
+ if motion_module is not None
856
+ else hidden_states
857
+ )
858
+
859
+ if self.upsamplers is not None:
860
+ for upsampler in self.upsamplers:
861
+ hidden_states = upsampler(hidden_states, upsample_size)
862
+
863
+ return hidden_states
2610_variant_runtime/diffusion/pipelines/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
2610_variant_runtime/diffusion/pipelines/pipeline_vfi2video_share_vae.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from dataclasses import dataclass
3
+ from typing import Callable, List, Optional, Union
4
+
5
+ import numpy as np
6
+ import torch
7
+ from diffusers import DiffusionPipeline
8
+ from diffusers.image_processor import VaeImageProcessor
9
+ from diffusers.schedulers import (
10
+ DDIMScheduler,
11
+ DPMSolverMultistepScheduler,
12
+ EulerAncestralDiscreteScheduler,
13
+ EulerDiscreteScheduler,
14
+ LMSDiscreteScheduler,
15
+ PNDMScheduler,
16
+ )
17
+ from diffusers.utils import BaseOutput, is_accelerate_available
18
+ from diffusers.utils.torch_utils import randn_tensor
19
+ from einops import rearrange
20
+ from tqdm import tqdm
21
+ from transformers import CLIPImageProcessor
22
+ from einops import rearrange
23
+
24
+ from models.mutual_self_attention import ReferenceAttentionControl
25
+
26
+
27
+ @dataclass
28
+ class Pose2VideoPipelineOutput(BaseOutput):
29
+ videos: Union[torch.Tensor, np.ndarray]
30
+
31
+ class Pose2VideoPipeline(DiffusionPipeline):
32
+ _optional_components = []
33
+
34
+ def __init__(
35
+ self,
36
+ vae,
37
+ image_encoder,
38
+ reference_unet,
39
+ denoising_unet,
40
+ pose_guider,
41
+ seed_guider,
42
+ scheduler: Union[
43
+ DDIMScheduler,
44
+ PNDMScheduler,
45
+ LMSDiscreteScheduler,
46
+ EulerDiscreteScheduler,
47
+ EulerAncestralDiscreteScheduler,
48
+ DPMSolverMultistepScheduler,
49
+ ],
50
+ image_proj_model=None,
51
+ tokenizer=None,
52
+ text_encoder=None,
53
+ ):
54
+ super().__init__()
55
+
56
+ self.register_modules(
57
+ vae=vae,
58
+ image_encoder=image_encoder,
59
+ reference_unet=reference_unet,
60
+ denoising_unet=denoising_unet,
61
+ pose_guider=pose_guider,
62
+ scheduler=scheduler,
63
+ seed_guider=seed_guider,
64
+ )
65
+ self.vae_scale_factor = 2 ** (len(self.vae.config.block_out_channels) - 1)
66
+ self.clip_image_processor = CLIPImageProcessor()
67
+ self.ref_image_processor = VaeImageProcessor(
68
+ vae_scale_factor=self.vae_scale_factor, do_convert_rgb=True
69
+ )
70
+ self.cond_image_processor = VaeImageProcessor(
71
+ vae_scale_factor=self.vae_scale_factor,
72
+ do_convert_rgb=True,
73
+ do_normalize=False,
74
+ )
75
+
76
+
77
+ def enable_vae_slicing(self):
78
+ self.vae.enable_slicing()
79
+
80
+ def disable_vae_slicing(self):
81
+ self.vae.disable_slicing()
82
+
83
+ def enable_sequential_cpu_offload(self, gpu_id=0):
84
+ if is_accelerate_available():
85
+ from accelerate import cpu_offload
86
+ else:
87
+ raise ImportError("Please install accelerate via `pip install accelerate`")
88
+
89
+ device = torch.device(f"cuda:{gpu_id}")
90
+
91
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
92
+ if cpu_offloaded_model is not None:
93
+ cpu_offload(cpu_offloaded_model, device)
94
+
95
+ @property
96
+ def _execution_device(self):
97
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
98
+ return self.device
99
+ for module in self.unet.modules():
100
+ if (
101
+ hasattr(module, "_hf_hook")
102
+ and hasattr(module._hf_hook, "execution_device")
103
+ and module._hf_hook.execution_device is not None
104
+ ):
105
+ return torch.device(module._hf_hook.execution_device)
106
+ return self.device
107
+
108
+ def decode_latents(self, latents):
109
+ video_length = latents.shape[2]
110
+ latents = 1 / 0.18215 * latents
111
+ latents = rearrange(latents, "b c f h w -> (b f) c h w")
112
+ video = []
113
+ for frame_idx in tqdm(range(latents.shape[0])):
114
+ video.append(self.vae.decode(latents[frame_idx : frame_idx + 1]).sample)
115
+ video = torch.cat(video)
116
+ video = rearrange(video, "(b f) c h w -> b c f h w", f=video_length)
117
+ video = (video / 2 + 0.5).clamp(0, 1)
118
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
119
+ video = video.cpu().float().numpy()
120
+ return video
121
+
122
+ def prepare_extra_step_kwargs(self, generator, eta):
123
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
124
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
125
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
126
+ # and should be between [0, 1]
127
+
128
+ accepts_eta = "eta" in set(
129
+ inspect.signature(self.scheduler.step).parameters.keys()
130
+ )
131
+ extra_step_kwargs = {}
132
+ if accepts_eta:
133
+ extra_step_kwargs["eta"] = eta
134
+
135
+ # check if the scheduler accepts generator
136
+ accepts_generator = "generator" in set(
137
+ inspect.signature(self.scheduler.step).parameters.keys()
138
+ )
139
+ if accepts_generator:
140
+ extra_step_kwargs["generator"] = generator
141
+ return extra_step_kwargs
142
+
143
+ def prepare_latents(
144
+ self,
145
+ batch_size,
146
+ num_channels_latents,
147
+ width,
148
+ height,
149
+ video_length,
150
+ dtype,
151
+ device,
152
+ generator,
153
+ latents=None,
154
+ ):
155
+ shape = (
156
+ batch_size,
157
+ num_channels_latents,
158
+ video_length,
159
+ height // self.vae_scale_factor,
160
+ width // self.vae_scale_factor,
161
+ )
162
+ if isinstance(generator, list) and len(generator) != batch_size:
163
+ raise ValueError(
164
+ f"You have passed a list of generators of length {len(generator)}, but requested an effective batch"
165
+ f" size of {batch_size}. Make sure the batch size matches the length of the generators."
166
+ )
167
+
168
+ if latents is None:
169
+ latents = randn_tensor(
170
+ shape, generator=generator, device=device, dtype=dtype
171
+ )
172
+ else:
173
+ latents = latents.to(device)
174
+
175
+ # scale the initial noise by the standard deviation required by the scheduler
176
+ latents = latents * self.scheduler.init_noise_sigma
177
+ return latents
178
+
179
+ def _encode_prompt(
180
+ self,
181
+ prompt,
182
+ device,
183
+ num_videos_per_prompt,
184
+ do_classifier_free_guidance,
185
+ negative_prompt,
186
+ ):
187
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
188
+
189
+ text_inputs = self.tokenizer(
190
+ prompt,
191
+ padding="max_length",
192
+ max_length=self.tokenizer.model_max_length,
193
+ truncation=True,
194
+ return_tensors="pt",
195
+ )
196
+ text_input_ids = text_inputs.input_ids
197
+ untruncated_ids = self.tokenizer(
198
+ prompt, padding="longest", return_tensors="pt"
199
+ ).input_ids
200
+
201
+ if untruncated_ids.shape[-1] >= text_input_ids.shape[-1] and not torch.equal(
202
+ text_input_ids, untruncated_ids
203
+ ):
204
+ removed_text = self.tokenizer.batch_decode(
205
+ untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1]
206
+ )
207
+
208
+ if (
209
+ hasattr(self.text_encoder.config, "use_attention_mask")
210
+ and self.text_encoder.config.use_attention_mask
211
+ ):
212
+ attention_mask = text_inputs.attention_mask.to(device)
213
+ else:
214
+ attention_mask = None
215
+
216
+ text_embeddings = self.text_encoder(
217
+ text_input_ids.to(device),
218
+ attention_mask=attention_mask,
219
+ )
220
+ text_embeddings = text_embeddings[0]
221
+
222
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
223
+ bs_embed, seq_len, _ = text_embeddings.shape
224
+ text_embeddings = text_embeddings.repeat(1, num_videos_per_prompt, 1)
225
+ text_embeddings = text_embeddings.view(
226
+ bs_embed * num_videos_per_prompt, seq_len, -1
227
+ )
228
+
229
+ # get unconditional embeddings for classifier free guidance
230
+ if do_classifier_free_guidance:
231
+ uncond_tokens: List[str]
232
+ if negative_prompt is None:
233
+ uncond_tokens = [""] * batch_size
234
+ elif type(prompt) is not type(negative_prompt):
235
+ raise TypeError(
236
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
237
+ f" {type(prompt)}."
238
+ )
239
+ elif isinstance(negative_prompt, str):
240
+ uncond_tokens = [negative_prompt]
241
+ elif batch_size != len(negative_prompt):
242
+ raise ValueError(
243
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
244
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
245
+ " the batch size of `prompt`."
246
+ )
247
+ else:
248
+ uncond_tokens = negative_prompt
249
+
250
+ max_length = text_input_ids.shape[-1]
251
+ uncond_input = self.tokenizer(
252
+ uncond_tokens,
253
+ padding="max_length",
254
+ max_length=max_length,
255
+ truncation=True,
256
+ return_tensors="pt",
257
+ )
258
+
259
+ if (
260
+ hasattr(self.text_encoder.config, "use_attention_mask")
261
+ and self.text_encoder.config.use_attention_mask
262
+ ):
263
+ attention_mask = uncond_input.attention_mask.to(device)
264
+ else:
265
+ attention_mask = None
266
+
267
+ uncond_embeddings = self.text_encoder(
268
+ uncond_input.input_ids.to(device),
269
+ attention_mask=attention_mask,
270
+ )
271
+ uncond_embeddings = uncond_embeddings[0]
272
+
273
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
274
+ seq_len = uncond_embeddings.shape[1]
275
+ uncond_embeddings = uncond_embeddings.repeat(1, num_videos_per_prompt, 1)
276
+ uncond_embeddings = uncond_embeddings.view(
277
+ batch_size * num_videos_per_prompt, seq_len, -1
278
+ )
279
+
280
+ # For classifier free guidance, we need to do two forward passes.
281
+ # Here we concatenate the unconditional and text embeddings into a single batch
282
+ # to avoid doing two forward passes
283
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
284
+
285
+ return text_embeddings
286
+
287
+ @torch.no_grad()
288
+ def __call__(
289
+ self,
290
+ ref_image,
291
+ pose_images,
292
+ seed_images,
293
+ width,
294
+ height,
295
+ video_length,
296
+ num_inference_steps,
297
+ guidance_scale,
298
+ num_images_per_prompt=1,
299
+ eta: float = 0.0,
300
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
301
+ output_type: Optional[str] = "tensor",
302
+ return_dict: bool = True,
303
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
304
+ callback_steps: Optional[int] = 1,
305
+ seed_mask=None,
306
+ **kwargs,
307
+ ):
308
+ # Default height and width to unet
309
+ height = height or self.unet.config.sample_size * self.vae_scale_factor
310
+ width = width or self.unet.config.sample_size * self.vae_scale_factor
311
+
312
+ device = self._execution_device
313
+
314
+ do_classifier_free_guidance = guidance_scale > 1.0
315
+
316
+ # Prepare timesteps
317
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
318
+ timesteps = self.scheduler.timesteps
319
+
320
+ batch_size = 1
321
+
322
+ # Prepare clip image embeds
323
+ clip_image = self.clip_image_processor.preprocess(
324
+ ref_image.resize((224, 224)), return_tensors="pt"
325
+ ).pixel_values
326
+ clip_image_embeds = self.image_encoder(
327
+ clip_image.to(device, dtype=self.image_encoder.dtype)
328
+ ).image_embeds
329
+ encoder_hidden_states = clip_image_embeds.unsqueeze(1)
330
+ uncond_encoder_hidden_states = torch.zeros_like(encoder_hidden_states)
331
+
332
+ if do_classifier_free_guidance:
333
+ encoder_hidden_states = torch.cat(
334
+ [uncond_encoder_hidden_states, encoder_hidden_states], dim=0
335
+ )
336
+ reference_control_writer = ReferenceAttentionControl(
337
+ self.reference_unet,
338
+ do_classifier_free_guidance=do_classifier_free_guidance,
339
+ mode="write",
340
+ batch_size=batch_size,
341
+ fusion_blocks="full",
342
+ )
343
+ reference_control_reader = ReferenceAttentionControl(
344
+ self.denoising_unet,
345
+ do_classifier_free_guidance=do_classifier_free_guidance,
346
+ mode="read",
347
+ batch_size=batch_size,
348
+ fusion_blocks="full",
349
+ )
350
+
351
+ num_channels_latents = self.denoising_unet.in_channels
352
+ latents = self.prepare_latents(
353
+ batch_size * num_images_per_prompt,
354
+ num_channels_latents,
355
+ width,
356
+ height,
357
+ video_length,
358
+ clip_image_embeds.dtype,
359
+ device,
360
+ generator,
361
+ )
362
+
363
+ # Prepare extra step kwargs.
364
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
365
+
366
+ # Prepare ref image latents
367
+ ref_image_tensor = self.ref_image_processor.preprocess(
368
+ ref_image, height=height, width=width
369
+ ) # (bs, c, width, height)
370
+ ref_image_tensor = ref_image_tensor.to(
371
+ dtype=self.vae.dtype, device=self.vae.device
372
+ )
373
+ ref_image_latents = self.vae.encode(ref_image_tensor).latent_dist.mean
374
+ ref_image_latents = ref_image_latents * 0.18215 # (b, 4, h, w)
375
+
376
+
377
+ # seed_features
378
+ if seed_images is not None:
379
+ seed_cond_tensor_list = []
380
+ for seed_image in seed_images:
381
+ seed_cond_tensor = self.ref_image_processor.preprocess(
382
+ seed_image, height=height, width=width
383
+ )
384
+ seed_cond_tensor = seed_cond_tensor.unsqueeze(2) # (bs, c, 1, h, w)
385
+ seed_cond_tensor_list.append(seed_cond_tensor)
386
+ seed_cond_tensor = torch.cat(seed_cond_tensor_list, dim=2) # (bs, c, t, h, w)
387
+
388
+ seed_cond_tensor = rearrange(
389
+ seed_cond_tensor, "b c f h w -> (b f) c h w"
390
+ )
391
+ seed_cond_tensor = seed_cond_tensor.to(
392
+ dtype=self.vae.dtype, device=self.vae.device
393
+ )
394
+ seed_image_latents = self.vae.encode(seed_cond_tensor).latent_dist.mean
395
+ seed_image_latents = seed_image_latents * 0.18215 # (b, 4, h, w)
396
+ seed_image_latents = rearrange(
397
+ seed_image_latents, "(b f) c h w -> b c f h w", f=video_length,
398
+ )
399
+ seed_image_latents = seed_image_latents.to(
400
+ device=device, dtype=self.denoising_unet.dtype
401
+ )
402
+ if seed_mask is not None:
403
+ seed_image_latents = torch.cat(
404
+ [seed_image_latents, seed_mask.to(seed_image_latents)], dim=1
405
+ )
406
+ seed_fea = self.seed_guider(seed_image_latents)
407
+ seed_fea = (
408
+ torch.cat([seed_fea] * 2) if do_classifier_free_guidance else seed_fea
409
+ )
410
+ else:
411
+ seed_fea = None
412
+
413
+
414
+ if pose_images is not None:
415
+ pose_cond_tensor_list = []
416
+ for pose_image in pose_images:
417
+ pose_cond_tensor = self.cond_image_processor.preprocess(
418
+ pose_image, height=height, width=width
419
+ )
420
+ pose_cond_tensor = pose_cond_tensor.unsqueeze(2) # (bs, c, 1, h, w)
421
+ pose_cond_tensor_list.append(pose_cond_tensor)
422
+ pose_cond_tensor = torch.cat(pose_cond_tensor_list, dim=2) # (bs, c, t, h, w)
423
+ pose_cond_tensor = pose_cond_tensor.to(
424
+ device=device, dtype=self.pose_guider.dtype
425
+ )
426
+ pose_fea = self.pose_guider(pose_cond_tensor)
427
+ pose_cond_tensor_zero = torch.zeros_like(pose_cond_tensor).to(
428
+ dtype=pose_fea.dtype, device=pose_fea.device
429
+ )
430
+ pose_fea_zero = self.pose_guider(pose_cond_tensor_zero)
431
+ pose_fea = (
432
+ torch.cat([pose_fea_zero, pose_fea]) if do_classifier_free_guidance else pose_fea
433
+ )
434
+ if seed_fea is None:
435
+ pose_fea = pose_fea
436
+ else:
437
+ pose_fea = pose_fea + seed_fea
438
+ else:
439
+ pose_fea = seed_fea
440
+
441
+ # denoising loop
442
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
443
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
444
+ for i, t in enumerate(timesteps):
445
+ # 1. Forward reference image
446
+ if i == 0:
447
+ self.reference_unet(
448
+ ref_image_latents.repeat(
449
+ (2 if do_classifier_free_guidance else 1), 1, 1, 1
450
+ ),
451
+ torch.zeros_like(t),
452
+ # t,
453
+ encoder_hidden_states=encoder_hidden_states,
454
+ return_dict=False,
455
+ )
456
+ reference_control_reader.update(reference_control_writer)
457
+
458
+ # 3.1 expand the latents if we are doing classifier free guidance
459
+ latent_model_input = (
460
+ torch.cat([latents] * 2) if do_classifier_free_guidance else latents
461
+ )
462
+ latent_model_input = self.scheduler.scale_model_input(
463
+ latent_model_input, t
464
+ )
465
+
466
+ # print(pose_fea.shape, latent_model_input.shape)
467
+ noise_pred = self.denoising_unet(
468
+ latent_model_input,
469
+ t,
470
+ encoder_hidden_states=encoder_hidden_states,
471
+ guidance_fea=pose_fea,
472
+ return_dict=False,
473
+ )[0]
474
+
475
+ # perform guidance
476
+ if do_classifier_free_guidance:
477
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
478
+ noise_pred = noise_pred_uncond + guidance_scale * (
479
+ noise_pred_text - noise_pred_uncond
480
+ )
481
+
482
+ # compute the previous noisy sample x_t -> x_t-1
483
+ latents = self.scheduler.step(
484
+ noise_pred, t, latents, **extra_step_kwargs, return_dict=False
485
+ )[0]
486
+
487
+ # call the callback, if provided
488
+ if i == len(timesteps) - 1 or (
489
+ (i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0
490
+ ):
491
+ progress_bar.update()
492
+ if callback is not None and i % callback_steps == 0:
493
+ step_idx = i // getattr(self.scheduler, "order", 1)
494
+ callback(step_idx, t, latents)
495
+
496
+ reference_control_reader.clear()
497
+ reference_control_writer.clear()
498
+
499
+ # Post-processing
500
+ images = self.decode_latents(latents) # (b, c, f, h, w)
501
+
502
+ # Convert to tensor
503
+ if output_type == "tensor":
504
+ images = torch.from_numpy(images)
505
+
506
+ if not return_dict:
507
+ return images
508
+
509
+ return Pose2VideoPipelineOutput(videos=images)
2610_variant_runtime/diffusion/utils/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+
2610_variant_runtime/diffusion/utils/util.py ADDED
@@ -0,0 +1,168 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import os
3
+ import os.path as osp
4
+ import shutil
5
+ import sys
6
+ from pathlib import Path
7
+ import time
8
+ import av
9
+ import numpy as np
10
+ import torch
11
+ import torchvision
12
+ from einops import rearrange
13
+ from PIL import Image
14
+ import cv2
15
+
16
+ def ensure_file_written(file_path, retries=10, delay=0.1):
17
+ for i in range(retries):
18
+ if os.path.exists(file_path):
19
+ image = Image.open(file_path)
20
+ if image is not None:
21
+ return True
22
+ else:
23
+ print(i)
24
+ time.sleep(delay)
25
+ return False
26
+
27
+ def compute_snr(noise_scheduler, timesteps):
28
+ """
29
+ Computes SNR as per
30
+ https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
31
+ """
32
+ alphas_cumprod = noise_scheduler.alphas_cumprod
33
+ sqrt_alphas_cumprod = alphas_cumprod**0.5
34
+ sqrt_one_minus_alphas_cumprod = (1.0 - alphas_cumprod) ** 0.5
35
+
36
+ # Expand the tensors.
37
+ # Adapted from https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L1026
38
+ sqrt_alphas_cumprod = sqrt_alphas_cumprod.to(device=timesteps.device)[
39
+ timesteps
40
+ ].float()
41
+ while len(sqrt_alphas_cumprod.shape) < len(timesteps.shape):
42
+ sqrt_alphas_cumprod = sqrt_alphas_cumprod[..., None]
43
+ alpha = sqrt_alphas_cumprod.expand(timesteps.shape)
44
+
45
+ sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod.to(
46
+ device=timesteps.device
47
+ )[timesteps].float()
48
+ while len(sqrt_one_minus_alphas_cumprod.shape) < len(timesteps.shape):
49
+ sqrt_one_minus_alphas_cumprod = sqrt_one_minus_alphas_cumprod[..., None]
50
+ sigma = sqrt_one_minus_alphas_cumprod.expand(timesteps.shape)
51
+
52
+ # Compute SNR.
53
+ snr = (alpha / sigma) ** 2
54
+ return snr
55
+
56
+ def seed_everything(seed):
57
+ import random
58
+
59
+ import numpy as np
60
+
61
+ torch.manual_seed(seed)
62
+ torch.cuda.manual_seed_all(seed)
63
+ np.random.seed(seed % (2**32))
64
+ random.seed(seed)
65
+
66
+
67
+ def import_filename(filename):
68
+ spec = importlib.util.spec_from_file_location("mymodule", filename)
69
+ module = importlib.util.module_from_spec(spec)
70
+ sys.modules[spec.name] = module
71
+ spec.loader.exec_module(module)
72
+ return module
73
+
74
+
75
+ def delete_additional_ckpt(base_path, num_keep):
76
+ dirs = []
77
+ for d in os.listdir(base_path):
78
+ if d.startswith("checkpoint-"):
79
+ dirs.append(d)
80
+ num_tot = len(dirs)
81
+ if num_tot <= num_keep:
82
+ return
83
+ # ensure ckpt is sorted and delete the ealier!
84
+ del_dirs = sorted(dirs, key=lambda x: int(x.split("-")[-1]))[: num_tot - num_keep]
85
+ for d in del_dirs:
86
+ path_to_dir = osp.join(base_path, d)
87
+ if osp.exists(path_to_dir):
88
+ shutil.rmtree(path_to_dir)
89
+
90
+
91
+ def save_videos_from_pil(pil_images, path, fps=8):
92
+ import av
93
+
94
+ save_fmt = Path(path).suffix
95
+ os.makedirs(os.path.dirname(path), exist_ok=True)
96
+ width, height = pil_images[0].size
97
+
98
+ if save_fmt == ".mp4":
99
+ codec = "libx264"
100
+ container = av.open(path, "w")
101
+ stream = container.add_stream(codec, rate=fps)
102
+
103
+ stream.width = width
104
+ stream.height = height
105
+
106
+ for pil_image in pil_images:
107
+ # pil_image = Image.fromarray(image_arr).convert("RGB")
108
+ av_frame = av.VideoFrame.from_image(pil_image)
109
+ container.mux(stream.encode(av_frame))
110
+ container.mux(stream.encode())
111
+ container.close()
112
+
113
+ elif save_fmt == ".gif":
114
+ pil_images[0].save(
115
+ fp=path,
116
+ format="GIF",
117
+ append_images=pil_images[1:],
118
+ save_all=True,
119
+ duration=(1 / fps * 1000),
120
+ loop=0,
121
+ )
122
+ else:
123
+ raise ValueError("Unsupported file type. Use .mp4 or .gif.")
124
+
125
+
126
+ def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=8):
127
+ videos = rearrange(videos, "b c t h w -> t b c h w")
128
+ height, width = videos.shape[-2:]
129
+ outputs = []
130
+
131
+ for x in videos:
132
+ x = torchvision.utils.make_grid(x, nrow=n_rows) # (c h w)
133
+ x = x.transpose(0, 1).transpose(1, 2).squeeze(-1) # (h w c)
134
+ if rescale:
135
+ x = (x + 1.0) / 2.0 # -1,1 -> 0,1
136
+ x = (x * 255).numpy().astype(np.uint8)
137
+ x = Image.fromarray(x)
138
+
139
+ outputs.append(x)
140
+
141
+ os.makedirs(os.path.dirname(path), exist_ok=True)
142
+
143
+ save_videos_from_pil(outputs, path, fps)
144
+
145
+
146
+ def read_frames(video_path):
147
+ container = av.open(video_path)
148
+
149
+ video_stream = next(s for s in container.streams if s.type == "video")
150
+ frames = []
151
+ for packet in container.demux(video_stream):
152
+ for frame in packet.decode():
153
+ image = Image.frombytes(
154
+ "RGB",
155
+ (frame.width, frame.height),
156
+ frame.to_rgb().to_ndarray(),
157
+ )
158
+ frames.append(image)
159
+
160
+ return frames
161
+
162
+
163
+ def get_fps(video_path):
164
+ container = av.open(video_path)
165
+ video_stream = next(s for s in container.streams if s.type == "video")
166
+ fps = video_stream.average_rate
167
+ container.close()
168
+ return fps
2610_variant_runtime/diffusion/utils/video_utils.py ADDED
@@ -0,0 +1,89 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import numpy as np
3
+ import torch
4
+ import torchvision
5
+ import torch.nn.functional as F
6
+ from PIL import Image
7
+ from pathlib import Path
8
+ import imageio
9
+ from einops import rearrange
10
+ import torchvision.transforms as transforms
11
+
12
+ def concat_pil(img_pil_lst):
13
+ # horizontally concat PIL images
14
+ # NOTE(ZSH): assume all images are of same size
15
+ W, H = img_pil_lst[0].size
16
+ num_img = len(img_pil_lst)
17
+ new_width = num_img * W
18
+ new_image = Image.new("RGB", (new_width, H), color=0)
19
+ for img_idx, img in enumerate(img_pil_lst):
20
+ new_image.paste(img, (W * img_idx, 0))
21
+
22
+ return new_image
23
+
24
+ def save_videos_from_pil(pil_images, path, fps=24, crf=23):
25
+
26
+ save_fmt = Path(path).suffix
27
+ os.makedirs(os.path.dirname(path), exist_ok=True)
28
+
29
+ if save_fmt == ".mp4":
30
+ with imageio.get_writer(path, fps=fps) as writer:
31
+ for img in pil_images:
32
+ img_array = np.array(img) # Convert PIL Image to numpy array
33
+ writer.append_data(img_array)
34
+
35
+ elif save_fmt == ".gif":
36
+ pil_images[0].save(
37
+ fp=path,
38
+ format="GIF",
39
+ append_images=pil_images[1:],
40
+ save_all=True,
41
+ duration=(1 / fps * 1000),
42
+ loop=0,
43
+ )
44
+ else:
45
+ raise ValueError("Unsupported file type. Use .mp4 or .gif.")
46
+
47
+
48
+ def save_videos_grid(videos: torch.Tensor, path: str, rescale=False, n_rows=6, fps=24):
49
+ videos = rearrange(videos, "b c t h w -> t b c h w")
50
+ height, width = videos.shape[-2:]
51
+ outputs = []
52
+
53
+ for x in videos:
54
+ x = torchvision.utils.make_grid(x, nrow=n_rows) # (c h w)
55
+ x = x.transpose(0, 1).transpose(1, 2).squeeze(-1) # (h w c)
56
+ if rescale:
57
+ x = (x + 1.0) / 2.0 # -1,1 -> 0,1
58
+ x = (x * 255).numpy().astype(np.uint8)
59
+ x = Image.fromarray(x)
60
+
61
+ outputs.append(x)
62
+
63
+ os.makedirs(os.path.dirname(path), exist_ok=True)
64
+
65
+ save_videos_from_pil(outputs, path, fps)
66
+
67
+
68
+ def resize_tensor_frames(video_tensor, new_size):
69
+ B, C, video_length, H, W = video_tensor.shape
70
+ # Reshape video tensor to combine batch and frame dimensions: (B*F, C, H, W)
71
+ video_tensor_reshaped = video_tensor.reshape(-1, C, H, W)
72
+ # Resize using interpolate
73
+ resized_frames = F.interpolate(
74
+ video_tensor_reshaped, size=new_size, mode="bilinear", align_corners=False
75
+ )
76
+ resized_video = resized_frames.reshape(B, C, video_length, new_size[0], new_size[1])
77
+
78
+ return resized_video
79
+
80
+
81
+ def pil_list_to_tensor(image_list, size=None):
82
+ to_tensor = transforms.ToTensor()
83
+ if size is not None:
84
+ tensor_list = [to_tensor(img.resize(size[::-1])) for img in image_list]
85
+ else:
86
+ tensor_list = [to_tensor(img) for img in image_list]
87
+ stacked_tensor = torch.stack(tensor_list, dim=0)
88
+ tensor = stacked_tensor.permute(1, 0, 2, 3)
89
+ return tensor
2610_variant_runtime/licenses/AnimateDiff.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
2610_variant_runtime/licenses/DWPose.txt ADDED
@@ -0,0 +1,219 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2023 IDEA. All Rights Reserved.
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
202
+
203
+
204
+
205
+ MMPose (https://github.com/open-mmlab/mmpose)
206
+
207
+ Copyright 2018-2020 Open-MMLab.
208
+
209
+ Licensed under the Apache License, Version 2.0 (the "License");
210
+ you may not use this file except in compliance with the License.
211
+ You may obtain a copy of the License at
212
+
213
+ http://www.apache.org/licenses/LICENSE-2.0
214
+
215
+ Unless required by applicable law or agreed to in writing, software
216
+ distributed under the License is distributed on an "AS IS" BASIS,
217
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
218
+ See the License for the specific language governing permissions and
219
+ limitations under the License.
2610_variant_runtime/licenses/OpenRAIL-M.txt ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Copyright (c) 2022 Robin Rombach and Patrick Esser and contributors
2
+
3
+ CreativeML Open RAIL-M
4
+ dated August 22, 2022
5
+
6
+ Section I: PREAMBLE
7
+
8
+ Multimodal generative models are being widely adopted and used, and have the potential to transform the way artists, among other individuals, conceive and benefit from AI or ML technologies as a tool for content creation.
9
+
10
+ Notwithstanding the current and potential benefits that these artifacts can bring to society at large, there are also concerns about potential misuses of them, either due to their technical limitations or ethical considerations.
11
+
12
+ In short, this license strives for both the open and responsible downstream use of the accompanying model. When it comes to the open character, we took inspiration from open source permissive licenses regarding the grant of IP rights. Referring to the downstream responsible use, we added use-based restrictions not permitting the use of the Model in very specific scenarios, in order for the licensor to be able to enforce the license in case potential misuses of the Model may occur. At the same time, we strive to promote open and responsible research on generative models for art and content generation.
13
+
14
+ Even though downstream derivative versions of the model could be released under different licensing terms, the latter will always have to include - at minimum - the same use-based restrictions as the ones in the original license (this license). We believe in the intersection between open and responsible AI development; thus, this License aims to strike a balance between both in order to enable responsible open-science in the field of AI.
15
+
16
+ This License governs the use of the model (and its derivatives) and is informed by the model card associated with the model.
17
+
18
+ NOW THEREFORE, You and Licensor agree as follows:
19
+
20
+ 1. Definitions
21
+
22
+ - "License" means the terms and conditions for use, reproduction, and Distribution as defined in this document.
23
+ - "Data" means a collection of information and/or content extracted from the dataset used with the Model, including to train, pretrain, or otherwise evaluate the Model. The Data is not licensed under this License.
24
+ - "Output" means the results of operating a Model as embodied in informational content resulting therefrom.
25
+ - "Model" means any accompanying machine-learning based assemblies (including checkpoints), consisting of learnt weights, parameters (including optimizer states), corresponding to the model architecture as embodied in the Complementary Material, that have been trained or tuned, in whole or in part on the Data, using the Complementary Material.
26
+ - "Derivatives of the Model" means all modifications to the Model, works based on the Model, or any other model which is created or initialized by transfer of patterns of the weights, parameters, activations or output of the Model, to the other model, in order to cause the other model to perform similarly to the Model, including - but not limited to - distillation methods entailing the use of intermediate data representations or methods based on the generation of synthetic data by the Model for training the other model.
27
+ - "Complementary Material" means the accompanying source code and scripts used to define, run, load, benchmark or evaluate the Model, and used to prepare data for training or evaluation, if any. This includes any accompanying documentation, tutorials, examples, etc, if any.
28
+ - "Distribution" means any transmission, reproduction, publication or other sharing of the Model or Derivatives of the Model to a third party, including providing the Model as a hosted service made available by electronic or other remote means - e.g. API-based or web access.
29
+ - "Licensor" means the copyright owner or entity authorized by the copyright owner that is granting the License, including the persons or entities that may have rights in the Model and/or distributing the Model.
30
+ - "You" (or "Your") means an individual or Legal Entity exercising permissions granted by this License and/or making use of the Model for whichever purpose and in any field of use, including usage of the Model in an end-use application - e.g. chatbot, translator, image generator.
31
+ - "Third Parties" means individuals or legal entities that are not under common control with Licensor or You.
32
+ - "Contribution" means any work of authorship, including the original version of the Model and any modifications or additions to that Model or Derivatives of the Model thereof, that is intentionally submitted to Licensor for inclusion in the Model by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Model, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
33
+ - "Contributor" means Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Model.
34
+
35
+ Section II: INTELLECTUAL PROPERTY RIGHTS
36
+
37
+ Both copyright and patent grants apply to the Model, Derivatives of the Model and Complementary Material. The Model and Derivatives of the Model are subject to additional terms as described in Section III.
38
+
39
+ 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare, publicly display, publicly perform, sublicense, and distribute the Complementary Material, the Model, and Derivatives of the Model.
40
+ 3. Grant of Patent License. Subject to the terms and conditions of this License and where and as applicable, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this paragraph) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Model and the Complementary Material, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Model to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Model and/or Complementary Material or a Contribution incorporated within the Model and/or Complementary Material constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for the Model and/or Work shall terminate as of the date such litigation is asserted or filed.
41
+
42
+ Section III: CONDITIONS OF USAGE, DISTRIBUTION AND REDISTRIBUTION
43
+
44
+ 4. Distribution and Redistribution. You may host for Third Party remote access purposes (e.g. software-as-a-service), reproduce and distribute copies of the Model or Derivatives of the Model thereof in any medium, with or without modifications, provided that You meet the following conditions:
45
+ Use-based restrictions as referenced in paragraph 5 MUST be included as an enforceable provision by You in any type of legal agreement (e.g. a license) governing the use and/or distribution of the Model or Derivatives of the Model, and You shall give notice to subsequent users You Distribute to, that the Model or Derivatives of the Model are subject to paragraph 5. This provision does not apply to the use of Complementary Material.
46
+ You must give any Third Party recipients of the Model or Derivatives of the Model a copy of this License;
47
+ You must cause any modified files to carry prominent notices stating that You changed the files;
48
+ You must retain all copyright, patent, trademark, and attribution notices excluding those notices that do not pertain to any part of the Model, Derivatives of the Model.
49
+ You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions - respecting paragraph 4.a. - for use, reproduction, or Distribution of Your modifications, or for any such Derivatives of the Model as a whole, provided Your use, reproduction, and Distribution of the Model otherwise complies with the conditions stated in this License.
50
+ 5. Use-based restrictions. The restrictions set forth in Attachment A are considered Use-based restrictions. Therefore You cannot use the Model and the Derivatives of the Model for the specified restricted uses. You may use the Model subject to this License, including only for lawful purposes and in accordance with the License. Use may include creating any content with, finetuning, updating, running, training, evaluating and/or reparametrizing the Model. You shall require all of Your users who use the Model or a Derivative of the Model to comply with the terms of this paragraph (paragraph 5).
51
+ 6. The Output You Generate. Except as set forth herein, Licensor claims no rights in the Output You generate using the Model. You are accountable for the Output you generate and its subsequent uses. No use of the output can contravene any provision as stated in the License.
52
+
53
+ Section IV: OTHER PROVISIONS
54
+
55
+ 7. Updates and Runtime Restrictions. To the maximum extent permitted by law, Licensor reserves the right to restrict (remotely or otherwise) usage of the Model in violation of this License, update the Model through electronic means, or modify the Output of the Model based on updates. You shall undertake reasonable efforts to use the latest version of the Model.
56
+ 8. Trademarks and related. Nothing in this License permits You to make use of Licensors’ trademarks, trade names, logos or to otherwise suggest endorsement or misrepresent the relationship between the parties; and any rights not expressly granted herein are reserved by the Licensors.
57
+ 9. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Model and the Complementary Material (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Model, Derivatives of the Model, and the Complementary Material and assume any risks associated with Your exercise of permissions under this License.
58
+ 10. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Model and the Complementary Material (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
59
+ 11. Accepting Warranty or Additional Liability. While redistributing the Model, Derivatives of the Model and the Complementary Material thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
60
+ 12. If any provision of this License is held to be invalid, illegal or unenforceable, the remaining provisions shall be unaffected thereby and remain valid as if such provision had not been set forth herein.
61
+
62
+ END OF TERMS AND CONDITIONS
63
+
64
+
65
+
66
+
67
+ Attachment A
68
+
69
+ Use Restrictions
70
+
71
+ You agree not to use the Model or Derivatives of the Model:
72
+ - In any way that violates any applicable national, federal, state, local or international law or regulation;
73
+ - For the purpose of exploiting, harming or attempting to exploit or harm minors in any way;
74
+ - To generate or disseminate verifiably false information and/or content with the purpose of harming others;
75
+ - To generate or disseminate personal identifiable information that can be used to harm an individual;
76
+ - To defame, disparage or otherwise harass others;
77
+ - For fully automated decision making that adversely impacts an individual’s legal rights or otherwise creates or modifies a binding, enforceable obligation;
78
+ - For any use intended to or which has the effect of discriminating against or harming individuals or groups based on online or offline social behavior or known or predicted personal or personality characteristics;
79
+ - To exploit any of the vulnerabilities of a specific group of persons based on their age, social, physical or mental characteristics, in order to materially distort the behavior of a person pertaining to that group in a manner that causes or is likely to cause that person or another person physical or psychological harm;
80
+ - For any use intended to or which has the effect of discriminating against individuals or groups based on legally protected characteristics or categories;
81
+ - To provide medical advice and medical results interpretation;
82
+ - To generate or disseminate information for the purpose to be used for administration of justice, law enforcement, immigration or asylum processes, such as predicting an individual will commit fraud/crime commitment (e.g. by text profiling, drawing causal relationships between assertions made in documents, indiscriminate and arbitrarily-targeted use).
2610_variant_runtime/licenses/PixArt-alpha.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2024 Junsong Chen, Jincheng Yu, Enze Xie
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
2610_variant_runtime/licenses/diffusers.txt ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, Any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
2610_variant_runtime/licenses/magic-animate.txt ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright 2023 MagicAnimate Team All rights reserved.
4
+
5
+ Redistribution and use in source and binary forms, with or without
6
+ modification, are permitted provided that the following conditions are met:
7
+
8
+ 1. Redistributions of source code must retain the above copyright notice, this
9
+ list of conditions and the following disclaimer.
10
+
11
+ 2. Redistributions in binary form must reproduce the above copyright notice,
12
+ this list of conditions and the following disclaimer in the documentation
13
+ and/or other materials provided with the distribution.
14
+
15
+ 3. Neither the name of the copyright holder nor the names of its
16
+ contributors may be used to endorse or promote products derived from
17
+ this software without specific prior written permission.
18
+
19
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
20
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
22
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
23
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
25
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
26
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
27
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
2610_variant_runtime/requirements.lock.txt ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ absl-py==2.5.1
2
+ accelerate==0.21.0
3
+ antlr4-python3-runtime==4.9.3
4
+ asttokens==3.0.2
5
+ audioread==3.1.0
6
+ av==12.2.0
7
+ bitsandbytes==0.43.3
8
+ certifi==2026.7.22
9
+ cffi==2.1.1
10
+ charset-normalizer==3.5.2
11
+ click==8.5.0
12
+ cloudpickle==3.1.2
13
+ coloredlogs==15.0.1
14
+ configargparse==1.8.0
15
+ contourpy==1.3.2
16
+ controlnet-aux==0.0.7
17
+ cycler==0.12.1
18
+ decorator==4.4.2
19
+ decord==0.6.0
20
+ diffusers==0.24.0
21
+ docker-pycreds==0.4.0
22
+ einops==0.8.2
23
+ exceptiongroup==1.3.1
24
+ executing==2.3.0
25
+ filelock==4.1.0
26
+ flatbuffers==25.12.19
27
+ fonttools==4.65.0
28
+ fsspec==2026.9.0
29
+ gitdb==4.0.12
30
+ gitpython==3.2.0
31
+ grpcio==1.84.0
32
+ h5py==3.16.0
33
+ huggingface-hub==0.25.2
34
+ humanfriendly==10.0
35
+ idna==3.20
36
+ igraph==0.11.6
37
+ imageio-ffmpeg==0.4.9
38
+ imageio==2.33.0
39
+ importlib-metadata==9.0.1
40
+ ipython==8.39.0
41
+ jedi==0.20.1
42
+ jinja2==3.1.6
43
+ joblib==1.6.0
44
+ kiwisolver==1.5.1
45
+ lazy-loader==0.6
46
+ librosa==0.10.2.post1
47
+ llvmlite==0.50.0
48
+ lmdb==3.0.0
49
+ loguru==0.7.3
50
+ markdown==3.10.3
51
+ markupsafe==3.0.4
52
+ matplotlib-inline==0.2.2
53
+ matplotlib==3.10.9
54
+ moviepy==1.0.3
55
+ mpmath==1.3.0
56
+ msgpack==1.2.3
57
+ networkx==3.4.2
58
+ numba==0.68.0
59
+ numpy==1.26.4
60
+ nvidia-cublas-cu12==12.1.3.1
61
+ nvidia-cuda-cupti-cu12==12.1.105
62
+ nvidia-cuda-nvrtc-cu12==12.1.105
63
+ nvidia-cuda-runtime-cu12==12.1.105
64
+ nvidia-cudnn-cu12==8.9.2.26
65
+ nvidia-cufft-cu12==11.0.2.54
66
+ nvidia-curand-cu12==10.3.2.106
67
+ nvidia-cusolver-cu12==11.4.5.107
68
+ nvidia-cusparse-cu12==12.1.0.106
69
+ nvidia-nccl-cu12==2.19.3
70
+ nvidia-nvjitlink-cu12==12.9.86
71
+ nvidia-nvtx-cu12==12.1.105
72
+ omegaconf==2.3.0
73
+ onnxruntime-gpu @ https://aiinfra.pkgs.visualstudio.com/2692857e-05ef-43b4-ba9c-ccf1c22c437c/_packaging/9387c3aa-d9ad-4513-968c-383f6f7f53b8/pypi/download/onnxruntime-gpu/1.18/onnxruntime_gpu-1.18.0-cp310-cp310-manylinux_2_28_x86_64.whl#sha256=039be9a6b7f71c6739e97eec79f4bf240793a7c0c4108a09e0e1a27b4c33dbca
74
+ opencv-python-headless==4.9.0.80
75
+ packaging==26.3
76
+ pandas==2.3.3
77
+ parso==0.8.7
78
+ pexpect==4.9.0
79
+ pillow==12.3.0
80
+ platformdirs==4.12.4
81
+ pooch==1.9.0
82
+ proglog==0.1.12
83
+ prompt-toolkit==3.0.53
84
+ protobuf==5.29.6
85
+ psutil==7.2.2
86
+ ptyprocess==0.7.0
87
+ pure-eval==0.2.4
88
+ pyarrow==25.0.1
89
+ pycparser==3.11
90
+ pygments==2.21.0
91
+ pyparsing==3.3.3
92
+ python-dateutil==2.9.0.post0
93
+ pytz==2026.5
94
+ pyyaml==6.0.3
95
+ regex==2026.9.29
96
+ requests==2.34.2
97
+ safetensors==0.8.0
98
+ scikit-image==0.25.2
99
+ scikit-learn==1.7.2
100
+ scipy==1.15.3
101
+ sentry-sdk==2.72.0
102
+ setproctitle==1.3.8
103
+ setuptools==80.10.2
104
+ six==1.17.0
105
+ smmap==5.0.3
106
+ smplx==0.1.28
107
+ soundfile==0.14.0
108
+ soxr==1.1.0
109
+ stack-data==0.6.3
110
+ sympy==1.14.0
111
+ tensorboard-data-server==0.7.2
112
+ tensorboard==2.18.0
113
+ termcolor==3.3.0
114
+ textgrid==1.6.1
115
+ texttable==1.7.1
116
+ threadpoolctl==3.7.0
117
+ tifffile==2025.5.10
118
+ timm==1.0.30
119
+ tokenizers==0.15.2
120
+ torch==2.2.2
121
+ torchvision==0.17.2
122
+ tqdm==4.70.1
123
+ traitlets==5.16.1
124
+ transformers==4.36.2
125
+ triton==2.2.0
126
+ typing-extensions==4.16.0
127
+ tzdata==2026.5
128
+ urllib3==2.8.0
129
+ wandb==0.17.9
130
+ wcwidth==0.9.2
131
+ werkzeug==3.1.9
132
+ xformers==0.0.25.post1
133
+ zipp==4.1.1
2610_variant_runtime/scripts/download_assets.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import hashlib
3
+ import json
4
+ import shutil
5
+ import urllib.request
6
+ from pathlib import Path
7
+
8
+
9
+ def verify(path, asset):
10
+ if not path.is_file() or path.stat().st_size != asset["bytes"]:
11
+ return False
12
+ digest = hashlib.sha256()
13
+ with path.open("rb") as stream:
14
+ for chunk in iter(lambda: stream.read(8 * 1024 * 1024), b""):
15
+ digest.update(chunk)
16
+ return digest.hexdigest() == asset["sha256"]
17
+
18
+
19
+ def main():
20
+ parser = argparse.ArgumentParser(description="Download and verify VMG models and raw examples.")
21
+ parser.add_argument("--group", choices=["all", "base", "preprocessing", "checkpoint", "examples"], default="all")
22
+ parser.add_argument("--verify-only", action="store_true")
23
+ args = parser.parse_args()
24
+ root = Path(__file__).resolve().parents[1]
25
+ assets = json.loads((root / "asset_manifest.json").read_text())["assets"]
26
+ missing = []
27
+ for asset in assets:
28
+ if args.group != "all" and asset["group"] != args.group:
29
+ continue
30
+ path = root / asset["path"]
31
+ if verify(path, asset):
32
+ print(f"Verified {asset['path']}", flush=True)
33
+ continue
34
+ if args.verify_only:
35
+ missing.append(asset["path"])
36
+ continue
37
+ path.parent.mkdir(parents=True, exist_ok=True)
38
+ temporary = path.with_name(path.name + ".part")
39
+ print(f"Downloading {asset['path']} ({asset['bytes']:,} bytes)", flush=True)
40
+ with urllib.request.urlopen(asset["url"], timeout=120) as response, temporary.open("wb") as output:
41
+ shutil.copyfileobj(response, output, length=8 * 1024 * 1024)
42
+ if not verify(temporary, asset):
43
+ raise RuntimeError(f"Checksum mismatch: {asset['path']}")
44
+ temporary.replace(path)
45
+ if missing:
46
+ raise SystemExit("Missing or invalid assets: " + ", ".join(missing))
47
+
48
+
49
+ if __name__ == "__main__":
50
+ main()
README.md CHANGED
@@ -27,3 +27,16 @@ Checkpoint SHA256: `9cc0f0354c5ec4b33085196ba5786f845e0901fd1dc7159e57be14d972c3
27
  Starting with only the raw 3,051-frame example video and music, the release code rebuilt pose and segmentation, constructed a 762-node / 1,059-edge graph, and generated three new diffusion transitions. The resulting video is 18 seconds, 768×768, 30 fps with audio. This run completed in 12 minutes 2 seconds on one H100 80GB.
28
 
29
  <video controls src="https://huggingface.co/H-Liu1997/Video-Motion-Graphs/resolve/main/examples/generated_demo.mp4"></video>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  Starting with only the raw 3,051-frame example video and music, the release code rebuilt pose and segmentation, constructed a 762-node / 1,059-edge graph, and generated three new diffusion transitions. The resulting video is 18 seconds, 768×768, 30 fps with audio. This run completed in 12 minutes 2 seconds on one H100 80GB.
28
 
29
  <video controls src="https://huggingface.co/H-Liu1997/Video-Motion-Graphs/resolve/main/examples/generated_demo.mp4"></video>
30
+ ## Historical interpolation variants
31
+
32
+ The following dated archival variants are separate from the original weighted-pose checkpoint above. Their downloaded source files passed full SHA256 checks and strict CPU key/shape checks. **GPU forward execution, rendered-video evaluation and fresh-Hub-download verification are pending.** The CPU checks did not perform a forward pass.
33
+
34
+ | Material Date | Historical Run | Step | Details |
35
+ | --- | --- | ---: | --- |
36
+ | 2024-09 | `v7_dup_14_continue_2` | 655000 | [2409 historical variant](2409_variants/v7_dup_14_continue_2_step655000/README.md) |
37
+ | 2024-11 | `v7_dup_14_s2_8frames_512` | 9000 | [2411 8-frame variant](2411_variants/v7_dup_14_s2_8frames_512_step9000/README.md) |
38
+ | 2024-11 | `v7_dup_14_s2_12frames_512` | 30000 | [2411 12-frame variant](2411_variants/v7_dup_14_s2_12frames_512_step30000/README.md) |
39
+
40
+ The [standalone runtime](2610_variant_runtime/README.md) contains the matching five-channel standard-VAE entrypoint, three configurations, pinned requirements, source licenses and a base-asset downloader. Its source snapshot is recorded in the [runtime hash manifest](2610_runtime_asset_manifest.json); model and configuration hashes are in the [variant asset manifest](2610_variant_asset_manifest.json).
41
+
42
+ Date prefixes describe the earliest confirmed source-material month. The relationship of step 655000 to the final TANGO or ACInterp model is unconfirmed; none of these checkpoints is labeled best or paper-final. Only model weights are retained, without optimizer or exact-resume state. The existing `finetune_weighted/checkpoint-8000` model and its previously verified example remain unchanged.