Image-to-3D
Hunyuan3D-2
Diffusers
Safetensors
English
Chinese
text-to-3d
ShaunSZ commited on
Commit
27268b8
·
verified ·
1 Parent(s): 3ec9fed

Upload 20 files

Browse files
hunyuan3d-paint-v2-0-turbo/.gitattributes ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
hunyuan3d-paint-v2-0-turbo/README.md ADDED
@@ -0,0 +1,53 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: openrail++
3
+ tags:
4
+ - stable-diffusion
5
+ - text-to-image
6
+ ---
7
+
8
+ # SD v2.1-base with Zero Terminal SNR (LAION Aesthetic 6+)
9
+
10
+ This model is used in [Diffusion Model with Perceptual Loss](https://arxiv.org/abs/2401.00110) paper as the MSE baseline.
11
+
12
+ This model is trained using zero terminal SNR schedule following [Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/abs/2305.08891) paper on LAION aesthetic 6+ data.
13
+
14
+ This model is finetuned from [stabilityai/stable-diffusion-2-1-base](https://huggingface.co/stabilityai/stable-diffusion-2-1-base).
15
+
16
+ This model is meant for research demonstration, not for production use.
17
+
18
+ ## Usage
19
+
20
+ ```python
21
+ from diffusers import StableDiffusionPipeline
22
+ prompt = "A young girl smiling"
23
+ pipe = StableDiffusionPipeline.from_pretrained("ByteDance/sd2.1-base-zsnr-laionaes6").to("cuda")
24
+ pipe(prompt, guidance_scale=7.5, guidance_rescale=0.7).images[0].save("out.jpg")
25
+ ```
26
+
27
+ ## Related Models
28
+
29
+ * [bytedance/sd2.1-base-zsnr-laionaes5](https://huggingface.co/ByteDance/sd2.1-base-zsnr-laionaes5)
30
+ * [bytedance/sd2.1-base-zsnr-laionaes6](https://huggingface.co/ByteDance/sd2.1-base-zsnr-laionaes6)
31
+ * [bytedance/sd2.1-base-zsnr-laionaes6-perceptual](https://huggingface.co/ByteDance/sd2.1-base-zsnr-laionaes6-perceptual)
32
+
33
+
34
+ ## Cite as
35
+ ```
36
+ @misc{lin2024diffusion,
37
+ title={Diffusion Model with Perceptual Loss},
38
+ author={Shanchuan Lin and Xiao Yang},
39
+ year={2024},
40
+ eprint={2401.00110},
41
+ archivePrefix={arXiv},
42
+ primaryClass={cs.CV}
43
+ }
44
+
45
+ @misc{lin2023common,
46
+ title={Common Diffusion Noise Schedules and Sample Steps are Flawed},
47
+ author={Shanchuan Lin and Bingchen Liu and Jiashi Li and Xiao Yang},
48
+ year={2023},
49
+ eprint={2305.08891},
50
+ archivePrefix={arXiv},
51
+ primaryClass={cs.CV}
52
+ }
53
+ ```
hunyuan3d-paint-v2-0-turbo/feature_extractor/preprocessor_config.json ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": 224,
3
+ "do_center_crop": true,
4
+ "do_convert_rgb": true,
5
+ "do_normalize": true,
6
+ "do_resize": true,
7
+ "feature_extractor_type": "CLIPFeatureExtractor",
8
+ "image_mean": [
9
+ 0.48145466,
10
+ 0.4578275,
11
+ 0.40821073
12
+ ],
13
+ "image_std": [
14
+ 0.26862954,
15
+ 0.26130258,
16
+ 0.27577711
17
+ ],
18
+ "resample": 3,
19
+ "size": 224
20
+ }
hunyuan3d-paint-v2-0-turbo/image_encoder/config.json ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "D:\\.cache\\huggingface\\hub\\models--sudo-ai--zero123plus-v1.1\\snapshots\\36df7de980afd15f80b2e1a4e9a920d7020e2654\\vision_encoder",
3
+ "architectures": [
4
+ "CLIPVisionModelWithProjection"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "dropout": 0.0,
8
+ "hidden_act": "gelu",
9
+ "hidden_size": 1280,
10
+ "image_size": 224,
11
+ "initializer_factor": 1.0,
12
+ "initializer_range": 0.02,
13
+ "intermediate_size": 5120,
14
+ "layer_norm_eps": 1e-05,
15
+ "model_type": "clip_vision_model",
16
+ "num_attention_heads": 16,
17
+ "num_channels": 3,
18
+ "num_hidden_layers": 32,
19
+ "patch_size": 14,
20
+ "projection_dim": 1024,
21
+ "torch_dtype": "float16",
22
+ "transformers_version": "4.36.0"
23
+ }
hunyuan3d-paint-v2-0-turbo/image_encoder/model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ae616c24393dd1854372b0639e5541666f7521cbe219669255e865cb7f89466a
3
+ size 1264217240
hunyuan3d-paint-v2-0-turbo/image_encoder/preprocessor_config.json ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "crop_size": {
3
+ "height": 224,
4
+ "width": 224
5
+ },
6
+ "do_center_crop": true,
7
+ "do_convert_rgb": true,
8
+ "do_normalize": true,
9
+ "do_rescale": true,
10
+ "do_resize": true,
11
+ "image_mean": [
12
+ 0.48145466,
13
+ 0.4578275,
14
+ 0.40821073
15
+ ],
16
+ "image_processor_type": "CLIPImageProcessor",
17
+ "image_std": [
18
+ 0.26862954,
19
+ 0.26130258,
20
+ 0.27577711
21
+ ],
22
+ "resample": 3,
23
+ "rescale_factor": 0.00392156862745098,
24
+ "size": {
25
+ "shortest_edge": 224
26
+ }
27
+ }
hunyuan3d-paint-v2-0-turbo/model_index.json ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "StableDiffusionPipeline",
3
+ "_diffusers_version": "0.23.1",
4
+ "feature_extractor": [
5
+ "transformers",
6
+ "CLIPImageProcessor"
7
+ ],
8
+ "requires_safety_checker": false,
9
+ "safety_checker": [
10
+ null,
11
+ null
12
+ ],
13
+ "scheduler": [
14
+ "diffusers",
15
+ "DDIMScheduler"
16
+ ],
17
+ "text_encoder": [
18
+ "transformers",
19
+ "CLIPTextModel"
20
+ ],
21
+ "tokenizer": [
22
+ "transformers",
23
+ "CLIPTokenizer"
24
+ ],
25
+ "image_encoder": [
26
+ "transformers",
27
+ "CLIPVisionModelWithProjection"
28
+ ],
29
+ "unet": [
30
+ "modules",
31
+ "UNet2p5DConditionModel"
32
+ ],
33
+ "vae": [
34
+ "diffusers",
35
+ "AutoencoderKL"
36
+ ]
37
+ }
hunyuan3d-paint-v2-0-turbo/scheduler/scheduler_config.json ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "DDIMScheduler",
3
+ "_diffusers_version": "0.23.1",
4
+ "beta_end": 0.012,
5
+ "beta_schedule": "scaled_linear",
6
+ "beta_start": 0.00085,
7
+ "clip_sample": false,
8
+ "num_train_timesteps": 1000,
9
+ "prediction_type": "v_prediction",
10
+ "set_alpha_to_one": true,
11
+ "steps_offset": 1,
12
+ "trained_betas": null,
13
+ "timestep_spacing": "trailing",
14
+ "rescale_betas_zero_snr": true
15
+ }
hunyuan3d-paint-v2-0-turbo/text_encoder/config.json ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "stabilityai/stable-diffusion-2",
3
+ "architectures": [
4
+ "CLIPTextModel"
5
+ ],
6
+ "attention_dropout": 0.0,
7
+ "bos_token_id": 0,
8
+ "dropout": 0.0,
9
+ "eos_token_id": 2,
10
+ "hidden_act": "gelu",
11
+ "hidden_size": 1024,
12
+ "initializer_factor": 1.0,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 4096,
15
+ "layer_norm_eps": 1e-05,
16
+ "max_position_embeddings": 77,
17
+ "model_type": "clip_text_model",
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 23,
20
+ "pad_token_id": 1,
21
+ "projection_dim": 512,
22
+ "torch_dtype": "float32",
23
+ "transformers_version": "4.25.0.dev0",
24
+ "vocab_size": 49408
25
+ }
hunyuan3d-paint-v2-0-turbo/text_encoder/pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c3e254d7b61353497ea0be2c4013df4ea8f739ee88cffa0ba58cd085459ed565
3
+ size 1361671895
hunyuan3d-paint-v2-0-turbo/tokenizer/merges.txt ADDED
The diff for this file is too large to render. See raw diff
 
hunyuan3d-paint-v2-0-turbo/tokenizer/special_tokens_map.json ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "bos_token": {
3
+ "content": "<|startoftext|>",
4
+ "lstrip": false,
5
+ "normalized": true,
6
+ "rstrip": false,
7
+ "single_word": false
8
+ },
9
+ "eos_token": {
10
+ "content": "<|endoftext|>",
11
+ "lstrip": false,
12
+ "normalized": true,
13
+ "rstrip": false,
14
+ "single_word": false
15
+ },
16
+ "pad_token": "!",
17
+ "unk_token": {
18
+ "content": "<|endoftext|>",
19
+ "lstrip": false,
20
+ "normalized": true,
21
+ "rstrip": false,
22
+ "single_word": false
23
+ }
24
+ }
hunyuan3d-paint-v2-0-turbo/tokenizer/tokenizer_config.json ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "add_prefix_space": false,
3
+ "bos_token": {
4
+ "__type": "AddedToken",
5
+ "content": "<|startoftext|>",
6
+ "lstrip": false,
7
+ "normalized": true,
8
+ "rstrip": false,
9
+ "single_word": false
10
+ },
11
+ "do_lower_case": true,
12
+ "eos_token": {
13
+ "__type": "AddedToken",
14
+ "content": "<|endoftext|>",
15
+ "lstrip": false,
16
+ "normalized": true,
17
+ "rstrip": false,
18
+ "single_word": false
19
+ },
20
+ "errors": "replace",
21
+ "model_max_length": 77,
22
+ "name_or_path": "stabilityai/stable-diffusion-2",
23
+ "pad_token": "<|endoftext|>",
24
+ "special_tokens_map_file": "./special_tokens_map.json",
25
+ "tokenizer_class": "CLIPTokenizer",
26
+ "unk_token": {
27
+ "__type": "AddedToken",
28
+ "content": "<|endoftext|>",
29
+ "lstrip": false,
30
+ "normalized": true,
31
+ "rstrip": false,
32
+ "single_word": false
33
+ }
34
+ }
hunyuan3d-paint-v2-0-turbo/tokenizer/vocab.json ADDED
The diff for this file is too large to render. See raw diff
 
hunyuan3d-paint-v2-0-turbo/unet/config.json ADDED
@@ -0,0 +1,45 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "UNet2DConditionModel",
3
+ "_diffusers_version": "0.10.0.dev0",
4
+ "act_fn": "silu",
5
+ "attention_head_dim": [
6
+ 5,
7
+ 10,
8
+ 20,
9
+ 20
10
+ ],
11
+ "block_out_channels": [
12
+ 320,
13
+ 640,
14
+ 1280,
15
+ 1280
16
+ ],
17
+ "center_input_sample": false,
18
+ "cross_attention_dim": 1024,
19
+ "down_block_types": [
20
+ "CrossAttnDownBlock2D",
21
+ "CrossAttnDownBlock2D",
22
+ "CrossAttnDownBlock2D",
23
+ "DownBlock2D"
24
+ ],
25
+ "downsample_padding": 1,
26
+ "dual_cross_attention": false,
27
+ "flip_sin_to_cos": true,
28
+ "freq_shift": 0,
29
+ "in_channels": 4,
30
+ "layers_per_block": 2,
31
+ "mid_block_scale_factor": 1,
32
+ "norm_eps": 1e-05,
33
+ "norm_num_groups": 32,
34
+ "num_class_embeds": null,
35
+ "only_cross_attention": false,
36
+ "out_channels": 4,
37
+ "sample_size": 64,
38
+ "up_block_types": [
39
+ "UpBlock2D",
40
+ "CrossAttnUpBlock2D",
41
+ "CrossAttnUpBlock2D",
42
+ "CrossAttnUpBlock2D"
43
+ ],
44
+ "use_linear_projection": true
45
+ }
hunyuan3d-paint-v2-0-turbo/unet/diffusion_pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:690a5fc63c4e263ba07dd41dc95f86f702c059c4361b863e2e21af88d8f75714
3
+ size 3722674238
hunyuan3d-paint-v2-0-turbo/unet/diffusion_pytorch_model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d6acffa4a22f4da61d87f446bfa83e7ac245481c1535fbf25b200fe4462d0b22
3
+ size 3722161032
hunyuan3d-paint-v2-0-turbo/unet/modules.py ADDED
@@ -0,0 +1,926 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Open Source Model Licensed under the Apache License Version 2.0
2
+ # and Other Licenses of the Third-Party Components therein:
3
+ # The below Model in this distribution may have been modified by THL A29 Limited
4
+ # ("Tencent Modifications"). All Tencent Modifications are Copyright (C) 2024 THL A29 Limited.
5
+
6
+ # Copyright (C) 2024 THL A29 Limited, a Tencent company. All rights reserved.
7
+ # The below software and/or models in this distribution may have been
8
+ # modified by THL A29 Limited ("Tencent Modifications").
9
+ # All Tencent Modifications are Copyright (C) THL A29 Limited.
10
+
11
+ # Hunyuan 3D is licensed under the TENCENT HUNYUAN NON-COMMERCIAL LICENSE AGREEMENT
12
+ # except for the third-party components listed below.
13
+ # Hunyuan 3D does not impose any additional limitations beyond what is outlined
14
+ # in the repsective licenses of these third-party components.
15
+ # Users must comply with all terms and conditions of original licenses of these third-party
16
+ # components and must ensure that the usage of the third party components adheres to
17
+ # all relevant laws and regulations.
18
+
19
+ # For avoidance of doubts, Hunyuan 3D means the large language models and
20
+ # their software and algorithms, including trained model weights, parameters (including
21
+ # optimizer states), machine-learning model code, inference-enabling code, training-enabling code,
22
+ # fine-tuning enabling code and other elements of the foregoing made publicly available
23
+ # by Tencent in accordance with TENCENT HUNYUAN COMMUNITY LICENSE AGREEMENT.
24
+
25
+
26
+ import copy
27
+ import json
28
+ import os
29
+ from typing import Any, Dict, List, Optional, Tuple, Union
30
+
31
+ import torch
32
+ import torch.nn as nn
33
+ import torch.nn.functional as F
34
+ from diffusers.models import UNet2DConditionModel
35
+ from diffusers.models.attention_processor import Attention
36
+ from diffusers.models.transformers.transformer_2d import BasicTransformerBlock
37
+ from einops import rearrange
38
+
39
+
40
+ def _chunked_feed_forward(ff: nn.Module, hidden_states: torch.Tensor, chunk_dim: int, chunk_size: int):
41
+ # "feed_forward_chunk_size" can be used to save memory
42
+ if hidden_states.shape[chunk_dim] % chunk_size != 0:
43
+ raise ValueError(
44
+ f"`hidden_states` dimension to be chunked: {hidden_states.shape[chunk_dim]} has to be divisible by chunk size: {chunk_size}. Make sure to set an appropriate `chunk_size` when calling `unet.enable_forward_chunking`."
45
+ )
46
+
47
+ num_chunks = hidden_states.shape[chunk_dim] // chunk_size
48
+ ff_output = torch.cat(
49
+ [ff(hid_slice) for hid_slice in hidden_states.chunk(num_chunks, dim=chunk_dim)],
50
+ dim=chunk_dim,
51
+ )
52
+ return ff_output
53
+
54
+ class PoseRoPEAttnProcessor2_0:
55
+ r"""
56
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
57
+ """
58
+
59
+ def __init__(self):
60
+ if not hasattr(F, "scaled_dot_product_attention"):
61
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
62
+
63
+ def get_1d_rotary_pos_embed(
64
+ self,
65
+ dim: int,
66
+ pos: torch.Tensor,
67
+ theta: float = 10000.0,
68
+ linear_factor=1.0,
69
+ ntk_factor=1.0,
70
+ ):
71
+ assert dim % 2 == 0
72
+
73
+ theta = theta * ntk_factor
74
+ freqs = (
75
+ 1.0
76
+ / (theta ** (torch.arange(0, dim, 2, dtype=pos.dtype, device=pos.device)[: (dim // 2)] / dim))
77
+ / linear_factor
78
+ ) # [D/2]
79
+ freqs = torch.outer(pos, freqs) # type: ignore # [S, D/2]
80
+ # flux, hunyuan-dit, cogvideox
81
+ freqs_cos = freqs.cos().repeat_interleave(2, dim=1).float() # [S, D]
82
+ freqs_sin = freqs.sin().repeat_interleave(2, dim=1).float() # [S, D]
83
+ return freqs_cos, freqs_sin
84
+
85
+
86
+ def get_3d_rotary_pos_embed(
87
+ self,
88
+ position,
89
+ embed_dim,
90
+ voxel_resolution,
91
+ theta: int = 10000,
92
+ ) -> Union[torch.Tensor, Tuple[torch.Tensor, torch.Tensor]]:
93
+ """
94
+ RoPE for video tokens with 3D structure.
95
+
96
+ Args:
97
+ voxel_resolution (`int`):
98
+ The grid size of the spatial positional embedding (height, width).
99
+ theta (`float`):
100
+ Scaling factor for frequency computation.
101
+
102
+ Returns:
103
+ `torch.Tensor`: positional embedding with shape `(temporal_size * grid_size[0] * grid_size[1], embed_dim/2)`.
104
+ """
105
+ assert position.shape[-1]==3
106
+
107
+ # Compute dimensions for each axis
108
+ dim_xy = embed_dim // 8 * 3
109
+ dim_z = embed_dim // 8 * 2
110
+
111
+ # Temporal frequencies
112
+ grid = torch.arange(voxel_resolution, dtype=torch.float32, device=position.device)
113
+ freqs_xy = self.get_1d_rotary_pos_embed(dim_xy, grid, theta=theta)
114
+ freqs_z = self.get_1d_rotary_pos_embed(dim_z, grid, theta=theta)
115
+
116
+ xy_cos, xy_sin = freqs_xy # both t_cos and t_sin has shape: voxel_resolution, dim_xy
117
+ z_cos, z_sin = freqs_z # both w_cos and w_sin has shape: voxel_resolution, dim_z
118
+
119
+ embed_flattn = position.view(-1, position.shape[-1])
120
+ x_cos = xy_cos[embed_flattn[:,0], :]
121
+ x_sin = xy_sin[embed_flattn[:,0], :]
122
+ y_cos = xy_cos[embed_flattn[:,1], :]
123
+ y_sin = xy_sin[embed_flattn[:,1], :]
124
+ z_cos = z_cos[embed_flattn[:,2], :]
125
+ z_sin = z_sin[embed_flattn[:,2], :]
126
+
127
+ cos = torch.cat((x_cos, y_cos, z_cos), dim=-1)
128
+ sin = torch.cat((x_sin, y_sin, z_sin), dim=-1)
129
+
130
+ cos = cos.view(*position.shape[:-1], embed_dim)
131
+ sin = sin.view(*position.shape[:-1], embed_dim)
132
+ return cos, sin
133
+
134
+ def apply_rotary_emb(
135
+ self,
136
+ x: torch.Tensor,
137
+ freqs_cis: Union[torch.Tensor, Tuple[torch.Tensor]]
138
+ ):
139
+ cos, sin = freqs_cis # [S, D]
140
+ cos, sin = cos.to(x.device), sin.to(x.device)
141
+ cos = cos.unsqueeze(1)
142
+ sin = sin.unsqueeze(1)
143
+
144
+ x_real, x_imag = x.reshape(*x.shape[:-1], -1, 2).unbind(-1) # [B, S, H, D//2]
145
+ x_rotated = torch.stack([-x_imag, x_real], dim=-1).flatten(3)
146
+
147
+ out = (x.float() * cos + x_rotated.float() * sin).to(x.dtype)
148
+
149
+ return out
150
+
151
+ def __call__(
152
+ self,
153
+ attn: Attention,
154
+ hidden_states: torch.Tensor,
155
+ encoder_hidden_states: Optional[torch.Tensor] = None,
156
+ attention_mask: Optional[torch.Tensor] = None,
157
+ position_indices: Dict = None,
158
+ temb: Optional[torch.Tensor] = None,
159
+ *args,
160
+ **kwargs,
161
+ ) -> torch.Tensor:
162
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
163
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
164
+ deprecate("scale", "1.0.0", deprecation_message)
165
+
166
+ residual = hidden_states
167
+ if attn.spatial_norm is not None:
168
+ hidden_states = attn.spatial_norm(hidden_states, temb)
169
+
170
+ input_ndim = hidden_states.ndim
171
+
172
+ if input_ndim == 4:
173
+ batch_size, channel, height, width = hidden_states.shape
174
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
175
+
176
+ batch_size, sequence_length, _ = (
177
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
178
+ )
179
+
180
+ if attention_mask is not None:
181
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
182
+ # scaled_dot_product_attention expects attention_mask shape to be
183
+ # (batch, heads, source_length, target_length)
184
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
185
+
186
+ if attn.group_norm is not None:
187
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
188
+
189
+ query = attn.to_q(hidden_states)
190
+
191
+ if encoder_hidden_states is None:
192
+ encoder_hidden_states = hidden_states
193
+ elif attn.norm_cross:
194
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
195
+
196
+ key = attn.to_k(encoder_hidden_states)
197
+ value = attn.to_v(encoder_hidden_states)
198
+
199
+ inner_dim = key.shape[-1]
200
+ head_dim = inner_dim // attn.heads
201
+
202
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
203
+
204
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
205
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
206
+
207
+ if attn.norm_q is not None:
208
+ query = attn.norm_q(query)
209
+ if attn.norm_k is not None:
210
+ key = attn.norm_k(key)
211
+
212
+ if position_indices is not None:
213
+ if head_dim in position_indices:
214
+ image_rotary_emb = position_indices[head_dim]
215
+ else:
216
+ image_rotary_emb = self.get_3d_rotary_pos_embed(position_indices['voxel_indices'], head_dim, voxel_resolution=position_indices['voxel_resolution'])
217
+ position_indices[head_dim] = image_rotary_emb
218
+ query = self.apply_rotary_emb(query, image_rotary_emb)
219
+ key = self.apply_rotary_emb(key, image_rotary_emb)
220
+
221
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
222
+ # TODO: add support for attn.scale when we move to Torch 2.1
223
+ hidden_states = F.scaled_dot_product_attention(
224
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
225
+ )
226
+
227
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
228
+ hidden_states = hidden_states.to(query.dtype)
229
+
230
+ # linear proj
231
+ hidden_states = attn.to_out[0](hidden_states)
232
+ # dropout
233
+ hidden_states = attn.to_out[1](hidden_states)
234
+
235
+ if input_ndim == 4:
236
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
237
+
238
+ if attn.residual_connection:
239
+ hidden_states = hidden_states + residual
240
+
241
+ hidden_states = hidden_states / attn.rescale_output_factor
242
+
243
+ return hidden_states
244
+
245
+ class IPAttnProcessor2_0:
246
+ r"""
247
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
248
+ """
249
+
250
+ def __init__(self, scale=0.0):
251
+ if not hasattr(F, "scaled_dot_product_attention"):
252
+ raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
253
+
254
+ self.scale = scale
255
+
256
+ def __call__(
257
+ self,
258
+ attn: Attention,
259
+ hidden_states: torch.Tensor,
260
+ encoder_hidden_states: Optional[torch.Tensor] = None,
261
+ ip_hidden_states: Optional[torch.Tensor] = None,
262
+ attention_mask: Optional[torch.Tensor] = None,
263
+ temb: Optional[torch.Tensor] = None,
264
+ *args,
265
+ **kwargs,
266
+ ) -> torch.Tensor:
267
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
268
+ deprecation_message = "The `scale` argument is deprecated and will be ignored. Please remove it, as passing it will raise an error in the future. `scale` should directly be passed while calling the underlying pipeline component i.e., via `cross_attention_kwargs`."
269
+ deprecate("scale", "1.0.0", deprecation_message)
270
+
271
+ residual = hidden_states
272
+ if attn.spatial_norm is not None:
273
+ hidden_states = attn.spatial_norm(hidden_states, temb)
274
+
275
+ input_ndim = hidden_states.ndim
276
+
277
+ if input_ndim == 4:
278
+ batch_size, channel, height, width = hidden_states.shape
279
+ hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
280
+
281
+ batch_size, sequence_length, _ = (
282
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
283
+ )
284
+
285
+ if attention_mask is not None:
286
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
287
+ # scaled_dot_product_attention expects attention_mask shape to be
288
+ # (batch, heads, source_length, target_length)
289
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
290
+
291
+ if attn.group_norm is not None:
292
+ hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
293
+
294
+ query = attn.to_q(hidden_states)
295
+
296
+ if encoder_hidden_states is None:
297
+ encoder_hidden_states = hidden_states
298
+ elif attn.norm_cross:
299
+ encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
300
+
301
+ key = attn.to_k(encoder_hidden_states)
302
+ value = attn.to_v(encoder_hidden_states)
303
+
304
+ inner_dim = key.shape[-1]
305
+ head_dim = inner_dim // attn.heads
306
+
307
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
308
+
309
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
310
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
311
+
312
+ if attn.norm_q is not None:
313
+ query = attn.norm_q(query)
314
+ if attn.norm_k is not None:
315
+ key = attn.norm_k(key)
316
+
317
+
318
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
319
+ # TODO: add support for attn.scale when we move to Torch 2.1
320
+ hidden_states = F.scaled_dot_product_attention(
321
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
322
+ )
323
+
324
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
325
+ hidden_states = hidden_states.to(query.dtype)
326
+
327
+ # for ip adapter
328
+ if ip_hidden_states is not None:
329
+
330
+ ip_key = attn.to_k_ip(ip_hidden_states)
331
+ ip_value = attn.to_v_ip(ip_hidden_states)
332
+
333
+ ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
334
+ ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
335
+
336
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
337
+ ip_hidden_states = F.scaled_dot_product_attention(
338
+ query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
339
+ )
340
+
341
+ ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
342
+ ip_hidden_states = ip_hidden_states.to(query.dtype)
343
+
344
+ hidden_states = hidden_states + self.scale * ip_hidden_states
345
+
346
+ # linear proj
347
+ hidden_states = attn.to_out[0](hidden_states)
348
+ # dropout
349
+ hidden_states = attn.to_out[1](hidden_states)
350
+
351
+ if input_ndim == 4:
352
+ hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
353
+
354
+ if attn.residual_connection:
355
+ hidden_states = hidden_states + residual
356
+
357
+ hidden_states = hidden_states / attn.rescale_output_factor
358
+
359
+ return hidden_states
360
+
361
+
362
+ class Basic2p5DTransformerBlock(torch.nn.Module):
363
+ def __init__(self, transformer: BasicTransformerBlock, layer_name, use_ipa=True, use_ma=True, use_ra=True) -> None:
364
+ super().__init__()
365
+ self.transformer = transformer
366
+ self.layer_name = layer_name
367
+ self.use_ipa = use_ipa
368
+ self.use_ma = use_ma
369
+ self.use_ra = use_ra
370
+
371
+ if use_ipa:
372
+ self.attn2.set_processor(IPAttnProcessor2_0())
373
+ cross_attention_dim = 1024
374
+ self.attn2.to_k_ip = nn.Linear(cross_attention_dim, self.dim, bias=False)
375
+ self.attn2.to_v_ip = nn.Linear(cross_attention_dim, self.dim, bias=False)
376
+
377
+ # multiview attn
378
+ if self.use_ma:
379
+ self.attn_multiview = Attention(
380
+ query_dim=self.dim,
381
+ heads=self.num_attention_heads,
382
+ dim_head=self.attention_head_dim,
383
+ dropout=self.dropout,
384
+ bias=self.attention_bias,
385
+ cross_attention_dim=None,
386
+ upcast_attention=self.attn1.upcast_attention,
387
+ out_bias=True,
388
+ processor=PoseRoPEAttnProcessor2_0(),
389
+ )
390
+
391
+ # ref attn
392
+ if self.use_ra:
393
+ self.attn_refview = Attention(
394
+ query_dim=self.dim,
395
+ heads=self.num_attention_heads,
396
+ dim_head=self.attention_head_dim,
397
+ dropout=self.dropout,
398
+ bias=self.attention_bias,
399
+ cross_attention_dim=None,
400
+ upcast_attention=self.attn1.upcast_attention,
401
+ out_bias=True,
402
+ )
403
+
404
+ self._initialize_attn_weights()
405
+
406
+ def _initialize_attn_weights(self):
407
+
408
+ if self.use_ma:
409
+ self.attn_multiview.load_state_dict(self.attn1.state_dict())
410
+ with torch.no_grad():
411
+ for layer in self.attn_multiview.to_out:
412
+ for param in layer.parameters():
413
+ param.zero_()
414
+ if self.use_ra:
415
+ self.attn_refview.load_state_dict(self.attn1.state_dict())
416
+ with torch.no_grad():
417
+ for layer in self.attn_refview.to_out:
418
+ for param in layer.parameters():
419
+ param.zero_()
420
+
421
+ if self.use_ipa:
422
+ self.attn2.to_k_ip.load_state_dict(self.attn2.to_k.state_dict())
423
+ self.attn2.to_v_ip.load_state_dict(self.attn2.to_v.state_dict())
424
+
425
+ def __getattr__(self, name: str):
426
+ try:
427
+ return super().__getattr__(name)
428
+ except AttributeError:
429
+ return getattr(self.transformer, name)
430
+
431
+ def forward(
432
+ self,
433
+ hidden_states: torch.Tensor,
434
+ attention_mask: Optional[torch.Tensor] = None,
435
+ encoder_hidden_states: Optional[torch.Tensor] = None,
436
+ encoder_attention_mask: Optional[torch.Tensor] = None,
437
+ timestep: Optional[torch.LongTensor] = None,
438
+ cross_attention_kwargs: Dict[str, Any] = None,
439
+ class_labels: Optional[torch.LongTensor] = None,
440
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
441
+ ) -> torch.Tensor:
442
+
443
+ # Notice that normalization is always applied before the real computation in the following blocks.
444
+ # 0. Self-Attention
445
+ batch_size = hidden_states.shape[0]
446
+
447
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
448
+ num_in_batch = cross_attention_kwargs.pop('num_in_batch', 1)
449
+ mode = cross_attention_kwargs.pop('mode', None)
450
+ condition_embed_dict = cross_attention_kwargs.pop("condition_embed_dict", None)
451
+ ip_hidden_states = cross_attention_kwargs.pop("ip_hidden_states", None)
452
+ position_attn_mask = cross_attention_kwargs.pop("position_attn_mask", None)
453
+ position_voxel_indices = cross_attention_kwargs.pop("position_voxel_indices", None)
454
+
455
+ if self.norm_type == "ada_norm":
456
+ norm_hidden_states = self.norm1(hidden_states, timestep)
457
+ elif self.norm_type == "ada_norm_zero":
458
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(
459
+ hidden_states, timestep, class_labels, hidden_dtype=hidden_states.dtype
460
+ )
461
+ elif self.norm_type in ["layer_norm", "layer_norm_i2vgen"]:
462
+ norm_hidden_states = self.norm1(hidden_states)
463
+ elif self.norm_type == "ada_norm_continuous":
464
+ norm_hidden_states = self.norm1(hidden_states, added_cond_kwargs["pooled_text_emb"])
465
+ elif self.norm_type == "ada_norm_single":
466
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
467
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
468
+ ).chunk(6, dim=1)
469
+ norm_hidden_states = self.norm1(hidden_states)
470
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
471
+ else:
472
+ raise ValueError("Incorrect norm used")
473
+
474
+ if self.pos_embed is not None:
475
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
476
+
477
+ # 1. Prepare GLIGEN inputs
478
+ cross_attention_kwargs = cross_attention_kwargs.copy() if cross_attention_kwargs is not None else {}
479
+ gligen_kwargs = cross_attention_kwargs.pop("gligen", None)
480
+
481
+ attn_output = self.attn1(
482
+ norm_hidden_states,
483
+ encoder_hidden_states=encoder_hidden_states if self.only_cross_attention else None,
484
+ attention_mask=attention_mask,
485
+ **cross_attention_kwargs,
486
+ )
487
+ if self.norm_type == "ada_norm_zero":
488
+ attn_output = gate_msa.unsqueeze(1) * attn_output
489
+ elif self.norm_type == "ada_norm_single":
490
+ attn_output = gate_msa * attn_output
491
+
492
+ hidden_states = attn_output + hidden_states
493
+ if hidden_states.ndim == 4:
494
+ hidden_states = hidden_states.squeeze(1)
495
+
496
+ # 1.2 Reference Attention
497
+ if 'w' in mode:
498
+ condition_embed_dict[self.layer_name] = rearrange(norm_hidden_states, '(b n) l c -> b (n l) c', n=num_in_batch) # B, (N L), C
499
+
500
+ if 'r' in mode:
501
+ condition_embed = condition_embed_dict[self.layer_name].unsqueeze(1).repeat(1,num_in_batch,1,1) # B N L C
502
+ condition_embed = rearrange(condition_embed, 'b n l c -> (b n) l c')
503
+
504
+ attn_output = self.attn_refview(
505
+ norm_hidden_states,
506
+ encoder_hidden_states=condition_embed,
507
+ attention_mask=None,
508
+ **cross_attention_kwargs
509
+ )
510
+
511
+ hidden_states = attn_output + hidden_states
512
+ if hidden_states.ndim == 4:
513
+ hidden_states = hidden_states.squeeze(1)
514
+
515
+
516
+ # 1.3 Multiview Attention
517
+ if num_in_batch > 1 and self.use_ma:
518
+ multivew_hidden_states = rearrange(norm_hidden_states, '(b n) l c -> b (n l) c', n=num_in_batch)
519
+ position_mask = None
520
+ if position_attn_mask is not None:
521
+ if multivew_hidden_states.shape[1] in position_attn_mask:
522
+ position_mask = position_attn_mask[multivew_hidden_states.shape[1]]
523
+ position_indices = None
524
+ if position_voxel_indices is not None:
525
+ if multivew_hidden_states.shape[1] in position_voxel_indices:
526
+ position_indices = position_voxel_indices[multivew_hidden_states.shape[1]]
527
+
528
+ attn_output = self.attn_multiview(
529
+ multivew_hidden_states,
530
+ encoder_hidden_states=multivew_hidden_states,
531
+ attention_mask=position_mask,
532
+ position_indices=position_indices,
533
+ **cross_attention_kwargs
534
+ )
535
+
536
+ attn_output = rearrange(attn_output, 'b (n l) c -> (b n) l c', n=num_in_batch)
537
+
538
+ hidden_states = attn_output + hidden_states
539
+ if hidden_states.ndim == 4:
540
+ hidden_states = hidden_states.squeeze(1)
541
+
542
+ # 1.2 GLIGEN Control
543
+ if gligen_kwargs is not None:
544
+ hidden_states = self.fuser(hidden_states, gligen_kwargs["objs"])
545
+
546
+ # 3. Cross-Attention
547
+ if self.attn2 is not None:
548
+ if self.norm_type == "ada_norm":
549
+ norm_hidden_states = self.norm2(hidden_states, timestep)
550
+ elif self.norm_type in ["ada_norm_zero", "layer_norm", "layer_norm_i2vgen"]:
551
+ norm_hidden_states = self.norm2(hidden_states)
552
+ elif self.norm_type == "ada_norm_single":
553
+ # For PixArt norm2 isn't applied here:
554
+ # https://github.com/PixArt-alpha/PixArt-alpha/blob/0f55e922376d8b797edd44d25d0e7464b260dcab/diffusion/model/nets/PixArtMS.py#L70C1-L76C103
555
+ norm_hidden_states = hidden_states
556
+ elif self.norm_type == "ada_norm_continuous":
557
+ norm_hidden_states = self.norm2(hidden_states, added_cond_kwargs["pooled_text_emb"])
558
+ else:
559
+ raise ValueError("Incorrect norm")
560
+
561
+ if self.pos_embed is not None and self.norm_type != "ada_norm_single":
562
+ norm_hidden_states = self.pos_embed(norm_hidden_states)
563
+
564
+ if ip_hidden_states is not None:
565
+ ip_hidden_states = ip_hidden_states.unsqueeze(1).repeat(1,num_in_batch,1,1) # B N L C
566
+ ip_hidden_states = rearrange(ip_hidden_states, 'b n l c -> (b n) l c')
567
+
568
+ if self.use_ipa:
569
+ attn_output = self.attn2(
570
+ norm_hidden_states,
571
+ encoder_hidden_states=encoder_hidden_states,
572
+ ip_hidden_states=ip_hidden_states,
573
+ attention_mask=encoder_attention_mask,
574
+ **cross_attention_kwargs,
575
+ )
576
+ else:
577
+ attn_output = self.attn2(
578
+ norm_hidden_states,
579
+ encoder_hidden_states=encoder_hidden_states,
580
+ attention_mask=encoder_attention_mask,
581
+ **cross_attention_kwargs,
582
+ )
583
+
584
+ hidden_states = attn_output + hidden_states
585
+
586
+ # 4. Feed-forward
587
+ # i2vgen doesn't have this norm 🤷‍♂️
588
+ if self.norm_type == "ada_norm_continuous":
589
+ norm_hidden_states = self.norm3(hidden_states, added_cond_kwargs["pooled_text_emb"])
590
+ elif not self.norm_type == "ada_norm_single":
591
+ norm_hidden_states = self.norm3(hidden_states)
592
+
593
+ if self.norm_type == "ada_norm_zero":
594
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
595
+
596
+ if self.norm_type == "ada_norm_single":
597
+ norm_hidden_states = self.norm2(hidden_states)
598
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
599
+
600
+ if self._chunk_size is not None:
601
+ # "feed_forward_chunk_size" can be used to save memory
602
+ ff_output = _chunked_feed_forward(self.ff, norm_hidden_states, self._chunk_dim, self._chunk_size)
603
+ else:
604
+ ff_output = self.ff(norm_hidden_states)
605
+
606
+ if self.norm_type == "ada_norm_zero":
607
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
608
+ elif self.norm_type == "ada_norm_single":
609
+ ff_output = gate_mlp * ff_output
610
+
611
+ hidden_states = ff_output + hidden_states
612
+ if hidden_states.ndim == 4:
613
+ hidden_states = hidden_states.squeeze(1)
614
+
615
+ return hidden_states
616
+
617
+ @torch.no_grad()
618
+ def compute_voxel_grid_mask(position, grid_resolution=8):
619
+
620
+ position = position.half()
621
+ B,N,_,H,W = position.shape
622
+ assert H%grid_resolution==0 and W%grid_resolution==0
623
+
624
+ valid_mask = (position != 1).all(dim=2, keepdim=True)
625
+ valid_mask = valid_mask.expand_as(position)
626
+ position[valid_mask==False] = 0
627
+
628
+
629
+ position = rearrange(position, 'b n c (num_h grid_h) (num_w grid_w) -> b n num_h num_w c grid_h grid_w', num_h=grid_resolution, num_w=grid_resolution)
630
+ valid_mask = rearrange(valid_mask, 'b n c (num_h grid_h) (num_w grid_w) -> b n num_h num_w c grid_h grid_w', num_h=grid_resolution, num_w=grid_resolution)
631
+
632
+ grid_position = position.sum(dim=(-2, -1))
633
+ count_masked = valid_mask.sum(dim=(-2, -1))
634
+
635
+ grid_position = grid_position / count_masked.clamp(min=1)
636
+ grid_position[count_masked<5] = 0
637
+
638
+ grid_position = grid_position.permute(0,1,4,2,3)
639
+ grid_position = rearrange(grid_position, 'b n c h w -> b n (h w) c')
640
+
641
+ grid_position_expanded_1 = grid_position.unsqueeze(2).unsqueeze(4) # 形状变为 B, N, 1, L, 1, 3
642
+ grid_position_expanded_2 = grid_position.unsqueeze(1).unsqueeze(3) # 形状变为 B, 1, N, 1, L, 3
643
+
644
+ # 计算欧氏距离
645
+ distances = torch.norm(grid_position_expanded_1 - grid_position_expanded_2, dim=-1) # 形状为 B, N, N, L, L
646
+
647
+ weights = distances
648
+ grid_distance = 1.73/grid_resolution
649
+
650
+ #weights = weights*-32
651
+ #weights = weights.clamp(min=-10000.0)
652
+
653
+ weights = weights< grid_distance
654
+
655
+ return weights
656
+
657
+ def compute_multi_resolution_mask(position_maps, grid_resolutions=[32, 16, 8]):
658
+ position_attn_mask = {}
659
+ with torch.no_grad():
660
+ for grid_resolution in grid_resolutions:
661
+ position_mask = compute_voxel_grid_mask(position_maps, grid_resolution)
662
+ position_mask = rearrange(position_mask, 'b ni nj li lj -> b (ni li) (nj lj)')
663
+ position_attn_mask[position_mask.shape[1]] = position_mask
664
+ return position_attn_mask
665
+
666
+ @torch.no_grad()
667
+ def compute_discrete_voxel_indice(position, grid_resolution=8, voxel_resolution=128):
668
+
669
+ position = position.half()
670
+ B,N,_,H,W = position.shape
671
+ assert H%grid_resolution==0 and W%grid_resolution==0
672
+
673
+ valid_mask = (position != 1).all(dim=2, keepdim=True)
674
+ valid_mask = valid_mask.expand_as(position)
675
+ position[valid_mask==False] = 0
676
+
677
+ position = rearrange(position, 'b n c (num_h grid_h) (num_w grid_w) -> b n num_h num_w c grid_h grid_w', num_h=grid_resolution, num_w=grid_resolution)
678
+ valid_mask = rearrange(valid_mask, 'b n c (num_h grid_h) (num_w grid_w) -> b n num_h num_w c grid_h grid_w', num_h=grid_resolution, num_w=grid_resolution)
679
+
680
+ grid_position = position.sum(dim=(-2, -1))
681
+ count_masked = valid_mask.sum(dim=(-2, -1))
682
+
683
+ grid_position = grid_position / count_masked.clamp(min=1)
684
+ grid_position[count_masked<5] = 0
685
+
686
+ grid_position = grid_position.permute(0,1,4,2,3).clamp(0, 1) # B N C H W
687
+ voxel_indices = grid_position * (voxel_resolution - 1)
688
+ voxel_indices = torch.round(voxel_indices).long()
689
+ return voxel_indices
690
+
691
+ def compute_multi_resolution_discrete_voxel_indice(position_maps, grid_resolutions=[64, 32, 16, 8], voxel_resolutions=[512, 256, 128, 64]):
692
+ voxel_indices = {}
693
+ with torch.no_grad():
694
+ for grid_resolution, voxel_resolution in zip(grid_resolutions, voxel_resolutions):
695
+ voxel_indice = compute_discrete_voxel_indice(position_maps, grid_resolution, voxel_resolution)
696
+ voxel_indice = rearrange(voxel_indice, 'b n c h w -> b (n h w) c')
697
+ voxel_indices[voxel_indice.shape[1]] = {'voxel_indices':voxel_indice, 'voxel_resolution':voxel_resolution}
698
+ return voxel_indices
699
+
700
+ class ImageProjModel(torch.nn.Module):
701
+ """Projection Model"""
702
+
703
+ def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
704
+ super().__init__()
705
+
706
+ self.generator = None
707
+ self.cross_attention_dim = cross_attention_dim
708
+ self.clip_extra_context_tokens = clip_extra_context_tokens
709
+ self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
710
+ self.norm = torch.nn.LayerNorm(cross_attention_dim)
711
+
712
+ def forward(self, image_embeds):
713
+ embeds = image_embeds
714
+ clip_extra_context_tokens = self.proj(embeds).reshape(
715
+ -1, self.clip_extra_context_tokens, self.cross_attention_dim
716
+ )
717
+ clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
718
+ return clip_extra_context_tokens
719
+
720
+ class UNet2p5DConditionModel(torch.nn.Module):
721
+ def __init__(self, unet: UNet2DConditionModel) -> None:
722
+ super().__init__()
723
+ self.unet = unet
724
+ self.unet_dual = copy.deepcopy(unet)
725
+
726
+ self.init_camera_embedding()
727
+ self.init_attention(self.unet, use_ipa=True, use_ma=True, use_ra=True)
728
+ self.init_attention(self.unet_dual, use_ipa=False, use_ma=False, use_ra=False)
729
+ self.init_condition()
730
+
731
+ @staticmethod
732
+ def from_pretrained(pretrained_model_name_or_path, **kwargs):
733
+ torch_dtype = kwargs.pop('torch_dtype', torch.float32)
734
+ config_path = os.path.join(pretrained_model_name_or_path, 'config.json')
735
+ unet_ckpt_path = os.path.join(pretrained_model_name_or_path, 'diffusion_pytorch_model.bin')
736
+ with open(config_path, 'r', encoding='utf-8') as file:
737
+ config = json.load(file)
738
+ unet = UNet2DConditionModel(**config)
739
+ unet = UNet2p5DConditionModel(unet)
740
+
741
+ unet.unet.conv_in = torch.nn.Conv2d(
742
+ 12,
743
+ unet.unet.conv_in.out_channels,
744
+ kernel_size=unet.unet.conv_in.kernel_size,
745
+ stride=unet.unet.conv_in.stride,
746
+ padding=unet.unet.conv_in.padding,
747
+ dilation=unet.unet.conv_in.dilation,
748
+ groups=unet.unet.conv_in.groups,
749
+ bias=unet.unet.conv_in.bias is not None)
750
+
751
+ unet_ckpt = torch.load(unet_ckpt_path, map_location='cpu', weights_only=True)
752
+ unet.load_state_dict(unet_ckpt, strict=True)
753
+ unet = unet.to(torch_dtype)
754
+ return unet
755
+
756
+ def init_condition(self):
757
+ self.unet.learned_text_clip_gen = nn.Parameter(torch.randn(1,77,1024))
758
+ self.unet.learned_text_clip_ref = nn.Parameter(torch.randn(1,77,1024))
759
+
760
+ self.unet.image_proj_model = ImageProjModel(
761
+ cross_attention_dim=self.unet.config.cross_attention_dim,
762
+ clip_embeddings_dim=1024,
763
+ )
764
+
765
+
766
+ def init_camera_embedding(self):
767
+ self.max_num_ref_image = 5
768
+ self.max_num_gen_image = 12*3+4*2
769
+
770
+ time_embed_dim = 1280
771
+ self.unet.class_embedding = nn.Embedding(self.max_num_ref_image+self.max_num_gen_image, time_embed_dim)
772
+ # 将嵌入层的权重初始化为全零
773
+ nn.init.zeros_(self.unet.class_embedding.weight)
774
+
775
+ def init_attention(self, unet, use_ipa=True, use_ma=True, use_ra=True):
776
+
777
+ for down_block_i, down_block in enumerate(unet.down_blocks):
778
+ if hasattr(down_block, "has_cross_attention") and down_block.has_cross_attention:
779
+ for attn_i, attn in enumerate(down_block.attentions):
780
+ for transformer_i, transformer in enumerate(attn.transformer_blocks):
781
+ if isinstance(transformer, BasicTransformerBlock):
782
+ attn.transformer_blocks[transformer_i] = Basic2p5DTransformerBlock(transformer, f'down_{down_block_i}_{attn_i}_{transformer_i}',use_ipa,use_ma,use_ra)
783
+
784
+ if hasattr(unet.mid_block, "has_cross_attention") and unet.mid_block.has_cross_attention:
785
+ for attn_i, attn in enumerate(unet.mid_block.attentions):
786
+ for transformer_i, transformer in enumerate(attn.transformer_blocks):
787
+ if isinstance(transformer, BasicTransformerBlock):
788
+ attn.transformer_blocks[transformer_i] = Basic2p5DTransformerBlock(transformer, f'mid_{attn_i}_{transformer_i}',use_ipa,use_ma,use_ra)
789
+
790
+ for up_block_i, up_block in enumerate(unet.up_blocks):
791
+ if hasattr(up_block, "has_cross_attention") and up_block.has_cross_attention:
792
+ for attn_i, attn in enumerate(up_block.attentions):
793
+ for transformer_i, transformer in enumerate(attn.transformer_blocks):
794
+ if isinstance(transformer, BasicTransformerBlock):
795
+ attn.transformer_blocks[transformer_i] = Basic2p5DTransformerBlock(transformer, f'up_{up_block_i}_{attn_i}_{transformer_i}',use_ipa,use_ma,use_ra)
796
+
797
+
798
+ def __getattr__(self, name: str):
799
+ try:
800
+ return super().__getattr__(name)
801
+ except AttributeError:
802
+ return getattr(self.unet, name)
803
+
804
+ def forward(
805
+ self, sample, timestep, encoder_hidden_states, class_labels=None,
806
+ *args, cross_attention_kwargs=None, down_intrablock_additional_residuals=None,
807
+ down_block_res_samples=None, mid_block_res_sample=None,
808
+ **cached_condition,
809
+ ):
810
+ B, N_gen, _, H, W = sample.shape
811
+ camera_info_gen = cached_condition['camera_info_gen'] + self.max_num_ref_image
812
+ camera_info_gen = rearrange(camera_info_gen, 'b n -> (b n)')
813
+ sample = [sample]
814
+
815
+ if 'normal_imgs' in cached_condition:
816
+ sample.append(cached_condition["normal_imgs"])
817
+ if 'position_imgs' in cached_condition:
818
+ sample.append(cached_condition["position_imgs"])
819
+
820
+ sample = torch.cat(sample, dim=2)
821
+ sample = rearrange(sample, 'b n c h w -> (b n) c h w')
822
+
823
+ encoder_hidden_states_gen = encoder_hidden_states.unsqueeze(1).repeat(1, N_gen, 1, 1)
824
+ encoder_hidden_states_gen = rearrange(encoder_hidden_states_gen, 'b n l c -> (b n) l c')
825
+
826
+
827
+ use_position_mask = False
828
+ use_position_rope = True
829
+
830
+ position_attn_mask = None
831
+ if use_position_mask:
832
+ if 'position_attn_mask' in cached_condition:
833
+ position_attn_mask = cached_condition['position_attn_mask']
834
+ else:
835
+ if 'position_maps' in cached_condition:
836
+ position_attn_mask = compute_multi_resolution_mask(cached_condition['position_maps'])
837
+
838
+ position_voxel_indices = None
839
+ if use_position_rope:
840
+ if 'position_voxel_indices' in cached_condition:
841
+ position_voxel_indices = cached_condition['position_voxel_indices']
842
+ else:
843
+ if 'position_maps' in cached_condition:
844
+ position_voxel_indices = compute_multi_resolution_discrete_voxel_indice(cached_condition['position_maps'])
845
+
846
+ if 'ip_hidden_states' in cached_condition:
847
+ ip_hidden_states = cached_condition['ip_hidden_states']
848
+ else:
849
+ if 'clip_embeds' in cached_condition:
850
+ ip_hidden_states = self.image_proj_model(cached_condition['clip_embeds'])
851
+ else:
852
+ ip_hidden_states = None
853
+ cached_condition['ip_hidden_states'] = ip_hidden_states
854
+
855
+ if 'condition_embed_dict' in cached_condition:
856
+ condition_embed_dict = cached_condition['condition_embed_dict']
857
+ else:
858
+ condition_embed_dict = {}
859
+ ref_latents = cached_condition['ref_latents']
860
+ N_ref = ref_latents.shape[1]
861
+ camera_info_ref = cached_condition['camera_info_ref']
862
+ camera_info_ref = rearrange(camera_info_ref, 'b n -> (b n)')
863
+
864
+ #ref_latents = [ref_latents]
865
+ #if 'normal_imgs' in cached_condition:
866
+ # ref_latents.append(torch.zeros_like(ref_latents[0]))
867
+ #if 'position_imgs' in cached_condition:
868
+ # ref_latents.append(torch.zeros_like(ref_latents[0]))
869
+ #ref_latents = torch.cat(ref_latents, dim=2)
870
+
871
+ ref_latents = rearrange(ref_latents, 'b n c h w -> (b n) c h w')
872
+
873
+ encoder_hidden_states_ref = self.learned_text_clip_ref.unsqueeze(1).repeat(B, N_ref, 1, 1)
874
+ encoder_hidden_states_ref = rearrange(encoder_hidden_states_ref, 'b n l c -> (b n) l c')
875
+
876
+ noisy_ref_latents = ref_latents
877
+ timestep_ref = 0
878
+ '''
879
+ if timestep.dim()>0:
880
+ timestep_ref = rearrange(timestep, '(b n) -> b n', b=B)[:,:1].repeat(1, N_ref)
881
+ timestep_ref = rearrange(timestep_ref, 'b n -> (b n)')
882
+ else:
883
+ timestep_ref = timestep
884
+ noise = torch.randn_like(noisy_ref_latents[:,:4,...])
885
+ if self.training:
886
+ noisy_ref_latents[:,:4,...] = self.train_sched.add_noise(noisy_ref_latents[:,:4,...], noise, timestep_ref)
887
+ noisy_ref_latents[:,:4,...] = self.train_sched.scale_model_input(noisy_ref_latents[:,:4,...], timestep_ref)
888
+ else:
889
+ noisy_ref_latents[:,:4,...] = self.val_sched.add_noise(noisy_ref_latents[:,:4,...], noise, timestep_ref.reshape(-1))
890
+ noisy_ref_latents[:,:4,...] = self.val_sched.scale_model_input(noisy_ref_latents[:,:4,...], timestep_ref.reshape(-1))
891
+ '''
892
+ self.unet_dual(
893
+ noisy_ref_latents, timestep_ref,
894
+ encoder_hidden_states=encoder_hidden_states_ref,
895
+ #class_labels=camera_info_ref,
896
+ # **kwargs
897
+ return_dict=False,
898
+ cross_attention_kwargs={
899
+ 'mode':'w', 'num_in_batch':N_ref,
900
+ 'condition_embed_dict':condition_embed_dict},
901
+ )
902
+ cached_condition['condition_embed_dict'] = condition_embed_dict
903
+
904
+ return self.unet(
905
+ sample, timestep,
906
+ encoder_hidden_states_gen, *args,
907
+ class_labels=camera_info_gen,
908
+ down_intrablock_additional_residuals=[
909
+ sample.to(dtype=self.unet.dtype) for sample in down_intrablock_additional_residuals
910
+ ] if down_intrablock_additional_residuals is not None else None,
911
+ down_block_additional_residuals=[
912
+ sample.to(dtype=self.unet.dtype) for sample in down_block_res_samples
913
+ ] if down_block_res_samples is not None else None,
914
+ mid_block_additional_residual=(
915
+ mid_block_res_sample.to(dtype=self.unet.dtype)
916
+ if mid_block_res_sample is not None else None
917
+ ),
918
+ return_dict=False,
919
+ cross_attention_kwargs={
920
+ 'mode':'r', 'num_in_batch':N_gen,
921
+ 'ip_hidden_states':ip_hidden_states,
922
+ 'condition_embed_dict':condition_embed_dict,
923
+ 'position_attn_mask':position_attn_mask,
924
+ 'position_voxel_indices':position_voxel_indices
925
+ },
926
+ )
hunyuan3d-paint-v2-0-turbo/vae/config.json ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_class_name": "AutoencoderKL",
3
+ "_diffusers_version": "0.10.0.dev0",
4
+ "act_fn": "silu",
5
+ "block_out_channels": [
6
+ 128,
7
+ 256,
8
+ 512,
9
+ 512
10
+ ],
11
+ "down_block_types": [
12
+ "DownEncoderBlock2D",
13
+ "DownEncoderBlock2D",
14
+ "DownEncoderBlock2D",
15
+ "DownEncoderBlock2D"
16
+ ],
17
+ "in_channels": 3,
18
+ "latent_channels": 4,
19
+ "layers_per_block": 2,
20
+ "norm_num_groups": 32,
21
+ "out_channels": 3,
22
+ "sample_size": 768,
23
+ "up_block_types": [
24
+ "UpDecoderBlock2D",
25
+ "UpDecoderBlock2D",
26
+ "UpDecoderBlock2D",
27
+ "UpDecoderBlock2D"
28
+ ]
29
+ }
hunyuan3d-paint-v2-0-turbo/vae/diffusion_pytorch_model.bin ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:1b4889b6b1d4ce7ae320a02dedaeff1780ad77d415ea0d744b476155c6377ddc
3
+ size 334707217