AdithyaSK HF Staff commited on
Commit
88051c8
·
verified ·
1 Parent(s): eb755f8

Stage Harbor release files 102001-102500

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnet_flux.py +70 -0
  2. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnet_sd3.py +68 -0
  3. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnet_sparsectrl.py +116 -0
  4. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/__init__.py +25 -0
  5. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet.py +867 -0
  6. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_flax.py +395 -0
  7. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_flux.py +509 -0
  8. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_hunyuan.py +401 -0
  9. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_sana.py +290 -0
  10. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_sd3.py +513 -0
  11. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_sparsectrl.py +785 -0
  12. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_union.py +841 -0
  13. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_xs.py +1907 -0
  14. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/multicontrolnet.py +183 -0
  15. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/multicontrolnet_union.py +196 -0
  16. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/downsampling.py +401 -0
  17. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/embeddings.py +0 -0
  18. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/embeddings_flax.py +111 -0
  19. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/lora.py +457 -0
  20. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/model_loading_utils.py +522 -0
  21. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_flax_pytorch_utils.py +135 -0
  22. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_flax_utils.py +561 -0
  23. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_outputs.py +31 -0
  24. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_pytorch_flax_utils.py +161 -0
  25. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_utils.py +1831 -0
  26. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/normalization.py +648 -0
  27. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/resnet.py +797 -0
  28. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/resnet_flax.py +124 -0
  29. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/__init__.py +32 -0
  30. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/auraflow_transformer_2d.py +564 -0
  31. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/cogvideox_transformer_3d.py +531 -0
  32. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/consisid_transformer_3d.py +789 -0
  33. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/dit_transformer_2d.py +226 -0
  34. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/dual_transformer_2d.py +156 -0
  35. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/hunyuan_transformer_2d.py +579 -0
  36. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/latte_transformer_3d.py +332 -0
  37. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/lumina_nextdit2d.py +342 -0
  38. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/pixart_transformer_2d.py +430 -0
  39. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/prior_transformer.py +384 -0
  40. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/sana_transformer.py +597 -0
  41. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/stable_audio_transformer.py +443 -0
  42. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/t5_film_transformer.py +436 -0
  43. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_2d.py +551 -0
  44. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_allegro.py +414 -0
  45. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_cogview3plus.py +375 -0
  46. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_cogview4.py +754 -0
  47. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_easyanimate.py +527 -0
  48. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_flux.py +551 -0
  49. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_hidream_image.py +922 -0
  50. tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_hunyuan_video.py +1149 -0
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnet_flux.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import List
17
+
18
+ from ..utils import deprecate, logging
19
+ from .controlnets.controlnet_flux import FluxControlNetModel, FluxControlNetOutput, FluxMultiControlNetModel
20
+
21
+
22
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
23
+
24
+
25
+ class FluxControlNetOutput(FluxControlNetOutput):
26
+ def __init__(self, *args, **kwargs):
27
+ deprecation_message = "Importing `FluxControlNetOutput` from `diffusers.models.controlnet_flux` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_flux import FluxControlNetOutput`, instead."
28
+ deprecate("diffusers.models.controlnet_flux.FluxControlNetOutput", "0.34", deprecation_message)
29
+ super().__init__(*args, **kwargs)
30
+
31
+
32
+ class FluxControlNetModel(FluxControlNetModel):
33
+ def __init__(
34
+ self,
35
+ patch_size: int = 1,
36
+ in_channels: int = 64,
37
+ num_layers: int = 19,
38
+ num_single_layers: int = 38,
39
+ attention_head_dim: int = 128,
40
+ num_attention_heads: int = 24,
41
+ joint_attention_dim: int = 4096,
42
+ pooled_projection_dim: int = 768,
43
+ guidance_embeds: bool = False,
44
+ axes_dims_rope: List[int] = [16, 56, 56],
45
+ num_mode: int = None,
46
+ conditioning_embedding_channels: int = None,
47
+ ):
48
+ deprecation_message = "Importing `FluxControlNetModel` from `diffusers.models.controlnet_flux` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_flux import FluxControlNetModel`, instead."
49
+ deprecate("diffusers.models.controlnet_flux.FluxControlNetModel", "0.34", deprecation_message)
50
+ super().__init__(
51
+ patch_size=patch_size,
52
+ in_channels=in_channels,
53
+ num_layers=num_layers,
54
+ num_single_layers=num_single_layers,
55
+ attention_head_dim=attention_head_dim,
56
+ num_attention_heads=num_attention_heads,
57
+ joint_attention_dim=joint_attention_dim,
58
+ pooled_projection_dim=pooled_projection_dim,
59
+ guidance_embeds=guidance_embeds,
60
+ axes_dims_rope=axes_dims_rope,
61
+ num_mode=num_mode,
62
+ conditioning_embedding_channels=conditioning_embedding_channels,
63
+ )
64
+
65
+
66
+ class FluxMultiControlNetModel(FluxMultiControlNetModel):
67
+ def __init__(self, *args, **kwargs):
68
+ deprecation_message = "Importing `FluxMultiControlNetModel` from `diffusers.models.controlnet_flux` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_flux import FluxMultiControlNetModel`, instead."
69
+ deprecate("diffusers.models.controlnet_flux.FluxMultiControlNetModel", "0.34", deprecation_message)
70
+ super().__init__(*args, **kwargs)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnet_sd3.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI, The HuggingFace Team and The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from ..utils import deprecate, logging
17
+ from .controlnets.controlnet_sd3 import SD3ControlNetModel, SD3ControlNetOutput, SD3MultiControlNetModel
18
+
19
+
20
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
21
+
22
+
23
+ class SD3ControlNetOutput(SD3ControlNetOutput):
24
+ def __init__(self, *args, **kwargs):
25
+ deprecation_message = "Importing `SD3ControlNetOutput` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sd3 import SD3ControlNetOutput`, instead."
26
+ deprecate("diffusers.models.controlnet_sd3.SD3ControlNetOutput", "0.34", deprecation_message)
27
+ super().__init__(*args, **kwargs)
28
+
29
+
30
+ class SD3ControlNetModel(SD3ControlNetModel):
31
+ def __init__(
32
+ self,
33
+ sample_size: int = 128,
34
+ patch_size: int = 2,
35
+ in_channels: int = 16,
36
+ num_layers: int = 18,
37
+ attention_head_dim: int = 64,
38
+ num_attention_heads: int = 18,
39
+ joint_attention_dim: int = 4096,
40
+ caption_projection_dim: int = 1152,
41
+ pooled_projection_dim: int = 2048,
42
+ out_channels: int = 16,
43
+ pos_embed_max_size: int = 96,
44
+ extra_conditioning_channels: int = 0,
45
+ ):
46
+ deprecation_message = "Importing `SD3ControlNetModel` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sd3 import SD3ControlNetModel`, instead."
47
+ deprecate("diffusers.models.controlnet_sd3.SD3ControlNetModel", "0.34", deprecation_message)
48
+ super().__init__(
49
+ sample_size=sample_size,
50
+ patch_size=patch_size,
51
+ in_channels=in_channels,
52
+ num_layers=num_layers,
53
+ attention_head_dim=attention_head_dim,
54
+ num_attention_heads=num_attention_heads,
55
+ joint_attention_dim=joint_attention_dim,
56
+ caption_projection_dim=caption_projection_dim,
57
+ pooled_projection_dim=pooled_projection_dim,
58
+ out_channels=out_channels,
59
+ pos_embed_max_size=pos_embed_max_size,
60
+ extra_conditioning_channels=extra_conditioning_channels,
61
+ )
62
+
63
+
64
+ class SD3MultiControlNetModel(SD3MultiControlNetModel):
65
+ def __init__(self, *args, **kwargs):
66
+ deprecation_message = "Importing `SD3MultiControlNetModel` from `diffusers.models.controlnet_sd3` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sd3 import SD3MultiControlNetModel`, instead."
67
+ deprecate("diffusers.models.controlnet_sd3.SD3MultiControlNetModel", "0.34", deprecation_message)
68
+ super().__init__(*args, **kwargs)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnet_sparsectrl.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Optional, Tuple, Union
17
+
18
+ from ..utils import deprecate, logging
19
+ from .controlnets.controlnet_sparsectrl import ( # noqa
20
+ SparseControlNetConditioningEmbedding,
21
+ SparseControlNetModel,
22
+ SparseControlNetOutput,
23
+ zero_module,
24
+ )
25
+
26
+
27
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
28
+
29
+
30
+ class SparseControlNetOutput(SparseControlNetOutput):
31
+ def __init__(self, *args, **kwargs):
32
+ deprecation_message = "Importing `SparseControlNetOutput` from `diffusers.models.controlnet_sparsectrl` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sparsectrl import SparseControlNetOutput`, instead."
33
+ deprecate("diffusers.models.controlnet_sparsectrl.SparseControlNetOutput", "0.34", deprecation_message)
34
+ super().__init__(*args, **kwargs)
35
+
36
+
37
+ class SparseControlNetConditioningEmbedding(SparseControlNetConditioningEmbedding):
38
+ def __init__(self, *args, **kwargs):
39
+ deprecation_message = "Importing `SparseControlNetConditioningEmbedding` from `diffusers.models.controlnet_sparsectrl` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sparsectrl import SparseControlNetConditioningEmbedding`, instead."
40
+ deprecate(
41
+ "diffusers.models.controlnet_sparsectrl.SparseControlNetConditioningEmbedding", "0.34", deprecation_message
42
+ )
43
+ super().__init__(*args, **kwargs)
44
+
45
+
46
+ class SparseControlNetModel(SparseControlNetModel):
47
+ def __init__(
48
+ self,
49
+ in_channels: int = 4,
50
+ conditioning_channels: int = 4,
51
+ flip_sin_to_cos: bool = True,
52
+ freq_shift: int = 0,
53
+ down_block_types: Tuple[str, ...] = (
54
+ "CrossAttnDownBlockMotion",
55
+ "CrossAttnDownBlockMotion",
56
+ "CrossAttnDownBlockMotion",
57
+ "DownBlockMotion",
58
+ ),
59
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
60
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
61
+ layers_per_block: int = 2,
62
+ downsample_padding: int = 1,
63
+ mid_block_scale_factor: float = 1,
64
+ act_fn: str = "silu",
65
+ norm_num_groups: Optional[int] = 32,
66
+ norm_eps: float = 1e-5,
67
+ cross_attention_dim: int = 768,
68
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
69
+ transformer_layers_per_mid_block: Optional[Union[int, Tuple[int]]] = None,
70
+ temporal_transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
71
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
72
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
73
+ use_linear_projection: bool = False,
74
+ upcast_attention: bool = False,
75
+ resnet_time_scale_shift: str = "default",
76
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
77
+ global_pool_conditions: bool = False,
78
+ controlnet_conditioning_channel_order: str = "rgb",
79
+ motion_max_seq_length: int = 32,
80
+ motion_num_attention_heads: int = 8,
81
+ concat_conditioning_mask: bool = True,
82
+ use_simplified_condition_embedding: bool = True,
83
+ ):
84
+ deprecation_message = "Importing `SparseControlNetModel` from `diffusers.models.controlnet_sparsectrl` is deprecated and this will be removed in a future version. Please use `from diffusers.models.controlnets.controlnet_sparsectrl import SparseControlNetModel`, instead."
85
+ deprecate("diffusers.models.controlnet_sparsectrl.SparseControlNetModel", "0.34", deprecation_message)
86
+ super().__init__(
87
+ in_channels=in_channels,
88
+ conditioning_channels=conditioning_channels,
89
+ flip_sin_to_cos=flip_sin_to_cos,
90
+ freq_shift=freq_shift,
91
+ down_block_types=down_block_types,
92
+ only_cross_attention=only_cross_attention,
93
+ block_out_channels=block_out_channels,
94
+ layers_per_block=layers_per_block,
95
+ downsample_padding=downsample_padding,
96
+ mid_block_scale_factor=mid_block_scale_factor,
97
+ act_fn=act_fn,
98
+ norm_num_groups=norm_num_groups,
99
+ norm_eps=norm_eps,
100
+ cross_attention_dim=cross_attention_dim,
101
+ transformer_layers_per_block=transformer_layers_per_block,
102
+ transformer_layers_per_mid_block=transformer_layers_per_mid_block,
103
+ temporal_transformer_layers_per_block=temporal_transformer_layers_per_block,
104
+ attention_head_dim=attention_head_dim,
105
+ num_attention_heads=num_attention_heads,
106
+ use_linear_projection=use_linear_projection,
107
+ upcast_attention=upcast_attention,
108
+ resnet_time_scale_shift=resnet_time_scale_shift,
109
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
110
+ global_pool_conditions=global_pool_conditions,
111
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
112
+ motion_max_seq_length=motion_max_seq_length,
113
+ motion_num_attention_heads=motion_num_attention_heads,
114
+ concat_conditioning_mask=concat_conditioning_mask,
115
+ use_simplified_condition_embedding=use_simplified_condition_embedding,
116
+ )
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/__init__.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ...utils import is_flax_available, is_torch_available
2
+
3
+
4
+ if is_torch_available():
5
+ from .controlnet import ControlNetModel, ControlNetOutput
6
+ from .controlnet_flux import FluxControlNetModel, FluxControlNetOutput, FluxMultiControlNetModel
7
+ from .controlnet_hunyuan import (
8
+ HunyuanControlNetOutput,
9
+ HunyuanDiT2DControlNetModel,
10
+ HunyuanDiT2DMultiControlNetModel,
11
+ )
12
+ from .controlnet_sana import SanaControlNetModel
13
+ from .controlnet_sd3 import SD3ControlNetModel, SD3ControlNetOutput, SD3MultiControlNetModel
14
+ from .controlnet_sparsectrl import (
15
+ SparseControlNetConditioningEmbedding,
16
+ SparseControlNetModel,
17
+ SparseControlNetOutput,
18
+ )
19
+ from .controlnet_union import ControlNetUnionModel
20
+ from .controlnet_xs import ControlNetXSAdapter, ControlNetXSOutput, UNetControlNetXSModel
21
+ from .multicontrolnet import MultiControlNetModel
22
+ from .multicontrolnet_union import MultiControlNetUnionModel
23
+
24
+ if is_flax_available():
25
+ from .controlnet_flax import FlaxControlNetModel
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet.py ADDED
@@ -0,0 +1,867 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ from torch import nn
19
+ from torch.nn import functional as F
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...loaders.single_file_model import FromOriginalModelMixin
23
+ from ...utils import BaseOutput, logging
24
+ from ..attention_processor import (
25
+ ADDED_KV_ATTENTION_PROCESSORS,
26
+ CROSS_ATTENTION_PROCESSORS,
27
+ AttentionProcessor,
28
+ AttnAddedKVProcessor,
29
+ AttnProcessor,
30
+ )
31
+ from ..embeddings import TextImageProjection, TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps
32
+ from ..modeling_utils import ModelMixin
33
+ from ..unets.unet_2d_blocks import (
34
+ UNetMidBlock2D,
35
+ UNetMidBlock2DCrossAttn,
36
+ get_down_block,
37
+ )
38
+ from ..unets.unet_2d_condition import UNet2DConditionModel
39
+
40
+
41
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
42
+
43
+
44
+ @dataclass
45
+ class ControlNetOutput(BaseOutput):
46
+ """
47
+ The output of [`ControlNetModel`].
48
+
49
+ Args:
50
+ down_block_res_samples (`tuple[torch.Tensor]`):
51
+ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
52
+ be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
53
+ used to condition the original UNet's downsampling activations.
54
+ mid_down_block_re_sample (`torch.Tensor`):
55
+ The activation of the middle block (the lowest sample resolution). Each tensor should be of shape
56
+ `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
57
+ Output can be used to condition the original UNet's middle block activation.
58
+ """
59
+
60
+ down_block_res_samples: Tuple[torch.Tensor]
61
+ mid_block_res_sample: torch.Tensor
62
+
63
+
64
+ class ControlNetConditioningEmbedding(nn.Module):
65
+ """
66
+ Quoting from https://arxiv.org/abs/2302.05543: "Stable Diffusion uses a pre-processing method similar to VQ-GAN
67
+ [11] to convert the entire dataset of 512 × 512 images into smaller 64 × 64 “latent images” for stabilized
68
+ training. This requires ControlNets to convert image-based conditions to 64 × 64 feature space to match the
69
+ convolution size. We use a tiny network E(·) of four convolution layers with 4 × 4 kernels and 2 × 2 strides
70
+ (activated by ReLU, channels are 16, 32, 64, 128, initialized with Gaussian weights, trained jointly with the full
71
+ model) to encode image-space conditions ... into feature maps ..."
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ conditioning_embedding_channels: int,
77
+ conditioning_channels: int = 3,
78
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
79
+ ):
80
+ super().__init__()
81
+
82
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
83
+
84
+ self.blocks = nn.ModuleList([])
85
+
86
+ for i in range(len(block_out_channels) - 1):
87
+ channel_in = block_out_channels[i]
88
+ channel_out = block_out_channels[i + 1]
89
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
90
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
91
+
92
+ self.conv_out = zero_module(
93
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
94
+ )
95
+
96
+ def forward(self, conditioning):
97
+ embedding = self.conv_in(conditioning)
98
+ embedding = F.silu(embedding)
99
+
100
+ for block in self.blocks:
101
+ embedding = block(embedding)
102
+ embedding = F.silu(embedding)
103
+
104
+ embedding = self.conv_out(embedding)
105
+
106
+ return embedding
107
+
108
+
109
+ class ControlNetModel(ModelMixin, ConfigMixin, FromOriginalModelMixin):
110
+ """
111
+ A ControlNet model.
112
+
113
+ Args:
114
+ in_channels (`int`, defaults to 4):
115
+ The number of channels in the input sample.
116
+ flip_sin_to_cos (`bool`, defaults to `True`):
117
+ Whether to flip the sin to cos in the time embedding.
118
+ freq_shift (`int`, defaults to 0):
119
+ The frequency shift to apply to the time embedding.
120
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
121
+ The tuple of downsample blocks to use.
122
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
123
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
124
+ The tuple of output channels for each block.
125
+ layers_per_block (`int`, defaults to 2):
126
+ The number of layers per block.
127
+ downsample_padding (`int`, defaults to 1):
128
+ The padding to use for the downsampling convolution.
129
+ mid_block_scale_factor (`float`, defaults to 1):
130
+ The scale factor to use for the mid block.
131
+ act_fn (`str`, defaults to "silu"):
132
+ The activation function to use.
133
+ norm_num_groups (`int`, *optional*, defaults to 32):
134
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
135
+ in post-processing.
136
+ norm_eps (`float`, defaults to 1e-5):
137
+ The epsilon to use for the normalization.
138
+ cross_attention_dim (`int`, defaults to 1280):
139
+ The dimension of the cross attention features.
140
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
141
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
142
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
143
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
144
+ encoder_hid_dim (`int`, *optional*, defaults to None):
145
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
146
+ dimension to `cross_attention_dim`.
147
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
148
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
149
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
150
+ attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
151
+ The dimension of the attention heads.
152
+ use_linear_projection (`bool`, defaults to `False`):
153
+ class_embed_type (`str`, *optional*, defaults to `None`):
154
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
155
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
156
+ addition_embed_type (`str`, *optional*, defaults to `None`):
157
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
158
+ "text". "text" will use the `TextTimeEmbedding` layer.
159
+ num_class_embeds (`int`, *optional*, defaults to 0):
160
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
161
+ class conditioning with `class_embed_type` equal to `None`.
162
+ upcast_attention (`bool`, defaults to `False`):
163
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
164
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
165
+ projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
166
+ The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
167
+ `class_embed_type="projection"`.
168
+ controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
169
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
170
+ conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(16, 32, 96, 256)`):
171
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
172
+ global_pool_conditions (`bool`, defaults to `False`):
173
+ TODO(Patrick) - unused parameter.
174
+ addition_embed_type_num_heads (`int`, defaults to 64):
175
+ The number of heads to use for the `TextTimeEmbedding` layer.
176
+ """
177
+
178
+ _supports_gradient_checkpointing = True
179
+
180
+ @register_to_config
181
+ def __init__(
182
+ self,
183
+ in_channels: int = 4,
184
+ conditioning_channels: int = 3,
185
+ flip_sin_to_cos: bool = True,
186
+ freq_shift: int = 0,
187
+ down_block_types: Tuple[str, ...] = (
188
+ "CrossAttnDownBlock2D",
189
+ "CrossAttnDownBlock2D",
190
+ "CrossAttnDownBlock2D",
191
+ "DownBlock2D",
192
+ ),
193
+ mid_block_type: Optional[str] = "UNetMidBlock2DCrossAttn",
194
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
195
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
196
+ layers_per_block: int = 2,
197
+ downsample_padding: int = 1,
198
+ mid_block_scale_factor: float = 1,
199
+ act_fn: str = "silu",
200
+ norm_num_groups: Optional[int] = 32,
201
+ norm_eps: float = 1e-5,
202
+ cross_attention_dim: int = 1280,
203
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
204
+ encoder_hid_dim: Optional[int] = None,
205
+ encoder_hid_dim_type: Optional[str] = None,
206
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
207
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
208
+ use_linear_projection: bool = False,
209
+ class_embed_type: Optional[str] = None,
210
+ addition_embed_type: Optional[str] = None,
211
+ addition_time_embed_dim: Optional[int] = None,
212
+ num_class_embeds: Optional[int] = None,
213
+ upcast_attention: bool = False,
214
+ resnet_time_scale_shift: str = "default",
215
+ projection_class_embeddings_input_dim: Optional[int] = None,
216
+ controlnet_conditioning_channel_order: str = "rgb",
217
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
218
+ global_pool_conditions: bool = False,
219
+ addition_embed_type_num_heads: int = 64,
220
+ ):
221
+ super().__init__()
222
+
223
+ # If `num_attention_heads` is not defined (which is the case for most models)
224
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
225
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
226
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
227
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
228
+ # which is why we correct for the naming here.
229
+ num_attention_heads = num_attention_heads or attention_head_dim
230
+
231
+ # Check inputs
232
+ if len(block_out_channels) != len(down_block_types):
233
+ raise ValueError(
234
+ 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}."
235
+ )
236
+
237
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
238
+ raise ValueError(
239
+ 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}."
240
+ )
241
+
242
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
243
+ raise ValueError(
244
+ 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}."
245
+ )
246
+
247
+ if isinstance(transformer_layers_per_block, int):
248
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
249
+
250
+ # input
251
+ conv_in_kernel = 3
252
+ conv_in_padding = (conv_in_kernel - 1) // 2
253
+ self.conv_in = nn.Conv2d(
254
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
255
+ )
256
+
257
+ # time
258
+ time_embed_dim = block_out_channels[0] * 4
259
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
260
+ timestep_input_dim = block_out_channels[0]
261
+ self.time_embedding = TimestepEmbedding(
262
+ timestep_input_dim,
263
+ time_embed_dim,
264
+ act_fn=act_fn,
265
+ )
266
+
267
+ if encoder_hid_dim_type is None and encoder_hid_dim is not None:
268
+ encoder_hid_dim_type = "text_proj"
269
+ self.register_to_config(encoder_hid_dim_type=encoder_hid_dim_type)
270
+ logger.info("encoder_hid_dim_type defaults to 'text_proj' as `encoder_hid_dim` is defined.")
271
+
272
+ if encoder_hid_dim is None and encoder_hid_dim_type is not None:
273
+ raise ValueError(
274
+ f"`encoder_hid_dim` has to be defined when `encoder_hid_dim_type` is set to {encoder_hid_dim_type}."
275
+ )
276
+
277
+ if encoder_hid_dim_type == "text_proj":
278
+ self.encoder_hid_proj = nn.Linear(encoder_hid_dim, cross_attention_dim)
279
+ elif encoder_hid_dim_type == "text_image_proj":
280
+ # image_embed_dim DOESN'T have to be `cross_attention_dim`. To not clutter the __init__ too much
281
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
282
+ # case when `addition_embed_type == "text_image_proj"` (Kandinsky 2.1)`
283
+ self.encoder_hid_proj = TextImageProjection(
284
+ text_embed_dim=encoder_hid_dim,
285
+ image_embed_dim=cross_attention_dim,
286
+ cross_attention_dim=cross_attention_dim,
287
+ )
288
+
289
+ elif encoder_hid_dim_type is not None:
290
+ raise ValueError(
291
+ f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None, 'text_proj' or 'text_image_proj'."
292
+ )
293
+ else:
294
+ self.encoder_hid_proj = None
295
+
296
+ # class embedding
297
+ if class_embed_type is None and num_class_embeds is not None:
298
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
299
+ elif class_embed_type == "timestep":
300
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
301
+ elif class_embed_type == "identity":
302
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
303
+ elif class_embed_type == "projection":
304
+ if projection_class_embeddings_input_dim is None:
305
+ raise ValueError(
306
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
307
+ )
308
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
309
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
310
+ # 2. it projects from an arbitrary input dimension.
311
+ #
312
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
313
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
314
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
315
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
316
+ else:
317
+ self.class_embedding = None
318
+
319
+ if addition_embed_type == "text":
320
+ if encoder_hid_dim is not None:
321
+ text_time_embedding_from_dim = encoder_hid_dim
322
+ else:
323
+ text_time_embedding_from_dim = cross_attention_dim
324
+
325
+ self.add_embedding = TextTimeEmbedding(
326
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
327
+ )
328
+ elif addition_embed_type == "text_image":
329
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
330
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
331
+ # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
332
+ self.add_embedding = TextImageTimeEmbedding(
333
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
334
+ )
335
+ elif addition_embed_type == "text_time":
336
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
337
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
338
+
339
+ elif addition_embed_type is not None:
340
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
341
+
342
+ # control net conditioning embedding
343
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
344
+ conditioning_embedding_channels=block_out_channels[0],
345
+ block_out_channels=conditioning_embedding_out_channels,
346
+ conditioning_channels=conditioning_channels,
347
+ )
348
+
349
+ self.down_blocks = nn.ModuleList([])
350
+ self.controlnet_down_blocks = nn.ModuleList([])
351
+
352
+ if isinstance(only_cross_attention, bool):
353
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
354
+
355
+ if isinstance(attention_head_dim, int):
356
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
357
+
358
+ if isinstance(num_attention_heads, int):
359
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
360
+
361
+ # down
362
+ output_channel = block_out_channels[0]
363
+
364
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
365
+ controlnet_block = zero_module(controlnet_block)
366
+ self.controlnet_down_blocks.append(controlnet_block)
367
+
368
+ for i, down_block_type in enumerate(down_block_types):
369
+ input_channel = output_channel
370
+ output_channel = block_out_channels[i]
371
+ is_final_block = i == len(block_out_channels) - 1
372
+
373
+ down_block = get_down_block(
374
+ down_block_type,
375
+ num_layers=layers_per_block,
376
+ transformer_layers_per_block=transformer_layers_per_block[i],
377
+ in_channels=input_channel,
378
+ out_channels=output_channel,
379
+ temb_channels=time_embed_dim,
380
+ add_downsample=not is_final_block,
381
+ resnet_eps=norm_eps,
382
+ resnet_act_fn=act_fn,
383
+ resnet_groups=norm_num_groups,
384
+ cross_attention_dim=cross_attention_dim,
385
+ num_attention_heads=num_attention_heads[i],
386
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
387
+ downsample_padding=downsample_padding,
388
+ use_linear_projection=use_linear_projection,
389
+ only_cross_attention=only_cross_attention[i],
390
+ upcast_attention=upcast_attention,
391
+ resnet_time_scale_shift=resnet_time_scale_shift,
392
+ )
393
+ self.down_blocks.append(down_block)
394
+
395
+ for _ in range(layers_per_block):
396
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
397
+ controlnet_block = zero_module(controlnet_block)
398
+ self.controlnet_down_blocks.append(controlnet_block)
399
+
400
+ if not is_final_block:
401
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
402
+ controlnet_block = zero_module(controlnet_block)
403
+ self.controlnet_down_blocks.append(controlnet_block)
404
+
405
+ # mid
406
+ mid_block_channel = block_out_channels[-1]
407
+
408
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
409
+ controlnet_block = zero_module(controlnet_block)
410
+ self.controlnet_mid_block = controlnet_block
411
+
412
+ if mid_block_type == "UNetMidBlock2DCrossAttn":
413
+ self.mid_block = UNetMidBlock2DCrossAttn(
414
+ transformer_layers_per_block=transformer_layers_per_block[-1],
415
+ in_channels=mid_block_channel,
416
+ temb_channels=time_embed_dim,
417
+ resnet_eps=norm_eps,
418
+ resnet_act_fn=act_fn,
419
+ output_scale_factor=mid_block_scale_factor,
420
+ resnet_time_scale_shift=resnet_time_scale_shift,
421
+ cross_attention_dim=cross_attention_dim,
422
+ num_attention_heads=num_attention_heads[-1],
423
+ resnet_groups=norm_num_groups,
424
+ use_linear_projection=use_linear_projection,
425
+ upcast_attention=upcast_attention,
426
+ )
427
+ elif mid_block_type == "UNetMidBlock2D":
428
+ self.mid_block = UNetMidBlock2D(
429
+ in_channels=block_out_channels[-1],
430
+ temb_channels=time_embed_dim,
431
+ num_layers=0,
432
+ resnet_eps=norm_eps,
433
+ resnet_act_fn=act_fn,
434
+ output_scale_factor=mid_block_scale_factor,
435
+ resnet_groups=norm_num_groups,
436
+ resnet_time_scale_shift=resnet_time_scale_shift,
437
+ add_attention=False,
438
+ )
439
+ else:
440
+ raise ValueError(f"unknown mid_block_type : {mid_block_type}")
441
+
442
+ @classmethod
443
+ def from_unet(
444
+ cls,
445
+ unet: UNet2DConditionModel,
446
+ controlnet_conditioning_channel_order: str = "rgb",
447
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
448
+ load_weights_from_unet: bool = True,
449
+ conditioning_channels: int = 3,
450
+ ):
451
+ r"""
452
+ Instantiate a [`ControlNetModel`] from [`UNet2DConditionModel`].
453
+
454
+ Parameters:
455
+ unet (`UNet2DConditionModel`):
456
+ The UNet model weights to copy to the [`ControlNetModel`]. All configuration options are also copied
457
+ where applicable.
458
+ """
459
+ transformer_layers_per_block = (
460
+ unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
461
+ )
462
+ encoder_hid_dim = unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
463
+ encoder_hid_dim_type = unet.config.encoder_hid_dim_type if "encoder_hid_dim_type" in unet.config else None
464
+ addition_embed_type = unet.config.addition_embed_type if "addition_embed_type" in unet.config else None
465
+ addition_time_embed_dim = (
466
+ unet.config.addition_time_embed_dim if "addition_time_embed_dim" in unet.config else None
467
+ )
468
+
469
+ controlnet = cls(
470
+ encoder_hid_dim=encoder_hid_dim,
471
+ encoder_hid_dim_type=encoder_hid_dim_type,
472
+ addition_embed_type=addition_embed_type,
473
+ addition_time_embed_dim=addition_time_embed_dim,
474
+ transformer_layers_per_block=transformer_layers_per_block,
475
+ in_channels=unet.config.in_channels,
476
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
477
+ freq_shift=unet.config.freq_shift,
478
+ down_block_types=unet.config.down_block_types,
479
+ only_cross_attention=unet.config.only_cross_attention,
480
+ block_out_channels=unet.config.block_out_channels,
481
+ layers_per_block=unet.config.layers_per_block,
482
+ downsample_padding=unet.config.downsample_padding,
483
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
484
+ act_fn=unet.config.act_fn,
485
+ norm_num_groups=unet.config.norm_num_groups,
486
+ norm_eps=unet.config.norm_eps,
487
+ cross_attention_dim=unet.config.cross_attention_dim,
488
+ attention_head_dim=unet.config.attention_head_dim,
489
+ num_attention_heads=unet.config.num_attention_heads,
490
+ use_linear_projection=unet.config.use_linear_projection,
491
+ class_embed_type=unet.config.class_embed_type,
492
+ num_class_embeds=unet.config.num_class_embeds,
493
+ upcast_attention=unet.config.upcast_attention,
494
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
495
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
496
+ mid_block_type=unet.config.mid_block_type,
497
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
498
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
499
+ conditioning_channels=conditioning_channels,
500
+ )
501
+
502
+ if load_weights_from_unet:
503
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
504
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
505
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
506
+
507
+ if controlnet.class_embedding:
508
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
509
+
510
+ if hasattr(controlnet, "add_embedding"):
511
+ controlnet.add_embedding.load_state_dict(unet.add_embedding.state_dict())
512
+
513
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict())
514
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict())
515
+
516
+ return controlnet
517
+
518
+ @property
519
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
520
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
521
+ r"""
522
+ Returns:
523
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
524
+ indexed by its weight name.
525
+ """
526
+ # set recursively
527
+ processors = {}
528
+
529
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
530
+ if hasattr(module, "get_processor"):
531
+ processors[f"{name}.processor"] = module.get_processor()
532
+
533
+ for sub_name, child in module.named_children():
534
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
535
+
536
+ return processors
537
+
538
+ for name, module in self.named_children():
539
+ fn_recursive_add_processors(name, module, processors)
540
+
541
+ return processors
542
+
543
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
544
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
545
+ r"""
546
+ Sets the attention processor to use to compute attention.
547
+
548
+ Parameters:
549
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
550
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
551
+ for **all** `Attention` layers.
552
+
553
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
554
+ processor. This is strongly recommended when setting trainable attention processors.
555
+
556
+ """
557
+ count = len(self.attn_processors.keys())
558
+
559
+ if isinstance(processor, dict) and len(processor) != count:
560
+ raise ValueError(
561
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
562
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
563
+ )
564
+
565
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
566
+ if hasattr(module, "set_processor"):
567
+ if not isinstance(processor, dict):
568
+ module.set_processor(processor)
569
+ else:
570
+ module.set_processor(processor.pop(f"{name}.processor"))
571
+
572
+ for sub_name, child in module.named_children():
573
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
574
+
575
+ for name, module in self.named_children():
576
+ fn_recursive_attn_processor(name, module, processor)
577
+
578
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
579
+ def set_default_attn_processor(self):
580
+ """
581
+ Disables custom attention processors and sets the default attention implementation.
582
+ """
583
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
584
+ processor = AttnAddedKVProcessor()
585
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
586
+ processor = AttnProcessor()
587
+ else:
588
+ raise ValueError(
589
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
590
+ )
591
+
592
+ self.set_attn_processor(processor)
593
+
594
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
595
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
596
+ r"""
597
+ Enable sliced attention computation.
598
+
599
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
600
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
601
+
602
+ Args:
603
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
604
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
605
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
606
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
607
+ must be a multiple of `slice_size`.
608
+ """
609
+ sliceable_head_dims = []
610
+
611
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
612
+ if hasattr(module, "set_attention_slice"):
613
+ sliceable_head_dims.append(module.sliceable_head_dim)
614
+
615
+ for child in module.children():
616
+ fn_recursive_retrieve_sliceable_dims(child)
617
+
618
+ # retrieve number of attention layers
619
+ for module in self.children():
620
+ fn_recursive_retrieve_sliceable_dims(module)
621
+
622
+ num_sliceable_layers = len(sliceable_head_dims)
623
+
624
+ if slice_size == "auto":
625
+ # half the attention head size is usually a good trade-off between
626
+ # speed and memory
627
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
628
+ elif slice_size == "max":
629
+ # make smallest slice possible
630
+ slice_size = num_sliceable_layers * [1]
631
+
632
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
633
+
634
+ if len(slice_size) != len(sliceable_head_dims):
635
+ raise ValueError(
636
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
637
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
638
+ )
639
+
640
+ for i in range(len(slice_size)):
641
+ size = slice_size[i]
642
+ dim = sliceable_head_dims[i]
643
+ if size is not None and size > dim:
644
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
645
+
646
+ # Recursively walk through all the children.
647
+ # Any children which exposes the set_attention_slice method
648
+ # gets the message
649
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
650
+ if hasattr(module, "set_attention_slice"):
651
+ module.set_attention_slice(slice_size.pop())
652
+
653
+ for child in module.children():
654
+ fn_recursive_set_attention_slice(child, slice_size)
655
+
656
+ reversed_slice_size = list(reversed(slice_size))
657
+ for module in self.children():
658
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
659
+
660
+ def forward(
661
+ self,
662
+ sample: torch.Tensor,
663
+ timestep: Union[torch.Tensor, float, int],
664
+ encoder_hidden_states: torch.Tensor,
665
+ controlnet_cond: torch.Tensor,
666
+ conditioning_scale: float = 1.0,
667
+ class_labels: Optional[torch.Tensor] = None,
668
+ timestep_cond: Optional[torch.Tensor] = None,
669
+ attention_mask: Optional[torch.Tensor] = None,
670
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
671
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
672
+ guess_mode: bool = False,
673
+ return_dict: bool = True,
674
+ ) -> Union[ControlNetOutput, Tuple[Tuple[torch.Tensor, ...], torch.Tensor]]:
675
+ """
676
+ The [`ControlNetModel`] forward method.
677
+
678
+ Args:
679
+ sample (`torch.Tensor`):
680
+ The noisy input tensor.
681
+ timestep (`Union[torch.Tensor, float, int]`):
682
+ The number of timesteps to denoise an input.
683
+ encoder_hidden_states (`torch.Tensor`):
684
+ The encoder hidden states.
685
+ controlnet_cond (`torch.Tensor`):
686
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
687
+ conditioning_scale (`float`, defaults to `1.0`):
688
+ The scale factor for ControlNet outputs.
689
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
690
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
691
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
692
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
693
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
694
+ embeddings.
695
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
696
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
697
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
698
+ negative values to the attention scores corresponding to "discard" tokens.
699
+ added_cond_kwargs (`dict`):
700
+ Additional conditions for the Stable Diffusion XL UNet.
701
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
702
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
703
+ guess_mode (`bool`, defaults to `False`):
704
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
705
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
706
+ return_dict (`bool`, defaults to `True`):
707
+ Whether or not to return a [`~models.controlnets.controlnet.ControlNetOutput`] instead of a plain
708
+ tuple.
709
+
710
+ Returns:
711
+ [`~models.controlnets.controlnet.ControlNetOutput`] **or** `tuple`:
712
+ If `return_dict` is `True`, a [`~models.controlnets.controlnet.ControlNetOutput`] is returned,
713
+ otherwise a tuple is returned where the first element is the sample tensor.
714
+ """
715
+ # check channel order
716
+ channel_order = self.config.controlnet_conditioning_channel_order
717
+
718
+ if channel_order == "rgb":
719
+ # in rgb order by default
720
+ ...
721
+ elif channel_order == "bgr":
722
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
723
+ else:
724
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
725
+
726
+ # prepare attention_mask
727
+ if attention_mask is not None:
728
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
729
+ attention_mask = attention_mask.unsqueeze(1)
730
+
731
+ # 1. time
732
+ timesteps = timestep
733
+ if not torch.is_tensor(timesteps):
734
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
735
+ # This would be a good case for the `match` statement (Python 3.10+)
736
+ is_mps = sample.device.type == "mps"
737
+ is_npu = sample.device.type == "npu"
738
+ if isinstance(timestep, float):
739
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
740
+ else:
741
+ dtype = torch.int32 if (is_mps or is_npu) else torch.int64
742
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
743
+ elif len(timesteps.shape) == 0:
744
+ timesteps = timesteps[None].to(sample.device)
745
+
746
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
747
+ timesteps = timesteps.expand(sample.shape[0])
748
+
749
+ t_emb = self.time_proj(timesteps)
750
+
751
+ # timesteps does not contain any weights and will always return f32 tensors
752
+ # but time_embedding might actually be running in fp16. so we need to cast here.
753
+ # there might be better ways to encapsulate this.
754
+ t_emb = t_emb.to(dtype=sample.dtype)
755
+
756
+ emb = self.time_embedding(t_emb, timestep_cond)
757
+ aug_emb = None
758
+
759
+ if self.class_embedding is not None:
760
+ if class_labels is None:
761
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
762
+
763
+ if self.config.class_embed_type == "timestep":
764
+ class_labels = self.time_proj(class_labels)
765
+
766
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
767
+ emb = emb + class_emb
768
+
769
+ if self.config.addition_embed_type is not None:
770
+ if self.config.addition_embed_type == "text":
771
+ aug_emb = self.add_embedding(encoder_hidden_states)
772
+
773
+ elif self.config.addition_embed_type == "text_time":
774
+ if "text_embeds" not in added_cond_kwargs:
775
+ raise ValueError(
776
+ 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`"
777
+ )
778
+ text_embeds = added_cond_kwargs.get("text_embeds")
779
+ if "time_ids" not in added_cond_kwargs:
780
+ raise ValueError(
781
+ 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`"
782
+ )
783
+ time_ids = added_cond_kwargs.get("time_ids")
784
+ time_embeds = self.add_time_proj(time_ids.flatten())
785
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
786
+
787
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
788
+ add_embeds = add_embeds.to(emb.dtype)
789
+ aug_emb = self.add_embedding(add_embeds)
790
+
791
+ emb = emb + aug_emb if aug_emb is not None else emb
792
+
793
+ # 2. pre-process
794
+ sample = self.conv_in(sample)
795
+
796
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
797
+ sample = sample + controlnet_cond
798
+
799
+ # 3. down
800
+ down_block_res_samples = (sample,)
801
+ for downsample_block in self.down_blocks:
802
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
803
+ sample, res_samples = downsample_block(
804
+ hidden_states=sample,
805
+ temb=emb,
806
+ encoder_hidden_states=encoder_hidden_states,
807
+ attention_mask=attention_mask,
808
+ cross_attention_kwargs=cross_attention_kwargs,
809
+ )
810
+ else:
811
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
812
+
813
+ down_block_res_samples += res_samples
814
+
815
+ # 4. mid
816
+ if self.mid_block is not None:
817
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
818
+ sample = self.mid_block(
819
+ sample,
820
+ emb,
821
+ encoder_hidden_states=encoder_hidden_states,
822
+ attention_mask=attention_mask,
823
+ cross_attention_kwargs=cross_attention_kwargs,
824
+ )
825
+ else:
826
+ sample = self.mid_block(sample, emb)
827
+
828
+ # 5. Control net blocks
829
+
830
+ controlnet_down_block_res_samples = ()
831
+
832
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
833
+ down_block_res_sample = controlnet_block(down_block_res_sample)
834
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
835
+
836
+ down_block_res_samples = controlnet_down_block_res_samples
837
+
838
+ mid_block_res_sample = self.controlnet_mid_block(sample)
839
+
840
+ # 6. scaling
841
+ if guess_mode and not self.config.global_pool_conditions:
842
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
843
+ scales = scales * conditioning_scale
844
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
845
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
846
+ else:
847
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
848
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale
849
+
850
+ if self.config.global_pool_conditions:
851
+ down_block_res_samples = [
852
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
853
+ ]
854
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
855
+
856
+ if not return_dict:
857
+ return (down_block_res_samples, mid_block_res_sample)
858
+
859
+ return ControlNetOutput(
860
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
861
+ )
862
+
863
+
864
+ def zero_module(module):
865
+ for p in module.parameters():
866
+ nn.init.zeros_(p)
867
+ return module
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_flax.py ADDED
@@ -0,0 +1,395 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Optional, Tuple, Union
15
+
16
+ import flax
17
+ import flax.linen as nn
18
+ import jax
19
+ import jax.numpy as jnp
20
+ from flax.core.frozen_dict import FrozenDict
21
+
22
+ from ...configuration_utils import ConfigMixin, flax_register_to_config
23
+ from ...utils import BaseOutput
24
+ from ..embeddings_flax import FlaxTimestepEmbedding, FlaxTimesteps
25
+ from ..modeling_flax_utils import FlaxModelMixin
26
+ from ..unets.unet_2d_blocks_flax import (
27
+ FlaxCrossAttnDownBlock2D,
28
+ FlaxDownBlock2D,
29
+ FlaxUNetMidBlock2DCrossAttn,
30
+ )
31
+
32
+
33
+ @flax.struct.dataclass
34
+ class FlaxControlNetOutput(BaseOutput):
35
+ """
36
+ The output of [`FlaxControlNetModel`].
37
+
38
+ Args:
39
+ down_block_res_samples (`jnp.ndarray`):
40
+ mid_block_res_sample (`jnp.ndarray`):
41
+ """
42
+
43
+ down_block_res_samples: jnp.ndarray
44
+ mid_block_res_sample: jnp.ndarray
45
+
46
+
47
+ class FlaxControlNetConditioningEmbedding(nn.Module):
48
+ conditioning_embedding_channels: int
49
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
50
+ dtype: jnp.dtype = jnp.float32
51
+
52
+ def setup(self) -> None:
53
+ self.conv_in = nn.Conv(
54
+ self.block_out_channels[0],
55
+ kernel_size=(3, 3),
56
+ padding=((1, 1), (1, 1)),
57
+ dtype=self.dtype,
58
+ )
59
+
60
+ blocks = []
61
+ for i in range(len(self.block_out_channels) - 1):
62
+ channel_in = self.block_out_channels[i]
63
+ channel_out = self.block_out_channels[i + 1]
64
+ conv1 = nn.Conv(
65
+ channel_in,
66
+ kernel_size=(3, 3),
67
+ padding=((1, 1), (1, 1)),
68
+ dtype=self.dtype,
69
+ )
70
+ blocks.append(conv1)
71
+ conv2 = nn.Conv(
72
+ channel_out,
73
+ kernel_size=(3, 3),
74
+ strides=(2, 2),
75
+ padding=((1, 1), (1, 1)),
76
+ dtype=self.dtype,
77
+ )
78
+ blocks.append(conv2)
79
+ self.blocks = blocks
80
+
81
+ self.conv_out = nn.Conv(
82
+ self.conditioning_embedding_channels,
83
+ kernel_size=(3, 3),
84
+ padding=((1, 1), (1, 1)),
85
+ kernel_init=nn.initializers.zeros_init(),
86
+ bias_init=nn.initializers.zeros_init(),
87
+ dtype=self.dtype,
88
+ )
89
+
90
+ def __call__(self, conditioning: jnp.ndarray) -> jnp.ndarray:
91
+ embedding = self.conv_in(conditioning)
92
+ embedding = nn.silu(embedding)
93
+
94
+ for block in self.blocks:
95
+ embedding = block(embedding)
96
+ embedding = nn.silu(embedding)
97
+
98
+ embedding = self.conv_out(embedding)
99
+
100
+ return embedding
101
+
102
+
103
+ @flax_register_to_config
104
+ class FlaxControlNetModel(nn.Module, FlaxModelMixin, ConfigMixin):
105
+ r"""
106
+ A ControlNet model.
107
+
108
+ This model inherits from [`FlaxModelMixin`]. Check the superclass documentation for it’s generic methods
109
+ implemented for all models (such as downloading or saving).
110
+
111
+ This model is also a Flax Linen [`flax.linen.Module`](https://flax.readthedocs.io/en/latest/flax.linen.html#module)
112
+ subclass. Use it as a regular Flax Linen module and refer to the Flax documentation for all matters related to its
113
+ general usage and behavior.
114
+
115
+ Inherent JAX features such as the following are supported:
116
+
117
+ - [Just-In-Time (JIT) compilation](https://jax.readthedocs.io/en/latest/jax.html#just-in-time-compilation-jit)
118
+ - [Automatic Differentiation](https://jax.readthedocs.io/en/latest/jax.html#automatic-differentiation)
119
+ - [Vectorization](https://jax.readthedocs.io/en/latest/jax.html#vectorization-vmap)
120
+ - [Parallelization](https://jax.readthedocs.io/en/latest/jax.html#parallelization-pmap)
121
+
122
+ Parameters:
123
+ sample_size (`int`, *optional*):
124
+ The size of the input sample.
125
+ in_channels (`int`, *optional*, defaults to 4):
126
+ The number of channels in the input sample.
127
+ down_block_types (`Tuple[str]`, *optional*, defaults to `("FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxCrossAttnDownBlock2D", "FlaxDownBlock2D")`):
128
+ The tuple of downsample blocks to use.
129
+ block_out_channels (`Tuple[int]`, *optional*, defaults to `(320, 640, 1280, 1280)`):
130
+ The tuple of output channels for each block.
131
+ layers_per_block (`int`, *optional*, defaults to 2):
132
+ The number of layers per block.
133
+ attention_head_dim (`int` or `Tuple[int]`, *optional*, defaults to 8):
134
+ The dimension of the attention heads.
135
+ num_attention_heads (`int` or `Tuple[int]`, *optional*):
136
+ The number of attention heads.
137
+ cross_attention_dim (`int`, *optional*, defaults to 768):
138
+ The dimension of the cross attention features.
139
+ dropout (`float`, *optional*, defaults to 0):
140
+ Dropout probability for down, up and bottleneck blocks.
141
+ flip_sin_to_cos (`bool`, *optional*, defaults to `True`):
142
+ Whether to flip the sin to cos in the time embedding.
143
+ freq_shift (`int`, *optional*, defaults to 0): The frequency shift to apply to the time embedding.
144
+ controlnet_conditioning_channel_order (`str`, *optional*, defaults to `rgb`):
145
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
146
+ conditioning_embedding_out_channels (`tuple`, *optional*, defaults to `(16, 32, 96, 256)`):
147
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
148
+ """
149
+
150
+ sample_size: int = 32
151
+ in_channels: int = 4
152
+ down_block_types: Tuple[str, ...] = (
153
+ "CrossAttnDownBlock2D",
154
+ "CrossAttnDownBlock2D",
155
+ "CrossAttnDownBlock2D",
156
+ "DownBlock2D",
157
+ )
158
+ only_cross_attention: Union[bool, Tuple[bool, ...]] = False
159
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280)
160
+ layers_per_block: int = 2
161
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8
162
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None
163
+ cross_attention_dim: int = 1280
164
+ dropout: float = 0.0
165
+ use_linear_projection: bool = False
166
+ dtype: jnp.dtype = jnp.float32
167
+ flip_sin_to_cos: bool = True
168
+ freq_shift: int = 0
169
+ controlnet_conditioning_channel_order: str = "rgb"
170
+ conditioning_embedding_out_channels: Tuple[int, ...] = (16, 32, 96, 256)
171
+
172
+ def init_weights(self, rng: jax.Array) -> FrozenDict:
173
+ # init input tensors
174
+ sample_shape = (1, self.in_channels, self.sample_size, self.sample_size)
175
+ sample = jnp.zeros(sample_shape, dtype=jnp.float32)
176
+ timesteps = jnp.ones((1,), dtype=jnp.int32)
177
+ encoder_hidden_states = jnp.zeros((1, 1, self.cross_attention_dim), dtype=jnp.float32)
178
+ controlnet_cond_shape = (1, 3, self.sample_size * 8, self.sample_size * 8)
179
+ controlnet_cond = jnp.zeros(controlnet_cond_shape, dtype=jnp.float32)
180
+
181
+ params_rng, dropout_rng = jax.random.split(rng)
182
+ rngs = {"params": params_rng, "dropout": dropout_rng}
183
+
184
+ return self.init(rngs, sample, timesteps, encoder_hidden_states, controlnet_cond)["params"]
185
+
186
+ def setup(self) -> None:
187
+ block_out_channels = self.block_out_channels
188
+ time_embed_dim = block_out_channels[0] * 4
189
+
190
+ # If `num_attention_heads` is not defined (which is the case for most models)
191
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
192
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
193
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
194
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
195
+ # which is why we correct for the naming here.
196
+ num_attention_heads = self.num_attention_heads or self.attention_head_dim
197
+
198
+ # input
199
+ self.conv_in = nn.Conv(
200
+ block_out_channels[0],
201
+ kernel_size=(3, 3),
202
+ strides=(1, 1),
203
+ padding=((1, 1), (1, 1)),
204
+ dtype=self.dtype,
205
+ )
206
+
207
+ # time
208
+ self.time_proj = FlaxTimesteps(
209
+ block_out_channels[0], flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.config.freq_shift
210
+ )
211
+ self.time_embedding = FlaxTimestepEmbedding(time_embed_dim, dtype=self.dtype)
212
+
213
+ self.controlnet_cond_embedding = FlaxControlNetConditioningEmbedding(
214
+ conditioning_embedding_channels=block_out_channels[0],
215
+ block_out_channels=self.conditioning_embedding_out_channels,
216
+ )
217
+
218
+ only_cross_attention = self.only_cross_attention
219
+ if isinstance(only_cross_attention, bool):
220
+ only_cross_attention = (only_cross_attention,) * len(self.down_block_types)
221
+
222
+ if isinstance(num_attention_heads, int):
223
+ num_attention_heads = (num_attention_heads,) * len(self.down_block_types)
224
+
225
+ # down
226
+ down_blocks = []
227
+ controlnet_down_blocks = []
228
+
229
+ output_channel = block_out_channels[0]
230
+
231
+ controlnet_block = nn.Conv(
232
+ output_channel,
233
+ kernel_size=(1, 1),
234
+ padding="VALID",
235
+ kernel_init=nn.initializers.zeros_init(),
236
+ bias_init=nn.initializers.zeros_init(),
237
+ dtype=self.dtype,
238
+ )
239
+ controlnet_down_blocks.append(controlnet_block)
240
+
241
+ for i, down_block_type in enumerate(self.down_block_types):
242
+ input_channel = output_channel
243
+ output_channel = block_out_channels[i]
244
+ is_final_block = i == len(block_out_channels) - 1
245
+
246
+ if down_block_type == "CrossAttnDownBlock2D":
247
+ down_block = FlaxCrossAttnDownBlock2D(
248
+ in_channels=input_channel,
249
+ out_channels=output_channel,
250
+ dropout=self.dropout,
251
+ num_layers=self.layers_per_block,
252
+ num_attention_heads=num_attention_heads[i],
253
+ add_downsample=not is_final_block,
254
+ use_linear_projection=self.use_linear_projection,
255
+ only_cross_attention=only_cross_attention[i],
256
+ dtype=self.dtype,
257
+ )
258
+ else:
259
+ down_block = FlaxDownBlock2D(
260
+ in_channels=input_channel,
261
+ out_channels=output_channel,
262
+ dropout=self.dropout,
263
+ num_layers=self.layers_per_block,
264
+ add_downsample=not is_final_block,
265
+ dtype=self.dtype,
266
+ )
267
+
268
+ down_blocks.append(down_block)
269
+
270
+ for _ in range(self.layers_per_block):
271
+ controlnet_block = nn.Conv(
272
+ output_channel,
273
+ kernel_size=(1, 1),
274
+ padding="VALID",
275
+ kernel_init=nn.initializers.zeros_init(),
276
+ bias_init=nn.initializers.zeros_init(),
277
+ dtype=self.dtype,
278
+ )
279
+ controlnet_down_blocks.append(controlnet_block)
280
+
281
+ if not is_final_block:
282
+ controlnet_block = nn.Conv(
283
+ output_channel,
284
+ kernel_size=(1, 1),
285
+ padding="VALID",
286
+ kernel_init=nn.initializers.zeros_init(),
287
+ bias_init=nn.initializers.zeros_init(),
288
+ dtype=self.dtype,
289
+ )
290
+ controlnet_down_blocks.append(controlnet_block)
291
+
292
+ self.down_blocks = down_blocks
293
+ self.controlnet_down_blocks = controlnet_down_blocks
294
+
295
+ # mid
296
+ mid_block_channel = block_out_channels[-1]
297
+ self.mid_block = FlaxUNetMidBlock2DCrossAttn(
298
+ in_channels=mid_block_channel,
299
+ dropout=self.dropout,
300
+ num_attention_heads=num_attention_heads[-1],
301
+ use_linear_projection=self.use_linear_projection,
302
+ dtype=self.dtype,
303
+ )
304
+
305
+ self.controlnet_mid_block = nn.Conv(
306
+ mid_block_channel,
307
+ kernel_size=(1, 1),
308
+ padding="VALID",
309
+ kernel_init=nn.initializers.zeros_init(),
310
+ bias_init=nn.initializers.zeros_init(),
311
+ dtype=self.dtype,
312
+ )
313
+
314
+ def __call__(
315
+ self,
316
+ sample: jnp.ndarray,
317
+ timesteps: Union[jnp.ndarray, float, int],
318
+ encoder_hidden_states: jnp.ndarray,
319
+ controlnet_cond: jnp.ndarray,
320
+ conditioning_scale: float = 1.0,
321
+ return_dict: bool = True,
322
+ train: bool = False,
323
+ ) -> Union[FlaxControlNetOutput, Tuple[Tuple[jnp.ndarray, ...], jnp.ndarray]]:
324
+ r"""
325
+ Args:
326
+ sample (`jnp.ndarray`): (batch, channel, height, width) noisy inputs tensor
327
+ timestep (`jnp.ndarray` or `float` or `int`): timesteps
328
+ encoder_hidden_states (`jnp.ndarray`): (batch_size, sequence_length, hidden_size) encoder hidden states
329
+ controlnet_cond (`jnp.ndarray`): (batch, channel, height, width) the conditional input tensor
330
+ conditioning_scale (`float`, *optional*, defaults to `1.0`): the scale factor for controlnet outputs
331
+ return_dict (`bool`, *optional*, defaults to `True`):
332
+ Whether or not to return a [`models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] instead of
333
+ a plain tuple.
334
+ train (`bool`, *optional*, defaults to `False`):
335
+ Use deterministic functions and disable dropout when not training.
336
+
337
+ Returns:
338
+ [`~models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] or `tuple`:
339
+ [`~models.unets.unet_2d_condition_flax.FlaxUNet2DConditionOutput`] if `return_dict` is True, otherwise
340
+ a `tuple`. When returning a tuple, the first element is the sample tensor.
341
+ """
342
+ channel_order = self.controlnet_conditioning_channel_order
343
+ if channel_order == "bgr":
344
+ controlnet_cond = jnp.flip(controlnet_cond, axis=1)
345
+
346
+ # 1. time
347
+ if not isinstance(timesteps, jnp.ndarray):
348
+ timesteps = jnp.array([timesteps], dtype=jnp.int32)
349
+ elif isinstance(timesteps, jnp.ndarray) and len(timesteps.shape) == 0:
350
+ timesteps = timesteps.astype(dtype=jnp.float32)
351
+ timesteps = jnp.expand_dims(timesteps, 0)
352
+
353
+ t_emb = self.time_proj(timesteps)
354
+ t_emb = self.time_embedding(t_emb)
355
+
356
+ # 2. pre-process
357
+ sample = jnp.transpose(sample, (0, 2, 3, 1))
358
+ sample = self.conv_in(sample)
359
+
360
+ controlnet_cond = jnp.transpose(controlnet_cond, (0, 2, 3, 1))
361
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
362
+ sample += controlnet_cond
363
+
364
+ # 3. down
365
+ down_block_res_samples = (sample,)
366
+ for down_block in self.down_blocks:
367
+ if isinstance(down_block, FlaxCrossAttnDownBlock2D):
368
+ sample, res_samples = down_block(sample, t_emb, encoder_hidden_states, deterministic=not train)
369
+ else:
370
+ sample, res_samples = down_block(sample, t_emb, deterministic=not train)
371
+ down_block_res_samples += res_samples
372
+
373
+ # 4. mid
374
+ sample = self.mid_block(sample, t_emb, encoder_hidden_states, deterministic=not train)
375
+
376
+ # 5. contronet blocks
377
+ controlnet_down_block_res_samples = ()
378
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
379
+ down_block_res_sample = controlnet_block(down_block_res_sample)
380
+ controlnet_down_block_res_samples += (down_block_res_sample,)
381
+
382
+ down_block_res_samples = controlnet_down_block_res_samples
383
+
384
+ mid_block_res_sample = self.controlnet_mid_block(sample)
385
+
386
+ # 6. scaling
387
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
388
+ mid_block_res_sample *= conditioning_scale
389
+
390
+ if not return_dict:
391
+ return (down_block_res_samples, mid_block_res_sample)
392
+
393
+ return FlaxControlNetOutput(
394
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
395
+ )
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_flux.py ADDED
@@ -0,0 +1,509 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...loaders import PeftAdapterMixin
23
+ from ...models.attention_processor import AttentionProcessor
24
+ from ...models.modeling_utils import ModelMixin
25
+ from ...utils import USE_PEFT_BACKEND, BaseOutput, logging, scale_lora_layers, unscale_lora_layers
26
+ from ..controlnets.controlnet import ControlNetConditioningEmbedding, zero_module
27
+ from ..embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
28
+ from ..modeling_outputs import Transformer2DModelOutput
29
+ from ..transformers.transformer_flux import FluxSingleTransformerBlock, FluxTransformerBlock
30
+
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+
35
+ @dataclass
36
+ class FluxControlNetOutput(BaseOutput):
37
+ controlnet_block_samples: Tuple[torch.Tensor]
38
+ controlnet_single_block_samples: Tuple[torch.Tensor]
39
+
40
+
41
+ class FluxControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
42
+ _supports_gradient_checkpointing = True
43
+
44
+ @register_to_config
45
+ def __init__(
46
+ self,
47
+ patch_size: int = 1,
48
+ in_channels: int = 64,
49
+ num_layers: int = 19,
50
+ num_single_layers: int = 38,
51
+ attention_head_dim: int = 128,
52
+ num_attention_heads: int = 24,
53
+ joint_attention_dim: int = 4096,
54
+ pooled_projection_dim: int = 768,
55
+ guidance_embeds: bool = False,
56
+ axes_dims_rope: List[int] = [16, 56, 56],
57
+ num_mode: int = None,
58
+ conditioning_embedding_channels: int = None,
59
+ ):
60
+ super().__init__()
61
+ self.out_channels = in_channels
62
+ self.inner_dim = num_attention_heads * attention_head_dim
63
+
64
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
65
+ text_time_guidance_cls = (
66
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
67
+ )
68
+ self.time_text_embed = text_time_guidance_cls(
69
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
70
+ )
71
+
72
+ self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
73
+ self.x_embedder = torch.nn.Linear(in_channels, self.inner_dim)
74
+
75
+ self.transformer_blocks = nn.ModuleList(
76
+ [
77
+ FluxTransformerBlock(
78
+ dim=self.inner_dim,
79
+ num_attention_heads=num_attention_heads,
80
+ attention_head_dim=attention_head_dim,
81
+ )
82
+ for i in range(num_layers)
83
+ ]
84
+ )
85
+
86
+ self.single_transformer_blocks = nn.ModuleList(
87
+ [
88
+ FluxSingleTransformerBlock(
89
+ dim=self.inner_dim,
90
+ num_attention_heads=num_attention_heads,
91
+ attention_head_dim=attention_head_dim,
92
+ )
93
+ for i in range(num_single_layers)
94
+ ]
95
+ )
96
+
97
+ # controlnet_blocks
98
+ self.controlnet_blocks = nn.ModuleList([])
99
+ for _ in range(len(self.transformer_blocks)):
100
+ self.controlnet_blocks.append(zero_module(nn.Linear(self.inner_dim, self.inner_dim)))
101
+
102
+ self.controlnet_single_blocks = nn.ModuleList([])
103
+ for _ in range(len(self.single_transformer_blocks)):
104
+ self.controlnet_single_blocks.append(zero_module(nn.Linear(self.inner_dim, self.inner_dim)))
105
+
106
+ self.union = num_mode is not None
107
+ if self.union:
108
+ self.controlnet_mode_embedder = nn.Embedding(num_mode, self.inner_dim)
109
+
110
+ if conditioning_embedding_channels is not None:
111
+ self.input_hint_block = ControlNetConditioningEmbedding(
112
+ conditioning_embedding_channels=conditioning_embedding_channels, block_out_channels=(16, 16, 16, 16)
113
+ )
114
+ self.controlnet_x_embedder = torch.nn.Linear(in_channels, self.inner_dim)
115
+ else:
116
+ self.input_hint_block = None
117
+ self.controlnet_x_embedder = zero_module(torch.nn.Linear(in_channels, self.inner_dim))
118
+
119
+ self.gradient_checkpointing = False
120
+
121
+ @property
122
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
123
+ def attn_processors(self):
124
+ r"""
125
+ Returns:
126
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
127
+ indexed by its weight name.
128
+ """
129
+ # set recursively
130
+ processors = {}
131
+
132
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
133
+ if hasattr(module, "get_processor"):
134
+ processors[f"{name}.processor"] = module.get_processor()
135
+
136
+ for sub_name, child in module.named_children():
137
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
138
+
139
+ return processors
140
+
141
+ for name, module in self.named_children():
142
+ fn_recursive_add_processors(name, module, processors)
143
+
144
+ return processors
145
+
146
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
147
+ def set_attn_processor(self, processor):
148
+ r"""
149
+ Sets the attention processor to use to compute attention.
150
+
151
+ Parameters:
152
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
153
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
154
+ for **all** `Attention` layers.
155
+
156
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
157
+ processor. This is strongly recommended when setting trainable attention processors.
158
+
159
+ """
160
+ count = len(self.attn_processors.keys())
161
+
162
+ if isinstance(processor, dict) and len(processor) != count:
163
+ raise ValueError(
164
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
165
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
166
+ )
167
+
168
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
169
+ if hasattr(module, "set_processor"):
170
+ if not isinstance(processor, dict):
171
+ module.set_processor(processor)
172
+ else:
173
+ module.set_processor(processor.pop(f"{name}.processor"))
174
+
175
+ for sub_name, child in module.named_children():
176
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
177
+
178
+ for name, module in self.named_children():
179
+ fn_recursive_attn_processor(name, module, processor)
180
+
181
+ @classmethod
182
+ def from_transformer(
183
+ cls,
184
+ transformer,
185
+ num_layers: int = 4,
186
+ num_single_layers: int = 10,
187
+ attention_head_dim: int = 128,
188
+ num_attention_heads: int = 24,
189
+ load_weights_from_transformer=True,
190
+ ):
191
+ config = dict(transformer.config)
192
+ config["num_layers"] = num_layers
193
+ config["num_single_layers"] = num_single_layers
194
+ config["attention_head_dim"] = attention_head_dim
195
+ config["num_attention_heads"] = num_attention_heads
196
+
197
+ controlnet = cls.from_config(config)
198
+
199
+ if load_weights_from_transformer:
200
+ controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict())
201
+ controlnet.time_text_embed.load_state_dict(transformer.time_text_embed.state_dict())
202
+ controlnet.context_embedder.load_state_dict(transformer.context_embedder.state_dict())
203
+ controlnet.x_embedder.load_state_dict(transformer.x_embedder.state_dict())
204
+ controlnet.transformer_blocks.load_state_dict(transformer.transformer_blocks.state_dict(), strict=False)
205
+ controlnet.single_transformer_blocks.load_state_dict(
206
+ transformer.single_transformer_blocks.state_dict(), strict=False
207
+ )
208
+
209
+ controlnet.controlnet_x_embedder = zero_module(controlnet.controlnet_x_embedder)
210
+
211
+ return controlnet
212
+
213
+ def forward(
214
+ self,
215
+ hidden_states: torch.Tensor,
216
+ controlnet_cond: torch.Tensor,
217
+ controlnet_mode: torch.Tensor = None,
218
+ conditioning_scale: float = 1.0,
219
+ encoder_hidden_states: torch.Tensor = None,
220
+ pooled_projections: torch.Tensor = None,
221
+ timestep: torch.LongTensor = None,
222
+ img_ids: torch.Tensor = None,
223
+ txt_ids: torch.Tensor = None,
224
+ guidance: torch.Tensor = None,
225
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
226
+ return_dict: bool = True,
227
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
228
+ """
229
+ The [`FluxTransformer2DModel`] forward method.
230
+
231
+ Args:
232
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
233
+ Input `hidden_states`.
234
+ controlnet_cond (`torch.Tensor`):
235
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
236
+ controlnet_mode (`torch.Tensor`):
237
+ The mode tensor of shape `(batch_size, 1)`.
238
+ conditioning_scale (`float`, defaults to `1.0`):
239
+ The scale factor for ControlNet outputs.
240
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence_len, embed_dims)`):
241
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
242
+ pooled_projections (`torch.FloatTensor` of shape `(batch_size, projection_dim)`): Embeddings projected
243
+ from the embeddings of input conditions.
244
+ timestep ( `torch.LongTensor`):
245
+ Used to indicate denoising step.
246
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
247
+ A list of tensors that if specified are added to the residuals of transformer blocks.
248
+ joint_attention_kwargs (`dict`, *optional*):
249
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
250
+ `self.processor` in
251
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
252
+ return_dict (`bool`, *optional*, defaults to `True`):
253
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
254
+ tuple.
255
+
256
+ Returns:
257
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
258
+ `tuple` where the first element is the sample tensor.
259
+ """
260
+ if joint_attention_kwargs is not None:
261
+ joint_attention_kwargs = joint_attention_kwargs.copy()
262
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
263
+ else:
264
+ lora_scale = 1.0
265
+
266
+ if USE_PEFT_BACKEND:
267
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
268
+ scale_lora_layers(self, lora_scale)
269
+ else:
270
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
271
+ logger.warning(
272
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
273
+ )
274
+ hidden_states = self.x_embedder(hidden_states)
275
+
276
+ if self.input_hint_block is not None:
277
+ controlnet_cond = self.input_hint_block(controlnet_cond)
278
+ batch_size, channels, height_pw, width_pw = controlnet_cond.shape
279
+ height = height_pw // self.config.patch_size
280
+ width = width_pw // self.config.patch_size
281
+ controlnet_cond = controlnet_cond.reshape(
282
+ batch_size, channels, height, self.config.patch_size, width, self.config.patch_size
283
+ )
284
+ controlnet_cond = controlnet_cond.permute(0, 2, 4, 1, 3, 5)
285
+ controlnet_cond = controlnet_cond.reshape(batch_size, height * width, -1)
286
+ # add
287
+ hidden_states = hidden_states + self.controlnet_x_embedder(controlnet_cond)
288
+
289
+ timestep = timestep.to(hidden_states.dtype) * 1000
290
+ if guidance is not None:
291
+ guidance = guidance.to(hidden_states.dtype) * 1000
292
+ else:
293
+ guidance = None
294
+ temb = (
295
+ self.time_text_embed(timestep, pooled_projections)
296
+ if guidance is None
297
+ else self.time_text_embed(timestep, guidance, pooled_projections)
298
+ )
299
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
300
+
301
+ if txt_ids.ndim == 3:
302
+ logger.warning(
303
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
304
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
305
+ )
306
+ txt_ids = txt_ids[0]
307
+ if img_ids.ndim == 3:
308
+ logger.warning(
309
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
310
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
311
+ )
312
+ img_ids = img_ids[0]
313
+
314
+ if self.union:
315
+ # union mode
316
+ if controlnet_mode is None:
317
+ raise ValueError("`controlnet_mode` cannot be `None` when applying ControlNet-Union")
318
+ # union mode emb
319
+ controlnet_mode_emb = self.controlnet_mode_embedder(controlnet_mode)
320
+ encoder_hidden_states = torch.cat([controlnet_mode_emb, encoder_hidden_states], dim=1)
321
+ txt_ids = torch.cat([txt_ids[:1], txt_ids], dim=0)
322
+
323
+ ids = torch.cat((txt_ids, img_ids), dim=0)
324
+ image_rotary_emb = self.pos_embed(ids)
325
+
326
+ block_samples = ()
327
+ for index_block, block in enumerate(self.transformer_blocks):
328
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
329
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
330
+ block,
331
+ hidden_states,
332
+ encoder_hidden_states,
333
+ temb,
334
+ image_rotary_emb,
335
+ )
336
+
337
+ else:
338
+ encoder_hidden_states, hidden_states = block(
339
+ hidden_states=hidden_states,
340
+ encoder_hidden_states=encoder_hidden_states,
341
+ temb=temb,
342
+ image_rotary_emb=image_rotary_emb,
343
+ )
344
+ block_samples = block_samples + (hidden_states,)
345
+
346
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
347
+
348
+ single_block_samples = ()
349
+ for index_block, block in enumerate(self.single_transformer_blocks):
350
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
351
+ hidden_states = self._gradient_checkpointing_func(
352
+ block,
353
+ hidden_states,
354
+ temb,
355
+ image_rotary_emb,
356
+ )
357
+
358
+ else:
359
+ hidden_states = block(
360
+ hidden_states=hidden_states,
361
+ temb=temb,
362
+ image_rotary_emb=image_rotary_emb,
363
+ )
364
+ single_block_samples = single_block_samples + (hidden_states[:, encoder_hidden_states.shape[1] :],)
365
+
366
+ # controlnet block
367
+ controlnet_block_samples = ()
368
+ for block_sample, controlnet_block in zip(block_samples, self.controlnet_blocks):
369
+ block_sample = controlnet_block(block_sample)
370
+ controlnet_block_samples = controlnet_block_samples + (block_sample,)
371
+
372
+ controlnet_single_block_samples = ()
373
+ for single_block_sample, controlnet_block in zip(single_block_samples, self.controlnet_single_blocks):
374
+ single_block_sample = controlnet_block(single_block_sample)
375
+ controlnet_single_block_samples = controlnet_single_block_samples + (single_block_sample,)
376
+
377
+ # scaling
378
+ controlnet_block_samples = [sample * conditioning_scale for sample in controlnet_block_samples]
379
+ controlnet_single_block_samples = [sample * conditioning_scale for sample in controlnet_single_block_samples]
380
+
381
+ controlnet_block_samples = None if len(controlnet_block_samples) == 0 else controlnet_block_samples
382
+ controlnet_single_block_samples = (
383
+ None if len(controlnet_single_block_samples) == 0 else controlnet_single_block_samples
384
+ )
385
+
386
+ if USE_PEFT_BACKEND:
387
+ # remove `lora_scale` from each PEFT layer
388
+ unscale_lora_layers(self, lora_scale)
389
+
390
+ if not return_dict:
391
+ return (controlnet_block_samples, controlnet_single_block_samples)
392
+
393
+ return FluxControlNetOutput(
394
+ controlnet_block_samples=controlnet_block_samples,
395
+ controlnet_single_block_samples=controlnet_single_block_samples,
396
+ )
397
+
398
+
399
+ class FluxMultiControlNetModel(ModelMixin):
400
+ r"""
401
+ `FluxMultiControlNetModel` wrapper class for Multi-FluxControlNetModel
402
+
403
+ This module is a wrapper for multiple instances of the `FluxControlNetModel`. The `forward()` API is designed to be
404
+ compatible with `FluxControlNetModel`.
405
+
406
+ Args:
407
+ controlnets (`List[FluxControlNetModel]`):
408
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
409
+ `FluxControlNetModel` as a list.
410
+ """
411
+
412
+ def __init__(self, controlnets):
413
+ super().__init__()
414
+ self.nets = nn.ModuleList(controlnets)
415
+
416
+ def forward(
417
+ self,
418
+ hidden_states: torch.FloatTensor,
419
+ controlnet_cond: List[torch.tensor],
420
+ controlnet_mode: List[torch.tensor],
421
+ conditioning_scale: List[float],
422
+ encoder_hidden_states: torch.Tensor = None,
423
+ pooled_projections: torch.Tensor = None,
424
+ timestep: torch.LongTensor = None,
425
+ img_ids: torch.Tensor = None,
426
+ txt_ids: torch.Tensor = None,
427
+ guidance: torch.Tensor = None,
428
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
429
+ return_dict: bool = True,
430
+ ) -> Union[FluxControlNetOutput, Tuple]:
431
+ # ControlNet-Union with multiple conditions
432
+ # only load one ControlNet for saving memories
433
+ if len(self.nets) == 1:
434
+ controlnet = self.nets[0]
435
+
436
+ for i, (image, mode, scale) in enumerate(zip(controlnet_cond, controlnet_mode, conditioning_scale)):
437
+ block_samples, single_block_samples = controlnet(
438
+ hidden_states=hidden_states,
439
+ controlnet_cond=image,
440
+ controlnet_mode=mode[:, None],
441
+ conditioning_scale=scale,
442
+ timestep=timestep,
443
+ guidance=guidance,
444
+ pooled_projections=pooled_projections,
445
+ encoder_hidden_states=encoder_hidden_states,
446
+ txt_ids=txt_ids,
447
+ img_ids=img_ids,
448
+ joint_attention_kwargs=joint_attention_kwargs,
449
+ return_dict=return_dict,
450
+ )
451
+
452
+ # merge samples
453
+ if i == 0:
454
+ control_block_samples = block_samples
455
+ control_single_block_samples = single_block_samples
456
+ else:
457
+ if block_samples is not None and control_block_samples is not None:
458
+ control_block_samples = [
459
+ control_block_sample + block_sample
460
+ for control_block_sample, block_sample in zip(control_block_samples, block_samples)
461
+ ]
462
+ if single_block_samples is not None and control_single_block_samples is not None:
463
+ control_single_block_samples = [
464
+ control_single_block_sample + block_sample
465
+ for control_single_block_sample, block_sample in zip(
466
+ control_single_block_samples, single_block_samples
467
+ )
468
+ ]
469
+
470
+ # Regular Multi-ControlNets
471
+ # load all ControlNets into memories
472
+ else:
473
+ for i, (image, mode, scale, controlnet) in enumerate(
474
+ zip(controlnet_cond, controlnet_mode, conditioning_scale, self.nets)
475
+ ):
476
+ block_samples, single_block_samples = controlnet(
477
+ hidden_states=hidden_states,
478
+ controlnet_cond=image,
479
+ controlnet_mode=mode[:, None],
480
+ conditioning_scale=scale,
481
+ timestep=timestep,
482
+ guidance=guidance,
483
+ pooled_projections=pooled_projections,
484
+ encoder_hidden_states=encoder_hidden_states,
485
+ txt_ids=txt_ids,
486
+ img_ids=img_ids,
487
+ joint_attention_kwargs=joint_attention_kwargs,
488
+ return_dict=return_dict,
489
+ )
490
+
491
+ # merge samples
492
+ if i == 0:
493
+ control_block_samples = block_samples
494
+ control_single_block_samples = single_block_samples
495
+ else:
496
+ if block_samples is not None and control_block_samples is not None:
497
+ control_block_samples = [
498
+ control_block_sample + block_sample
499
+ for control_block_sample, block_sample in zip(control_block_samples, block_samples)
500
+ ]
501
+ if single_block_samples is not None and control_single_block_samples is not None:
502
+ control_single_block_samples = [
503
+ control_single_block_sample + block_sample
504
+ for control_single_block_sample, block_sample in zip(
505
+ control_single_block_samples, single_block_samples
506
+ )
507
+ ]
508
+
509
+ return control_block_samples, control_single_block_samples
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_hunyuan.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HunyuanDiT Authors, Qixun Wang and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from typing import Dict, Optional, Union
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from ...configuration_utils import ConfigMixin, register_to_config
21
+ from ...utils import BaseOutput, logging
22
+ from ..attention_processor import AttentionProcessor
23
+ from ..embeddings import (
24
+ HunyuanCombinedTimestepTextSizeStyleEmbedding,
25
+ PatchEmbed,
26
+ PixArtAlphaTextProjection,
27
+ )
28
+ from ..modeling_utils import ModelMixin
29
+ from ..transformers.hunyuan_transformer_2d import HunyuanDiTBlock
30
+ from .controlnet import Tuple, zero_module
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+
36
+ @dataclass
37
+ class HunyuanControlNetOutput(BaseOutput):
38
+ controlnet_block_samples: Tuple[torch.Tensor]
39
+
40
+
41
+ class HunyuanDiT2DControlNetModel(ModelMixin, ConfigMixin):
42
+ @register_to_config
43
+ def __init__(
44
+ self,
45
+ conditioning_channels: int = 3,
46
+ num_attention_heads: int = 16,
47
+ attention_head_dim: int = 88,
48
+ in_channels: Optional[int] = None,
49
+ patch_size: Optional[int] = None,
50
+ activation_fn: str = "gelu-approximate",
51
+ sample_size=32,
52
+ hidden_size=1152,
53
+ transformer_num_layers: int = 40,
54
+ mlp_ratio: float = 4.0,
55
+ cross_attention_dim: int = 1024,
56
+ cross_attention_dim_t5: int = 2048,
57
+ pooled_projection_dim: int = 1024,
58
+ text_len: int = 77,
59
+ text_len_t5: int = 256,
60
+ use_style_cond_and_image_meta_size: bool = True,
61
+ ):
62
+ super().__init__()
63
+ self.num_heads = num_attention_heads
64
+ self.inner_dim = num_attention_heads * attention_head_dim
65
+
66
+ self.text_embedder = PixArtAlphaTextProjection(
67
+ in_features=cross_attention_dim_t5,
68
+ hidden_size=cross_attention_dim_t5 * 4,
69
+ out_features=cross_attention_dim,
70
+ act_fn="silu_fp32",
71
+ )
72
+
73
+ self.text_embedding_padding = nn.Parameter(
74
+ torch.randn(text_len + text_len_t5, cross_attention_dim, dtype=torch.float32)
75
+ )
76
+
77
+ self.pos_embed = PatchEmbed(
78
+ height=sample_size,
79
+ width=sample_size,
80
+ in_channels=in_channels,
81
+ embed_dim=hidden_size,
82
+ patch_size=patch_size,
83
+ pos_embed_type=None,
84
+ )
85
+
86
+ self.time_extra_emb = HunyuanCombinedTimestepTextSizeStyleEmbedding(
87
+ hidden_size,
88
+ pooled_projection_dim=pooled_projection_dim,
89
+ seq_len=text_len_t5,
90
+ cross_attention_dim=cross_attention_dim_t5,
91
+ use_style_cond_and_image_meta_size=use_style_cond_and_image_meta_size,
92
+ )
93
+
94
+ # controlnet_blocks
95
+ self.controlnet_blocks = nn.ModuleList([])
96
+
97
+ # HunyuanDiT Blocks
98
+ self.blocks = nn.ModuleList(
99
+ [
100
+ HunyuanDiTBlock(
101
+ dim=self.inner_dim,
102
+ num_attention_heads=self.config.num_attention_heads,
103
+ activation_fn=activation_fn,
104
+ ff_inner_dim=int(self.inner_dim * mlp_ratio),
105
+ cross_attention_dim=cross_attention_dim,
106
+ qk_norm=True, # See http://arxiv.org/abs/2302.05442 for details.
107
+ skip=False, # always False as it is the first half of the model
108
+ )
109
+ for layer in range(transformer_num_layers // 2 - 1)
110
+ ]
111
+ )
112
+ self.input_block = zero_module(nn.Linear(hidden_size, hidden_size))
113
+ for _ in range(len(self.blocks)):
114
+ controlnet_block = nn.Linear(hidden_size, hidden_size)
115
+ controlnet_block = zero_module(controlnet_block)
116
+ self.controlnet_blocks.append(controlnet_block)
117
+
118
+ @property
119
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
120
+ r"""
121
+ Returns:
122
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
123
+ indexed by its weight name.
124
+ """
125
+ # set recursively
126
+ processors = {}
127
+
128
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
129
+ if hasattr(module, "get_processor"):
130
+ processors[f"{name}.processor"] = module.get_processor(return_deprecated_lora=True)
131
+
132
+ for sub_name, child in module.named_children():
133
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
134
+
135
+ return processors
136
+
137
+ for name, module in self.named_children():
138
+ fn_recursive_add_processors(name, module, processors)
139
+
140
+ return processors
141
+
142
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
143
+ r"""
144
+ Sets the attention processor to use to compute attention.
145
+
146
+ Parameters:
147
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
148
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
149
+ for **all** `Attention` layers. If `processor` is a dict, the key needs to define the path to the
150
+ corresponding cross attention processor. This is strongly recommended when setting trainable attention
151
+ processors.
152
+ """
153
+ count = len(self.attn_processors.keys())
154
+
155
+ if isinstance(processor, dict) and len(processor) != count:
156
+ raise ValueError(
157
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
158
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
159
+ )
160
+
161
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
162
+ if hasattr(module, "set_processor"):
163
+ if not isinstance(processor, dict):
164
+ module.set_processor(processor)
165
+ else:
166
+ module.set_processor(processor.pop(f"{name}.processor"))
167
+
168
+ for sub_name, child in module.named_children():
169
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
170
+
171
+ for name, module in self.named_children():
172
+ fn_recursive_attn_processor(name, module, processor)
173
+
174
+ @classmethod
175
+ def from_transformer(
176
+ cls, transformer, conditioning_channels=3, transformer_num_layers=None, load_weights_from_transformer=True
177
+ ):
178
+ config = transformer.config
179
+ activation_fn = config.activation_fn
180
+ attention_head_dim = config.attention_head_dim
181
+ cross_attention_dim = config.cross_attention_dim
182
+ cross_attention_dim_t5 = config.cross_attention_dim_t5
183
+ hidden_size = config.hidden_size
184
+ in_channels = config.in_channels
185
+ mlp_ratio = config.mlp_ratio
186
+ num_attention_heads = config.num_attention_heads
187
+ patch_size = config.patch_size
188
+ sample_size = config.sample_size
189
+ text_len = config.text_len
190
+ text_len_t5 = config.text_len_t5
191
+
192
+ conditioning_channels = conditioning_channels
193
+ transformer_num_layers = transformer_num_layers or config.transformer_num_layers
194
+
195
+ controlnet = cls(
196
+ conditioning_channels=conditioning_channels,
197
+ transformer_num_layers=transformer_num_layers,
198
+ activation_fn=activation_fn,
199
+ attention_head_dim=attention_head_dim,
200
+ cross_attention_dim=cross_attention_dim,
201
+ cross_attention_dim_t5=cross_attention_dim_t5,
202
+ hidden_size=hidden_size,
203
+ in_channels=in_channels,
204
+ mlp_ratio=mlp_ratio,
205
+ num_attention_heads=num_attention_heads,
206
+ patch_size=patch_size,
207
+ sample_size=sample_size,
208
+ text_len=text_len,
209
+ text_len_t5=text_len_t5,
210
+ )
211
+ if load_weights_from_transformer:
212
+ key = controlnet.load_state_dict(transformer.state_dict(), strict=False)
213
+ logger.warning(f"controlnet load from Hunyuan-DiT. missing_keys: {key[0]}")
214
+ return controlnet
215
+
216
+ def forward(
217
+ self,
218
+ hidden_states,
219
+ timestep,
220
+ controlnet_cond: torch.Tensor,
221
+ conditioning_scale: float = 1.0,
222
+ encoder_hidden_states=None,
223
+ text_embedding_mask=None,
224
+ encoder_hidden_states_t5=None,
225
+ text_embedding_mask_t5=None,
226
+ image_meta_size=None,
227
+ style=None,
228
+ image_rotary_emb=None,
229
+ return_dict=True,
230
+ ):
231
+ """
232
+ The [`HunyuanDiT2DControlNetModel`] forward method.
233
+
234
+ Args:
235
+ hidden_states (`torch.Tensor` of shape `(batch size, dim, height, width)`):
236
+ The input tensor.
237
+ timestep ( `torch.LongTensor`, *optional*):
238
+ Used to indicate denoising step.
239
+ controlnet_cond ( `torch.Tensor` ):
240
+ The conditioning input to ControlNet.
241
+ conditioning_scale ( `float` ):
242
+ Indicate the conditioning scale.
243
+ encoder_hidden_states ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
244
+ Conditional embeddings for cross attention layer. This is the output of `BertModel`.
245
+ text_embedding_mask: torch.Tensor
246
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. This is the output
247
+ of `BertModel`.
248
+ encoder_hidden_states_t5 ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
249
+ Conditional embeddings for cross attention layer. This is the output of T5 Text Encoder.
250
+ text_embedding_mask_t5: torch.Tensor
251
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. This is the output
252
+ of T5 Text Encoder.
253
+ image_meta_size (torch.Tensor):
254
+ Conditional embedding indicate the image sizes
255
+ style: torch.Tensor:
256
+ Conditional embedding indicate the style
257
+ image_rotary_emb (`torch.Tensor`):
258
+ The image rotary embeddings to apply on query and key tensors during attention calculation.
259
+ return_dict: bool
260
+ Whether to return a dictionary.
261
+ """
262
+
263
+ height, width = hidden_states.shape[-2:]
264
+
265
+ hidden_states = self.pos_embed(hidden_states) # b,c,H,W -> b, N, C
266
+
267
+ # 2. pre-process
268
+ hidden_states = hidden_states + self.input_block(self.pos_embed(controlnet_cond))
269
+
270
+ temb = self.time_extra_emb(
271
+ timestep, encoder_hidden_states_t5, image_meta_size, style, hidden_dtype=timestep.dtype
272
+ ) # [B, D]
273
+
274
+ # text projection
275
+ batch_size, sequence_length, _ = encoder_hidden_states_t5.shape
276
+ encoder_hidden_states_t5 = self.text_embedder(
277
+ encoder_hidden_states_t5.view(-1, encoder_hidden_states_t5.shape[-1])
278
+ )
279
+ encoder_hidden_states_t5 = encoder_hidden_states_t5.view(batch_size, sequence_length, -1)
280
+
281
+ encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states_t5], dim=1)
282
+ text_embedding_mask = torch.cat([text_embedding_mask, text_embedding_mask_t5], dim=-1)
283
+ text_embedding_mask = text_embedding_mask.unsqueeze(2).bool()
284
+
285
+ encoder_hidden_states = torch.where(text_embedding_mask, encoder_hidden_states, self.text_embedding_padding)
286
+
287
+ block_res_samples = ()
288
+ for layer, block in enumerate(self.blocks):
289
+ hidden_states = block(
290
+ hidden_states,
291
+ temb=temb,
292
+ encoder_hidden_states=encoder_hidden_states,
293
+ image_rotary_emb=image_rotary_emb,
294
+ ) # (N, L, D)
295
+
296
+ block_res_samples = block_res_samples + (hidden_states,)
297
+
298
+ controlnet_block_res_samples = ()
299
+ for block_res_sample, controlnet_block in zip(block_res_samples, self.controlnet_blocks):
300
+ block_res_sample = controlnet_block(block_res_sample)
301
+ controlnet_block_res_samples = controlnet_block_res_samples + (block_res_sample,)
302
+
303
+ # 6. scaling
304
+ controlnet_block_res_samples = [sample * conditioning_scale for sample in controlnet_block_res_samples]
305
+
306
+ if not return_dict:
307
+ return (controlnet_block_res_samples,)
308
+
309
+ return HunyuanControlNetOutput(controlnet_block_samples=controlnet_block_res_samples)
310
+
311
+
312
+ class HunyuanDiT2DMultiControlNetModel(ModelMixin):
313
+ r"""
314
+ `HunyuanDiT2DMultiControlNetModel` wrapper class for Multi-HunyuanDiT2DControlNetModel
315
+
316
+ This module is a wrapper for multiple instances of the `HunyuanDiT2DControlNetModel`. The `forward()` API is
317
+ designed to be compatible with `HunyuanDiT2DControlNetModel`.
318
+
319
+ Args:
320
+ controlnets (`List[HunyuanDiT2DControlNetModel]`):
321
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
322
+ `HunyuanDiT2DControlNetModel` as a list.
323
+ """
324
+
325
+ def __init__(self, controlnets):
326
+ super().__init__()
327
+ self.nets = nn.ModuleList(controlnets)
328
+
329
+ def forward(
330
+ self,
331
+ hidden_states,
332
+ timestep,
333
+ controlnet_cond: torch.Tensor,
334
+ conditioning_scale: float = 1.0,
335
+ encoder_hidden_states=None,
336
+ text_embedding_mask=None,
337
+ encoder_hidden_states_t5=None,
338
+ text_embedding_mask_t5=None,
339
+ image_meta_size=None,
340
+ style=None,
341
+ image_rotary_emb=None,
342
+ return_dict=True,
343
+ ):
344
+ """
345
+ The [`HunyuanDiT2DControlNetModel`] forward method.
346
+
347
+ Args:
348
+ hidden_states (`torch.Tensor` of shape `(batch size, dim, height, width)`):
349
+ The input tensor.
350
+ timestep ( `torch.LongTensor`, *optional*):
351
+ Used to indicate denoising step.
352
+ controlnet_cond ( `torch.Tensor` ):
353
+ The conditioning input to ControlNet.
354
+ conditioning_scale ( `float` ):
355
+ Indicate the conditioning scale.
356
+ encoder_hidden_states ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
357
+ Conditional embeddings for cross attention layer. This is the output of `BertModel`.
358
+ text_embedding_mask: torch.Tensor
359
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. This is the output
360
+ of `BertModel`.
361
+ encoder_hidden_states_t5 ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
362
+ Conditional embeddings for cross attention layer. This is the output of T5 Text Encoder.
363
+ text_embedding_mask_t5: torch.Tensor
364
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. This is the output
365
+ of T5 Text Encoder.
366
+ image_meta_size (torch.Tensor):
367
+ Conditional embedding indicate the image sizes
368
+ style: torch.Tensor:
369
+ Conditional embedding indicate the style
370
+ image_rotary_emb (`torch.Tensor`):
371
+ The image rotary embeddings to apply on query and key tensors during attention calculation.
372
+ return_dict: bool
373
+ Whether to return a dictionary.
374
+ """
375
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
376
+ block_samples = controlnet(
377
+ hidden_states=hidden_states,
378
+ timestep=timestep,
379
+ controlnet_cond=image,
380
+ conditioning_scale=scale,
381
+ encoder_hidden_states=encoder_hidden_states,
382
+ text_embedding_mask=text_embedding_mask,
383
+ encoder_hidden_states_t5=encoder_hidden_states_t5,
384
+ text_embedding_mask_t5=text_embedding_mask_t5,
385
+ image_meta_size=image_meta_size,
386
+ style=style,
387
+ image_rotary_emb=image_rotary_emb,
388
+ return_dict=return_dict,
389
+ )
390
+
391
+ # merge samples
392
+ if i == 0:
393
+ control_block_samples = block_samples
394
+ else:
395
+ control_block_samples = [
396
+ control_block_sample + block_sample
397
+ for control_block_sample, block_sample in zip(control_block_samples[0], block_samples[0])
398
+ ]
399
+ control_block_samples = (control_block_samples,)
400
+
401
+ return control_block_samples
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_sana.py ADDED
@@ -0,0 +1,290 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...loaders import PeftAdapterMixin
23
+ from ...utils import USE_PEFT_BACKEND, BaseOutput, logging, scale_lora_layers, unscale_lora_layers
24
+ from ..attention_processor import AttentionProcessor
25
+ from ..embeddings import PatchEmbed, PixArtAlphaTextProjection
26
+ from ..modeling_outputs import Transformer2DModelOutput
27
+ from ..modeling_utils import ModelMixin
28
+ from ..normalization import AdaLayerNormSingle, RMSNorm
29
+ from ..transformers.sana_transformer import SanaTransformerBlock
30
+ from .controlnet import zero_module
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+
36
+ @dataclass
37
+ class SanaControlNetOutput(BaseOutput):
38
+ controlnet_block_samples: Tuple[torch.Tensor]
39
+
40
+
41
+ class SanaControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
42
+ _supports_gradient_checkpointing = True
43
+ _no_split_modules = ["SanaTransformerBlock", "PatchEmbed"]
44
+ _skip_layerwise_casting_patterns = ["patch_embed", "norm"]
45
+
46
+ @register_to_config
47
+ def __init__(
48
+ self,
49
+ in_channels: int = 32,
50
+ out_channels: Optional[int] = 32,
51
+ num_attention_heads: int = 70,
52
+ attention_head_dim: int = 32,
53
+ num_layers: int = 7,
54
+ num_cross_attention_heads: Optional[int] = 20,
55
+ cross_attention_head_dim: Optional[int] = 112,
56
+ cross_attention_dim: Optional[int] = 2240,
57
+ caption_channels: int = 2304,
58
+ mlp_ratio: float = 2.5,
59
+ dropout: float = 0.0,
60
+ attention_bias: bool = False,
61
+ sample_size: int = 32,
62
+ patch_size: int = 1,
63
+ norm_elementwise_affine: bool = False,
64
+ norm_eps: float = 1e-6,
65
+ interpolation_scale: Optional[int] = None,
66
+ ) -> None:
67
+ super().__init__()
68
+
69
+ out_channels = out_channels or in_channels
70
+ inner_dim = num_attention_heads * attention_head_dim
71
+
72
+ # 1. Patch Embedding
73
+ self.patch_embed = PatchEmbed(
74
+ height=sample_size,
75
+ width=sample_size,
76
+ patch_size=patch_size,
77
+ in_channels=in_channels,
78
+ embed_dim=inner_dim,
79
+ interpolation_scale=interpolation_scale,
80
+ pos_embed_type="sincos" if interpolation_scale is not None else None,
81
+ )
82
+
83
+ # 2. Additional condition embeddings
84
+ self.time_embed = AdaLayerNormSingle(inner_dim)
85
+
86
+ self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
87
+ self.caption_norm = RMSNorm(inner_dim, eps=1e-5, elementwise_affine=True)
88
+
89
+ # 3. Transformer blocks
90
+ self.transformer_blocks = nn.ModuleList(
91
+ [
92
+ SanaTransformerBlock(
93
+ inner_dim,
94
+ num_attention_heads,
95
+ attention_head_dim,
96
+ dropout=dropout,
97
+ num_cross_attention_heads=num_cross_attention_heads,
98
+ cross_attention_head_dim=cross_attention_head_dim,
99
+ cross_attention_dim=cross_attention_dim,
100
+ attention_bias=attention_bias,
101
+ norm_elementwise_affine=norm_elementwise_affine,
102
+ norm_eps=norm_eps,
103
+ mlp_ratio=mlp_ratio,
104
+ )
105
+ for _ in range(num_layers)
106
+ ]
107
+ )
108
+
109
+ # controlnet_blocks
110
+ self.controlnet_blocks = nn.ModuleList([])
111
+
112
+ self.input_block = zero_module(nn.Linear(inner_dim, inner_dim))
113
+ for _ in range(len(self.transformer_blocks)):
114
+ controlnet_block = nn.Linear(inner_dim, inner_dim)
115
+ controlnet_block = zero_module(controlnet_block)
116
+ self.controlnet_blocks.append(controlnet_block)
117
+
118
+ self.gradient_checkpointing = False
119
+
120
+ @property
121
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
122
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
123
+ r"""
124
+ Returns:
125
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
126
+ indexed by its weight name.
127
+ """
128
+ # set recursively
129
+ processors = {}
130
+
131
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
132
+ if hasattr(module, "get_processor"):
133
+ processors[f"{name}.processor"] = module.get_processor()
134
+
135
+ for sub_name, child in module.named_children():
136
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
137
+
138
+ return processors
139
+
140
+ for name, module in self.named_children():
141
+ fn_recursive_add_processors(name, module, processors)
142
+
143
+ return processors
144
+
145
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
146
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
147
+ r"""
148
+ Sets the attention processor to use to compute attention.
149
+
150
+ Parameters:
151
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
152
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
153
+ for **all** `Attention` layers.
154
+
155
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
156
+ processor. This is strongly recommended when setting trainable attention processors.
157
+
158
+ """
159
+ count = len(self.attn_processors.keys())
160
+
161
+ if isinstance(processor, dict) and len(processor) != count:
162
+ raise ValueError(
163
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
164
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
165
+ )
166
+
167
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
168
+ if hasattr(module, "set_processor"):
169
+ if not isinstance(processor, dict):
170
+ module.set_processor(processor)
171
+ else:
172
+ module.set_processor(processor.pop(f"{name}.processor"))
173
+
174
+ for sub_name, child in module.named_children():
175
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
176
+
177
+ for name, module in self.named_children():
178
+ fn_recursive_attn_processor(name, module, processor)
179
+
180
+ def forward(
181
+ self,
182
+ hidden_states: torch.Tensor,
183
+ encoder_hidden_states: torch.Tensor,
184
+ timestep: torch.LongTensor,
185
+ controlnet_cond: torch.Tensor,
186
+ conditioning_scale: float = 1.0,
187
+ encoder_attention_mask: Optional[torch.Tensor] = None,
188
+ attention_mask: Optional[torch.Tensor] = None,
189
+ attention_kwargs: Optional[Dict[str, Any]] = None,
190
+ return_dict: bool = True,
191
+ ) -> Union[Tuple[torch.Tensor, ...], Transformer2DModelOutput]:
192
+ if attention_kwargs is not None:
193
+ attention_kwargs = attention_kwargs.copy()
194
+ lora_scale = attention_kwargs.pop("scale", 1.0)
195
+ else:
196
+ lora_scale = 1.0
197
+
198
+ if USE_PEFT_BACKEND:
199
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
200
+ scale_lora_layers(self, lora_scale)
201
+ else:
202
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
203
+ logger.warning(
204
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
205
+ )
206
+
207
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
208
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
209
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
210
+ # expects mask of shape:
211
+ # [batch, key_tokens]
212
+ # adds singleton query_tokens dimension:
213
+ # [batch, 1, key_tokens]
214
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
215
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
216
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
217
+ if attention_mask is not None and attention_mask.ndim == 2:
218
+ # assume that mask is expressed as:
219
+ # (1 = keep, 0 = discard)
220
+ # convert mask into a bias that can be added to attention scores:
221
+ # (keep = +0, discard = -10000.0)
222
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
223
+ attention_mask = attention_mask.unsqueeze(1)
224
+
225
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
226
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
227
+ encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
228
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
229
+
230
+ # 1. Input
231
+ batch_size, num_channels, height, width = hidden_states.shape
232
+ p = self.config.patch_size
233
+ post_patch_height, post_patch_width = height // p, width // p
234
+
235
+ hidden_states = self.patch_embed(hidden_states)
236
+ hidden_states = hidden_states + self.input_block(self.patch_embed(controlnet_cond.to(hidden_states.dtype)))
237
+
238
+ timestep, embedded_timestep = self.time_embed(
239
+ timestep, batch_size=batch_size, hidden_dtype=hidden_states.dtype
240
+ )
241
+
242
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
243
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
244
+
245
+ encoder_hidden_states = self.caption_norm(encoder_hidden_states)
246
+
247
+ # 2. Transformer blocks
248
+ block_res_samples = ()
249
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
250
+ for block in self.transformer_blocks:
251
+ hidden_states = self._gradient_checkpointing_func(
252
+ block,
253
+ hidden_states,
254
+ attention_mask,
255
+ encoder_hidden_states,
256
+ encoder_attention_mask,
257
+ timestep,
258
+ post_patch_height,
259
+ post_patch_width,
260
+ )
261
+ block_res_samples = block_res_samples + (hidden_states,)
262
+ else:
263
+ for block in self.transformer_blocks:
264
+ hidden_states = block(
265
+ hidden_states,
266
+ attention_mask,
267
+ encoder_hidden_states,
268
+ encoder_attention_mask,
269
+ timestep,
270
+ post_patch_height,
271
+ post_patch_width,
272
+ )
273
+ block_res_samples = block_res_samples + (hidden_states,)
274
+
275
+ # 3. ControlNet blocks
276
+ controlnet_block_res_samples = ()
277
+ for block_res_sample, controlnet_block in zip(block_res_samples, self.controlnet_blocks):
278
+ block_res_sample = controlnet_block(block_res_sample)
279
+ controlnet_block_res_samples = controlnet_block_res_samples + (block_res_sample,)
280
+
281
+ if USE_PEFT_BACKEND:
282
+ # remove `lora_scale` from each PEFT layer
283
+ unscale_lora_layers(self, lora_scale)
284
+
285
+ controlnet_block_res_samples = [sample * conditioning_scale for sample in controlnet_block_res_samples]
286
+
287
+ if not return_dict:
288
+ return (controlnet_block_res_samples,)
289
+
290
+ return SanaControlNetOutput(controlnet_block_samples=controlnet_block_res_samples)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_sd3.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI, The HuggingFace Team and The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from dataclasses import dataclass
17
+ from typing import Any, Dict, List, Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...loaders import FromOriginalModelMixin, PeftAdapterMixin
24
+ from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
25
+ from ..attention import JointTransformerBlock
26
+ from ..attention_processor import Attention, AttentionProcessor, FusedJointAttnProcessor2_0
27
+ from ..embeddings import CombinedTimestepTextProjEmbeddings, PatchEmbed
28
+ from ..modeling_outputs import Transformer2DModelOutput
29
+ from ..modeling_utils import ModelMixin
30
+ from ..transformers.transformer_sd3 import SD3SingleTransformerBlock
31
+ from .controlnet import BaseOutput, zero_module
32
+
33
+
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+
37
+ @dataclass
38
+ class SD3ControlNetOutput(BaseOutput):
39
+ controlnet_block_samples: Tuple[torch.Tensor]
40
+
41
+
42
+ class SD3ControlNetModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
43
+ r"""
44
+ ControlNet model for [Stable Diffusion 3](https://huggingface.co/papers/2403.03206).
45
+
46
+ Parameters:
47
+ sample_size (`int`, defaults to `128`):
48
+ The width/height of the latents. This is fixed during training since it is used to learn a number of
49
+ position embeddings.
50
+ patch_size (`int`, defaults to `2`):
51
+ Patch size to turn the input data into small patches.
52
+ in_channels (`int`, defaults to `16`):
53
+ The number of latent channels in the input.
54
+ num_layers (`int`, defaults to `18`):
55
+ The number of layers of transformer blocks to use.
56
+ attention_head_dim (`int`, defaults to `64`):
57
+ The number of channels in each head.
58
+ num_attention_heads (`int`, defaults to `18`):
59
+ The number of heads to use for multi-head attention.
60
+ joint_attention_dim (`int`, defaults to `4096`):
61
+ The embedding dimension to use for joint text-image attention.
62
+ caption_projection_dim (`int`, defaults to `1152`):
63
+ The embedding dimension of caption embeddings.
64
+ pooled_projection_dim (`int`, defaults to `2048`):
65
+ The embedding dimension of pooled text projections.
66
+ out_channels (`int`, defaults to `16`):
67
+ The number of latent channels in the output.
68
+ pos_embed_max_size (`int`, defaults to `96`):
69
+ The maximum latent height/width of positional embeddings.
70
+ extra_conditioning_channels (`int`, defaults to `0`):
71
+ The number of extra channels to use for conditioning for patch embedding.
72
+ dual_attention_layers (`Tuple[int, ...]`, defaults to `()`):
73
+ The number of dual-stream transformer blocks to use.
74
+ qk_norm (`str`, *optional*, defaults to `None`):
75
+ The normalization to use for query and key in the attention layer. If `None`, no normalization is used.
76
+ pos_embed_type (`str`, defaults to `"sincos"`):
77
+ The type of positional embedding to use. Choose between `"sincos"` and `None`.
78
+ use_pos_embed (`bool`, defaults to `True`):
79
+ Whether to use positional embeddings.
80
+ force_zeros_for_pooled_projection (`bool`, defaults to `True`):
81
+ Whether to force zeros for pooled projection embeddings. This is handled in the pipelines by reading the
82
+ config value of the ControlNet model.
83
+ """
84
+
85
+ _supports_gradient_checkpointing = True
86
+
87
+ @register_to_config
88
+ def __init__(
89
+ self,
90
+ sample_size: int = 128,
91
+ patch_size: int = 2,
92
+ in_channels: int = 16,
93
+ num_layers: int = 18,
94
+ attention_head_dim: int = 64,
95
+ num_attention_heads: int = 18,
96
+ joint_attention_dim: int = 4096,
97
+ caption_projection_dim: int = 1152,
98
+ pooled_projection_dim: int = 2048,
99
+ out_channels: int = 16,
100
+ pos_embed_max_size: int = 96,
101
+ extra_conditioning_channels: int = 0,
102
+ dual_attention_layers: Tuple[int, ...] = (),
103
+ qk_norm: Optional[str] = None,
104
+ pos_embed_type: Optional[str] = "sincos",
105
+ use_pos_embed: bool = True,
106
+ force_zeros_for_pooled_projection: bool = True,
107
+ ):
108
+ super().__init__()
109
+ default_out_channels = in_channels
110
+ self.out_channels = out_channels if out_channels is not None else default_out_channels
111
+ self.inner_dim = num_attention_heads * attention_head_dim
112
+
113
+ if use_pos_embed:
114
+ self.pos_embed = PatchEmbed(
115
+ height=sample_size,
116
+ width=sample_size,
117
+ patch_size=patch_size,
118
+ in_channels=in_channels,
119
+ embed_dim=self.inner_dim,
120
+ pos_embed_max_size=pos_embed_max_size,
121
+ pos_embed_type=pos_embed_type,
122
+ )
123
+ else:
124
+ self.pos_embed = None
125
+ self.time_text_embed = CombinedTimestepTextProjEmbeddings(
126
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
127
+ )
128
+ if joint_attention_dim is not None:
129
+ self.context_embedder = nn.Linear(joint_attention_dim, caption_projection_dim)
130
+
131
+ # `attention_head_dim` is doubled to account for the mixing.
132
+ # It needs to crafted when we get the actual checkpoints.
133
+ self.transformer_blocks = nn.ModuleList(
134
+ [
135
+ JointTransformerBlock(
136
+ dim=self.inner_dim,
137
+ num_attention_heads=num_attention_heads,
138
+ attention_head_dim=attention_head_dim,
139
+ context_pre_only=False,
140
+ qk_norm=qk_norm,
141
+ use_dual_attention=True if i in dual_attention_layers else False,
142
+ )
143
+ for i in range(num_layers)
144
+ ]
145
+ )
146
+ else:
147
+ self.context_embedder = None
148
+ self.transformer_blocks = nn.ModuleList(
149
+ [
150
+ SD3SingleTransformerBlock(
151
+ dim=self.inner_dim,
152
+ num_attention_heads=num_attention_heads,
153
+ attention_head_dim=attention_head_dim,
154
+ )
155
+ for _ in range(num_layers)
156
+ ]
157
+ )
158
+
159
+ # controlnet_blocks
160
+ self.controlnet_blocks = nn.ModuleList([])
161
+ for _ in range(len(self.transformer_blocks)):
162
+ controlnet_block = nn.Linear(self.inner_dim, self.inner_dim)
163
+ controlnet_block = zero_module(controlnet_block)
164
+ self.controlnet_blocks.append(controlnet_block)
165
+ pos_embed_input = PatchEmbed(
166
+ height=sample_size,
167
+ width=sample_size,
168
+ patch_size=patch_size,
169
+ in_channels=in_channels + extra_conditioning_channels,
170
+ embed_dim=self.inner_dim,
171
+ pos_embed_type=None,
172
+ )
173
+ self.pos_embed_input = zero_module(pos_embed_input)
174
+
175
+ self.gradient_checkpointing = False
176
+
177
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
178
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
179
+ """
180
+ Sets the attention processor to use [feed forward
181
+ chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
182
+
183
+ Parameters:
184
+ chunk_size (`int`, *optional*):
185
+ The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
186
+ over each tensor of dim=`dim`.
187
+ dim (`int`, *optional*, defaults to `0`):
188
+ The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
189
+ or dim=1 (sequence length).
190
+ """
191
+ if dim not in [0, 1]:
192
+ raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
193
+
194
+ # By default chunk size is 1
195
+ chunk_size = chunk_size or 1
196
+
197
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
198
+ if hasattr(module, "set_chunk_feed_forward"):
199
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
200
+
201
+ for child in module.children():
202
+ fn_recursive_feed_forward(child, chunk_size, dim)
203
+
204
+ for module in self.children():
205
+ fn_recursive_feed_forward(module, chunk_size, dim)
206
+
207
+ @property
208
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
209
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
210
+ r"""
211
+ Returns:
212
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
213
+ indexed by its weight name.
214
+ """
215
+ # set recursively
216
+ processors = {}
217
+
218
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
219
+ if hasattr(module, "get_processor"):
220
+ processors[f"{name}.processor"] = module.get_processor()
221
+
222
+ for sub_name, child in module.named_children():
223
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
224
+
225
+ return processors
226
+
227
+ for name, module in self.named_children():
228
+ fn_recursive_add_processors(name, module, processors)
229
+
230
+ return processors
231
+
232
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
233
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
234
+ r"""
235
+ Sets the attention processor to use to compute attention.
236
+
237
+ Parameters:
238
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
239
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
240
+ for **all** `Attention` layers.
241
+
242
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
243
+ processor. This is strongly recommended when setting trainable attention processors.
244
+
245
+ """
246
+ count = len(self.attn_processors.keys())
247
+
248
+ if isinstance(processor, dict) and len(processor) != count:
249
+ raise ValueError(
250
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
251
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
252
+ )
253
+
254
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
255
+ if hasattr(module, "set_processor"):
256
+ if not isinstance(processor, dict):
257
+ module.set_processor(processor)
258
+ else:
259
+ module.set_processor(processor.pop(f"{name}.processor"))
260
+
261
+ for sub_name, child in module.named_children():
262
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
263
+
264
+ for name, module in self.named_children():
265
+ fn_recursive_attn_processor(name, module, processor)
266
+
267
+ # Copied from diffusers.models.transformers.transformer_sd3.SD3Transformer2DModel.fuse_qkv_projections
268
+ def fuse_qkv_projections(self):
269
+ """
270
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
271
+ are fused. For cross-attention modules, key and value projection matrices are fused.
272
+
273
+ <Tip warning={true}>
274
+
275
+ This API is 🧪 experimental.
276
+
277
+ </Tip>
278
+ """
279
+ self.original_attn_processors = None
280
+
281
+ for _, attn_processor in self.attn_processors.items():
282
+ if "Added" in str(attn_processor.__class__.__name__):
283
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
284
+
285
+ self.original_attn_processors = self.attn_processors
286
+
287
+ for module in self.modules():
288
+ if isinstance(module, Attention):
289
+ module.fuse_projections(fuse=True)
290
+
291
+ self.set_attn_processor(FusedJointAttnProcessor2_0())
292
+
293
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
294
+ def unfuse_qkv_projections(self):
295
+ """Disables the fused QKV projection if enabled.
296
+
297
+ <Tip warning={true}>
298
+
299
+ This API is 🧪 experimental.
300
+
301
+ </Tip>
302
+
303
+ """
304
+ if self.original_attn_processors is not None:
305
+ self.set_attn_processor(self.original_attn_processors)
306
+
307
+ # Notes: This is for SD3.5 8b controlnet, which shares the pos_embed with the transformer
308
+ # we should have handled this in conversion script
309
+ def _get_pos_embed_from_transformer(self, transformer):
310
+ pos_embed = PatchEmbed(
311
+ height=transformer.config.sample_size,
312
+ width=transformer.config.sample_size,
313
+ patch_size=transformer.config.patch_size,
314
+ in_channels=transformer.config.in_channels,
315
+ embed_dim=transformer.inner_dim,
316
+ pos_embed_max_size=transformer.config.pos_embed_max_size,
317
+ )
318
+ pos_embed.load_state_dict(transformer.pos_embed.state_dict(), strict=True)
319
+ return pos_embed
320
+
321
+ @classmethod
322
+ def from_transformer(
323
+ cls, transformer, num_layers=12, num_extra_conditioning_channels=1, load_weights_from_transformer=True
324
+ ):
325
+ config = transformer.config
326
+ config["num_layers"] = num_layers or config.num_layers
327
+ config["extra_conditioning_channels"] = num_extra_conditioning_channels
328
+ controlnet = cls.from_config(config)
329
+
330
+ if load_weights_from_transformer:
331
+ controlnet.pos_embed.load_state_dict(transformer.pos_embed.state_dict())
332
+ controlnet.time_text_embed.load_state_dict(transformer.time_text_embed.state_dict())
333
+ controlnet.context_embedder.load_state_dict(transformer.context_embedder.state_dict())
334
+ controlnet.transformer_blocks.load_state_dict(transformer.transformer_blocks.state_dict(), strict=False)
335
+
336
+ controlnet.pos_embed_input = zero_module(controlnet.pos_embed_input)
337
+
338
+ return controlnet
339
+
340
+ def forward(
341
+ self,
342
+ hidden_states: torch.Tensor,
343
+ controlnet_cond: torch.Tensor,
344
+ conditioning_scale: float = 1.0,
345
+ encoder_hidden_states: torch.Tensor = None,
346
+ pooled_projections: torch.Tensor = None,
347
+ timestep: torch.LongTensor = None,
348
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
349
+ return_dict: bool = True,
350
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
351
+ """
352
+ The [`SD3Transformer2DModel`] forward method.
353
+
354
+ Args:
355
+ hidden_states (`torch.Tensor` of shape `(batch size, channel, height, width)`):
356
+ Input `hidden_states`.
357
+ controlnet_cond (`torch.Tensor`):
358
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
359
+ conditioning_scale (`float`, defaults to `1.0`):
360
+ The scale factor for ControlNet outputs.
361
+ encoder_hidden_states (`torch.Tensor` of shape `(batch size, sequence_len, embed_dims)`):
362
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
363
+ pooled_projections (`torch.Tensor` of shape `(batch_size, projection_dim)`): Embeddings projected
364
+ from the embeddings of input conditions.
365
+ timestep ( `torch.LongTensor`):
366
+ Used to indicate denoising step.
367
+ joint_attention_kwargs (`dict`, *optional*):
368
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
369
+ `self.processor` in
370
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
371
+ return_dict (`bool`, *optional*, defaults to `True`):
372
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
373
+ tuple.
374
+
375
+ Returns:
376
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
377
+ `tuple` where the first element is the sample tensor.
378
+ """
379
+ if joint_attention_kwargs is not None:
380
+ joint_attention_kwargs = joint_attention_kwargs.copy()
381
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
382
+ else:
383
+ lora_scale = 1.0
384
+
385
+ if USE_PEFT_BACKEND:
386
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
387
+ scale_lora_layers(self, lora_scale)
388
+ else:
389
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
390
+ logger.warning(
391
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
392
+ )
393
+
394
+ if self.pos_embed is not None and hidden_states.ndim != 4:
395
+ raise ValueError("hidden_states must be 4D when pos_embed is used")
396
+
397
+ # SD3.5 8b controlnet does not have a `pos_embed`,
398
+ # it use the `pos_embed` from the transformer to process input before passing to controlnet
399
+ elif self.pos_embed is None and hidden_states.ndim != 3:
400
+ raise ValueError("hidden_states must be 3D when pos_embed is not used")
401
+
402
+ if self.context_embedder is not None and encoder_hidden_states is None:
403
+ raise ValueError("encoder_hidden_states must be provided when context_embedder is used")
404
+ # SD3.5 8b controlnet does not have a `context_embedder`, it does not use `encoder_hidden_states`
405
+ elif self.context_embedder is None and encoder_hidden_states is not None:
406
+ raise ValueError("encoder_hidden_states should not be provided when context_embedder is not used")
407
+
408
+ if self.pos_embed is not None:
409
+ hidden_states = self.pos_embed(hidden_states) # takes care of adding positional embeddings too.
410
+
411
+ temb = self.time_text_embed(timestep, pooled_projections)
412
+
413
+ if self.context_embedder is not None:
414
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
415
+
416
+ # add
417
+ hidden_states = hidden_states + self.pos_embed_input(controlnet_cond)
418
+
419
+ block_res_samples = ()
420
+
421
+ for block in self.transformer_blocks:
422
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
423
+ if self.context_embedder is not None:
424
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
425
+ block,
426
+ hidden_states,
427
+ encoder_hidden_states,
428
+ temb,
429
+ )
430
+ else:
431
+ # SD3.5 8b controlnet use single transformer block, which does not use `encoder_hidden_states`
432
+ hidden_states = self._gradient_checkpointing_func(block, hidden_states, temb)
433
+
434
+ else:
435
+ if self.context_embedder is not None:
436
+ encoder_hidden_states, hidden_states = block(
437
+ hidden_states=hidden_states, encoder_hidden_states=encoder_hidden_states, temb=temb
438
+ )
439
+ else:
440
+ # SD3.5 8b controlnet use single transformer block, which does not use `encoder_hidden_states`
441
+ hidden_states = block(hidden_states, temb)
442
+
443
+ block_res_samples = block_res_samples + (hidden_states,)
444
+
445
+ controlnet_block_res_samples = ()
446
+ for block_res_sample, controlnet_block in zip(block_res_samples, self.controlnet_blocks):
447
+ block_res_sample = controlnet_block(block_res_sample)
448
+ controlnet_block_res_samples = controlnet_block_res_samples + (block_res_sample,)
449
+
450
+ # 6. scaling
451
+ controlnet_block_res_samples = [sample * conditioning_scale for sample in controlnet_block_res_samples]
452
+
453
+ if USE_PEFT_BACKEND:
454
+ # remove `lora_scale` from each PEFT layer
455
+ unscale_lora_layers(self, lora_scale)
456
+
457
+ if not return_dict:
458
+ return (controlnet_block_res_samples,)
459
+
460
+ return SD3ControlNetOutput(controlnet_block_samples=controlnet_block_res_samples)
461
+
462
+
463
+ class SD3MultiControlNetModel(ModelMixin):
464
+ r"""
465
+ `SD3ControlNetModel` wrapper class for Multi-SD3ControlNet
466
+
467
+ This module is a wrapper for multiple instances of the `SD3ControlNetModel`. The `forward()` API is designed to be
468
+ compatible with `SD3ControlNetModel`.
469
+
470
+ Args:
471
+ controlnets (`List[SD3ControlNetModel]`):
472
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
473
+ `SD3ControlNetModel` as a list.
474
+ """
475
+
476
+ def __init__(self, controlnets):
477
+ super().__init__()
478
+ self.nets = nn.ModuleList(controlnets)
479
+
480
+ def forward(
481
+ self,
482
+ hidden_states: torch.Tensor,
483
+ controlnet_cond: List[torch.tensor],
484
+ conditioning_scale: List[float],
485
+ pooled_projections: torch.Tensor,
486
+ encoder_hidden_states: torch.Tensor = None,
487
+ timestep: torch.LongTensor = None,
488
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
489
+ return_dict: bool = True,
490
+ ) -> Union[SD3ControlNetOutput, Tuple]:
491
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
492
+ block_samples = controlnet(
493
+ hidden_states=hidden_states,
494
+ timestep=timestep,
495
+ encoder_hidden_states=encoder_hidden_states,
496
+ pooled_projections=pooled_projections,
497
+ controlnet_cond=image,
498
+ conditioning_scale=scale,
499
+ joint_attention_kwargs=joint_attention_kwargs,
500
+ return_dict=return_dict,
501
+ )
502
+
503
+ # merge samples
504
+ if i == 0:
505
+ control_block_samples = block_samples
506
+ else:
507
+ control_block_samples = [
508
+ control_block_sample + block_sample
509
+ for control_block_sample, block_sample in zip(control_block_samples[0], block_samples[0])
510
+ ]
511
+ control_block_samples = (tuple(control_block_samples),)
512
+
513
+ return control_block_samples
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_sparsectrl.py ADDED
@@ -0,0 +1,785 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from dataclasses import dataclass
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+ from torch.nn import functional as F
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...loaders import FromOriginalModelMixin
24
+ from ...utils import BaseOutput, logging
25
+ from ..attention_processor import (
26
+ ADDED_KV_ATTENTION_PROCESSORS,
27
+ CROSS_ATTENTION_PROCESSORS,
28
+ AttentionProcessor,
29
+ AttnAddedKVProcessor,
30
+ AttnProcessor,
31
+ )
32
+ from ..embeddings import TimestepEmbedding, Timesteps
33
+ from ..modeling_utils import ModelMixin
34
+ from ..unets.unet_2d_blocks import UNetMidBlock2DCrossAttn
35
+ from ..unets.unet_2d_condition import UNet2DConditionModel
36
+ from ..unets.unet_motion_model import CrossAttnDownBlockMotion, DownBlockMotion
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ @dataclass
43
+ class SparseControlNetOutput(BaseOutput):
44
+ """
45
+ The output of [`SparseControlNetModel`].
46
+
47
+ Args:
48
+ down_block_res_samples (`tuple[torch.Tensor]`):
49
+ A tuple of downsample activations at different resolutions for each downsampling block. Each tensor should
50
+ be of shape `(batch_size, channel * resolution, height //resolution, width // resolution)`. Output can be
51
+ used to condition the original UNet's downsampling activations.
52
+ mid_down_block_re_sample (`torch.Tensor`):
53
+ The activation of the middle block (the lowest sample resolution). Each tensor should be of shape
54
+ `(batch_size, channel * lowest_resolution, height // lowest_resolution, width // lowest_resolution)`.
55
+ Output can be used to condition the original UNet's middle block activation.
56
+ """
57
+
58
+ down_block_res_samples: Tuple[torch.Tensor]
59
+ mid_block_res_sample: torch.Tensor
60
+
61
+
62
+ class SparseControlNetConditioningEmbedding(nn.Module):
63
+ def __init__(
64
+ self,
65
+ conditioning_embedding_channels: int,
66
+ conditioning_channels: int = 3,
67
+ block_out_channels: Tuple[int, ...] = (16, 32, 96, 256),
68
+ ):
69
+ super().__init__()
70
+
71
+ self.conv_in = nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
72
+ self.blocks = nn.ModuleList([])
73
+
74
+ for i in range(len(block_out_channels) - 1):
75
+ channel_in = block_out_channels[i]
76
+ channel_out = block_out_channels[i + 1]
77
+ self.blocks.append(nn.Conv2d(channel_in, channel_in, kernel_size=3, padding=1))
78
+ self.blocks.append(nn.Conv2d(channel_in, channel_out, kernel_size=3, padding=1, stride=2))
79
+
80
+ self.conv_out = zero_module(
81
+ nn.Conv2d(block_out_channels[-1], conditioning_embedding_channels, kernel_size=3, padding=1)
82
+ )
83
+
84
+ def forward(self, conditioning: torch.Tensor) -> torch.Tensor:
85
+ embedding = self.conv_in(conditioning)
86
+ embedding = F.silu(embedding)
87
+
88
+ for block in self.blocks:
89
+ embedding = block(embedding)
90
+ embedding = F.silu(embedding)
91
+
92
+ embedding = self.conv_out(embedding)
93
+ return embedding
94
+
95
+
96
+ class SparseControlNetModel(ModelMixin, ConfigMixin, FromOriginalModelMixin):
97
+ """
98
+ A SparseControlNet model as described in [SparseCtrl: Adding Sparse Controls to Text-to-Video Diffusion
99
+ Models](https://arxiv.org/abs/2311.16933).
100
+
101
+ Args:
102
+ in_channels (`int`, defaults to 4):
103
+ The number of channels in the input sample.
104
+ conditioning_channels (`int`, defaults to 4):
105
+ The number of input channels in the controlnet conditional embedding module. If
106
+ `concat_condition_embedding` is True, the value provided here is incremented by 1.
107
+ flip_sin_to_cos (`bool`, defaults to `True`):
108
+ Whether to flip the sin to cos in the time embedding.
109
+ freq_shift (`int`, defaults to 0):
110
+ The frequency shift to apply to the time embedding.
111
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
112
+ The tuple of downsample blocks to use.
113
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
114
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
115
+ The tuple of output channels for each block.
116
+ layers_per_block (`int`, defaults to 2):
117
+ The number of layers per block.
118
+ downsample_padding (`int`, defaults to 1):
119
+ The padding to use for the downsampling convolution.
120
+ mid_block_scale_factor (`float`, defaults to 1):
121
+ The scale factor to use for the mid block.
122
+ act_fn (`str`, defaults to "silu"):
123
+ The activation function to use.
124
+ norm_num_groups (`int`, *optional*, defaults to 32):
125
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
126
+ in post-processing.
127
+ norm_eps (`float`, defaults to 1e-5):
128
+ The epsilon to use for the normalization.
129
+ cross_attention_dim (`int`, defaults to 1280):
130
+ The dimension of the cross attention features.
131
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
132
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
133
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
134
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
135
+ transformer_layers_per_mid_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
136
+ The number of transformer layers to use in each layer in the middle block.
137
+ attention_head_dim (`int` or `Tuple[int]`, defaults to 8):
138
+ The dimension of the attention heads.
139
+ num_attention_heads (`int` or `Tuple[int]`, *optional*):
140
+ The number of heads to use for multi-head attention.
141
+ use_linear_projection (`bool`, defaults to `False`):
142
+ upcast_attention (`bool`, defaults to `False`):
143
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
144
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
145
+ conditioning_embedding_out_channels (`Tuple[int]`, defaults to `(16, 32, 96, 256)`):
146
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
147
+ global_pool_conditions (`bool`, defaults to `False`):
148
+ TODO(Patrick) - unused parameter
149
+ controlnet_conditioning_channel_order (`str`, defaults to `rgb`):
150
+ motion_max_seq_length (`int`, defaults to `32`):
151
+ The maximum sequence length to use in the motion module.
152
+ motion_num_attention_heads (`int` or `Tuple[int]`, defaults to `8`):
153
+ The number of heads to use in each attention layer of the motion module.
154
+ concat_conditioning_mask (`bool`, defaults to `True`):
155
+ use_simplified_condition_embedding (`bool`, defaults to `True`):
156
+ """
157
+
158
+ _supports_gradient_checkpointing = True
159
+
160
+ @register_to_config
161
+ def __init__(
162
+ self,
163
+ in_channels: int = 4,
164
+ conditioning_channels: int = 4,
165
+ flip_sin_to_cos: bool = True,
166
+ freq_shift: int = 0,
167
+ down_block_types: Tuple[str, ...] = (
168
+ "CrossAttnDownBlockMotion",
169
+ "CrossAttnDownBlockMotion",
170
+ "CrossAttnDownBlockMotion",
171
+ "DownBlockMotion",
172
+ ),
173
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
174
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
175
+ layers_per_block: int = 2,
176
+ downsample_padding: int = 1,
177
+ mid_block_scale_factor: float = 1,
178
+ act_fn: str = "silu",
179
+ norm_num_groups: Optional[int] = 32,
180
+ norm_eps: float = 1e-5,
181
+ cross_attention_dim: int = 768,
182
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
183
+ transformer_layers_per_mid_block: Optional[Union[int, Tuple[int]]] = None,
184
+ temporal_transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
185
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
186
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
187
+ use_linear_projection: bool = False,
188
+ upcast_attention: bool = False,
189
+ resnet_time_scale_shift: str = "default",
190
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
191
+ global_pool_conditions: bool = False,
192
+ controlnet_conditioning_channel_order: str = "rgb",
193
+ motion_max_seq_length: int = 32,
194
+ motion_num_attention_heads: int = 8,
195
+ concat_conditioning_mask: bool = True,
196
+ use_simplified_condition_embedding: bool = True,
197
+ ):
198
+ super().__init__()
199
+ self.use_simplified_condition_embedding = use_simplified_condition_embedding
200
+
201
+ # If `num_attention_heads` is not defined (which is the case for most models)
202
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
203
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
204
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
205
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
206
+ # which is why we correct for the naming here.
207
+ num_attention_heads = num_attention_heads or attention_head_dim
208
+
209
+ # Check inputs
210
+ if len(block_out_channels) != len(down_block_types):
211
+ raise ValueError(
212
+ 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}."
213
+ )
214
+
215
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
216
+ raise ValueError(
217
+ 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}."
218
+ )
219
+
220
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
221
+ raise ValueError(
222
+ 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}."
223
+ )
224
+
225
+ if isinstance(transformer_layers_per_block, int):
226
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
227
+ if isinstance(temporal_transformer_layers_per_block, int):
228
+ temporal_transformer_layers_per_block = [temporal_transformer_layers_per_block] * len(down_block_types)
229
+
230
+ # input
231
+ conv_in_kernel = 3
232
+ conv_in_padding = (conv_in_kernel - 1) // 2
233
+ self.conv_in = nn.Conv2d(
234
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
235
+ )
236
+
237
+ if concat_conditioning_mask:
238
+ conditioning_channels = conditioning_channels + 1
239
+
240
+ self.concat_conditioning_mask = concat_conditioning_mask
241
+
242
+ # control net conditioning embedding
243
+ if use_simplified_condition_embedding:
244
+ self.controlnet_cond_embedding = zero_module(
245
+ nn.Conv2d(conditioning_channels, block_out_channels[0], kernel_size=3, padding=1)
246
+ )
247
+ else:
248
+ self.controlnet_cond_embedding = SparseControlNetConditioningEmbedding(
249
+ conditioning_embedding_channels=block_out_channels[0],
250
+ block_out_channels=conditioning_embedding_out_channels,
251
+ conditioning_channels=conditioning_channels,
252
+ )
253
+
254
+ # time
255
+ time_embed_dim = block_out_channels[0] * 4
256
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
257
+ timestep_input_dim = block_out_channels[0]
258
+
259
+ self.time_embedding = TimestepEmbedding(
260
+ timestep_input_dim,
261
+ time_embed_dim,
262
+ act_fn=act_fn,
263
+ )
264
+
265
+ self.down_blocks = nn.ModuleList([])
266
+ self.controlnet_down_blocks = nn.ModuleList([])
267
+
268
+ if isinstance(cross_attention_dim, int):
269
+ cross_attention_dim = (cross_attention_dim,) * len(down_block_types)
270
+
271
+ if isinstance(only_cross_attention, bool):
272
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
273
+
274
+ if isinstance(attention_head_dim, int):
275
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
276
+
277
+ if isinstance(num_attention_heads, int):
278
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
279
+
280
+ if isinstance(motion_num_attention_heads, int):
281
+ motion_num_attention_heads = (motion_num_attention_heads,) * len(down_block_types)
282
+
283
+ # down
284
+ output_channel = block_out_channels[0]
285
+
286
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
287
+ controlnet_block = zero_module(controlnet_block)
288
+ self.controlnet_down_blocks.append(controlnet_block)
289
+
290
+ for i, down_block_type in enumerate(down_block_types):
291
+ input_channel = output_channel
292
+ output_channel = block_out_channels[i]
293
+ is_final_block = i == len(block_out_channels) - 1
294
+
295
+ if down_block_type == "CrossAttnDownBlockMotion":
296
+ down_block = CrossAttnDownBlockMotion(
297
+ in_channels=input_channel,
298
+ out_channels=output_channel,
299
+ temb_channels=time_embed_dim,
300
+ dropout=0,
301
+ num_layers=layers_per_block,
302
+ transformer_layers_per_block=transformer_layers_per_block[i],
303
+ resnet_eps=norm_eps,
304
+ resnet_time_scale_shift=resnet_time_scale_shift,
305
+ resnet_act_fn=act_fn,
306
+ resnet_groups=norm_num_groups,
307
+ resnet_pre_norm=True,
308
+ num_attention_heads=num_attention_heads[i],
309
+ cross_attention_dim=cross_attention_dim[i],
310
+ add_downsample=not is_final_block,
311
+ dual_cross_attention=False,
312
+ use_linear_projection=use_linear_projection,
313
+ only_cross_attention=only_cross_attention[i],
314
+ upcast_attention=upcast_attention,
315
+ temporal_num_attention_heads=motion_num_attention_heads[i],
316
+ temporal_max_seq_length=motion_max_seq_length,
317
+ temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
318
+ temporal_double_self_attention=False,
319
+ )
320
+ elif down_block_type == "DownBlockMotion":
321
+ down_block = DownBlockMotion(
322
+ in_channels=input_channel,
323
+ out_channels=output_channel,
324
+ temb_channels=time_embed_dim,
325
+ dropout=0,
326
+ num_layers=layers_per_block,
327
+ resnet_eps=norm_eps,
328
+ resnet_time_scale_shift=resnet_time_scale_shift,
329
+ resnet_act_fn=act_fn,
330
+ resnet_groups=norm_num_groups,
331
+ resnet_pre_norm=True,
332
+ add_downsample=not is_final_block,
333
+ temporal_num_attention_heads=motion_num_attention_heads[i],
334
+ temporal_max_seq_length=motion_max_seq_length,
335
+ temporal_transformer_layers_per_block=temporal_transformer_layers_per_block[i],
336
+ temporal_double_self_attention=False,
337
+ )
338
+ else:
339
+ raise ValueError(
340
+ "Invalid `block_type` encountered. Must be one of `CrossAttnDownBlockMotion` or `DownBlockMotion`"
341
+ )
342
+
343
+ self.down_blocks.append(down_block)
344
+
345
+ for _ in range(layers_per_block):
346
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
347
+ controlnet_block = zero_module(controlnet_block)
348
+ self.controlnet_down_blocks.append(controlnet_block)
349
+
350
+ if not is_final_block:
351
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
352
+ controlnet_block = zero_module(controlnet_block)
353
+ self.controlnet_down_blocks.append(controlnet_block)
354
+
355
+ # mid
356
+ mid_block_channels = block_out_channels[-1]
357
+
358
+ controlnet_block = nn.Conv2d(mid_block_channels, mid_block_channels, kernel_size=1)
359
+ controlnet_block = zero_module(controlnet_block)
360
+ self.controlnet_mid_block = controlnet_block
361
+
362
+ if transformer_layers_per_mid_block is None:
363
+ transformer_layers_per_mid_block = (
364
+ transformer_layers_per_block[-1] if isinstance(transformer_layers_per_block[-1], int) else 1
365
+ )
366
+
367
+ self.mid_block = UNetMidBlock2DCrossAttn(
368
+ in_channels=mid_block_channels,
369
+ temb_channels=time_embed_dim,
370
+ dropout=0,
371
+ num_layers=1,
372
+ transformer_layers_per_block=transformer_layers_per_mid_block,
373
+ resnet_eps=norm_eps,
374
+ resnet_time_scale_shift=resnet_time_scale_shift,
375
+ resnet_act_fn=act_fn,
376
+ resnet_groups=norm_num_groups,
377
+ resnet_pre_norm=True,
378
+ num_attention_heads=num_attention_heads[-1],
379
+ output_scale_factor=mid_block_scale_factor,
380
+ cross_attention_dim=cross_attention_dim[-1],
381
+ dual_cross_attention=False,
382
+ use_linear_projection=use_linear_projection,
383
+ upcast_attention=upcast_attention,
384
+ attention_type="default",
385
+ )
386
+
387
+ @classmethod
388
+ def from_unet(
389
+ cls,
390
+ unet: UNet2DConditionModel,
391
+ controlnet_conditioning_channel_order: str = "rgb",
392
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
393
+ load_weights_from_unet: bool = True,
394
+ conditioning_channels: int = 3,
395
+ ) -> "SparseControlNetModel":
396
+ r"""
397
+ Instantiate a [`SparseControlNetModel`] from [`UNet2DConditionModel`].
398
+
399
+ Parameters:
400
+ unet (`UNet2DConditionModel`):
401
+ The UNet model weights to copy to the [`SparseControlNetModel`]. All configuration options are also
402
+ copied where applicable.
403
+ """
404
+ transformer_layers_per_block = (
405
+ unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
406
+ )
407
+ down_block_types = unet.config.down_block_types
408
+
409
+ for i in range(len(down_block_types)):
410
+ if "CrossAttn" in down_block_types[i]:
411
+ down_block_types[i] = "CrossAttnDownBlockMotion"
412
+ elif "Down" in down_block_types[i]:
413
+ down_block_types[i] = "DownBlockMotion"
414
+ else:
415
+ raise ValueError("Invalid `block_type` encountered. Must be a cross-attention or down block")
416
+
417
+ controlnet = cls(
418
+ in_channels=unet.config.in_channels,
419
+ conditioning_channels=conditioning_channels,
420
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
421
+ freq_shift=unet.config.freq_shift,
422
+ down_block_types=unet.config.down_block_types,
423
+ only_cross_attention=unet.config.only_cross_attention,
424
+ block_out_channels=unet.config.block_out_channels,
425
+ layers_per_block=unet.config.layers_per_block,
426
+ downsample_padding=unet.config.downsample_padding,
427
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
428
+ act_fn=unet.config.act_fn,
429
+ norm_num_groups=unet.config.norm_num_groups,
430
+ norm_eps=unet.config.norm_eps,
431
+ cross_attention_dim=unet.config.cross_attention_dim,
432
+ transformer_layers_per_block=transformer_layers_per_block,
433
+ attention_head_dim=unet.config.attention_head_dim,
434
+ num_attention_heads=unet.config.num_attention_heads,
435
+ use_linear_projection=unet.config.use_linear_projection,
436
+ upcast_attention=unet.config.upcast_attention,
437
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
438
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
439
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
440
+ )
441
+
442
+ if load_weights_from_unet:
443
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict(), strict=False)
444
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict(), strict=False)
445
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict(), strict=False)
446
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict(), strict=False)
447
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict(), strict=False)
448
+
449
+ return controlnet
450
+
451
+ @property
452
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
453
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
454
+ r"""
455
+ Returns:
456
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
457
+ indexed by its weight name.
458
+ """
459
+ # set recursively
460
+ processors = {}
461
+
462
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
463
+ if hasattr(module, "get_processor"):
464
+ processors[f"{name}.processor"] = module.get_processor()
465
+
466
+ for sub_name, child in module.named_children():
467
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
468
+
469
+ return processors
470
+
471
+ for name, module in self.named_children():
472
+ fn_recursive_add_processors(name, module, processors)
473
+
474
+ return processors
475
+
476
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
477
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
478
+ r"""
479
+ Sets the attention processor to use to compute attention.
480
+
481
+ Parameters:
482
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
483
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
484
+ for **all** `Attention` layers.
485
+
486
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
487
+ processor. This is strongly recommended when setting trainable attention processors.
488
+
489
+ """
490
+ count = len(self.attn_processors.keys())
491
+
492
+ if isinstance(processor, dict) and len(processor) != count:
493
+ raise ValueError(
494
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
495
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
496
+ )
497
+
498
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
499
+ if hasattr(module, "set_processor"):
500
+ if not isinstance(processor, dict):
501
+ module.set_processor(processor)
502
+ else:
503
+ module.set_processor(processor.pop(f"{name}.processor"))
504
+
505
+ for sub_name, child in module.named_children():
506
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
507
+
508
+ for name, module in self.named_children():
509
+ fn_recursive_attn_processor(name, module, processor)
510
+
511
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
512
+ def set_default_attn_processor(self):
513
+ """
514
+ Disables custom attention processors and sets the default attention implementation.
515
+ """
516
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
517
+ processor = AttnAddedKVProcessor()
518
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
519
+ processor = AttnProcessor()
520
+ else:
521
+ raise ValueError(
522
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
523
+ )
524
+
525
+ self.set_attn_processor(processor)
526
+
527
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
528
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
529
+ r"""
530
+ Enable sliced attention computation.
531
+
532
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
533
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
534
+
535
+ Args:
536
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
537
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
538
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
539
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
540
+ must be a multiple of `slice_size`.
541
+ """
542
+ sliceable_head_dims = []
543
+
544
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
545
+ if hasattr(module, "set_attention_slice"):
546
+ sliceable_head_dims.append(module.sliceable_head_dim)
547
+
548
+ for child in module.children():
549
+ fn_recursive_retrieve_sliceable_dims(child)
550
+
551
+ # retrieve number of attention layers
552
+ for module in self.children():
553
+ fn_recursive_retrieve_sliceable_dims(module)
554
+
555
+ num_sliceable_layers = len(sliceable_head_dims)
556
+
557
+ if slice_size == "auto":
558
+ # half the attention head size is usually a good trade-off between
559
+ # speed and memory
560
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
561
+ elif slice_size == "max":
562
+ # make smallest slice possible
563
+ slice_size = num_sliceable_layers * [1]
564
+
565
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
566
+
567
+ if len(slice_size) != len(sliceable_head_dims):
568
+ raise ValueError(
569
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
570
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
571
+ )
572
+
573
+ for i in range(len(slice_size)):
574
+ size = slice_size[i]
575
+ dim = sliceable_head_dims[i]
576
+ if size is not None and size > dim:
577
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
578
+
579
+ # Recursively walk through all the children.
580
+ # Any children which exposes the set_attention_slice method
581
+ # gets the message
582
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
583
+ if hasattr(module, "set_attention_slice"):
584
+ module.set_attention_slice(slice_size.pop())
585
+
586
+ for child in module.children():
587
+ fn_recursive_set_attention_slice(child, slice_size)
588
+
589
+ reversed_slice_size = list(reversed(slice_size))
590
+ for module in self.children():
591
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
592
+
593
+ def forward(
594
+ self,
595
+ sample: torch.Tensor,
596
+ timestep: Union[torch.Tensor, float, int],
597
+ encoder_hidden_states: torch.Tensor,
598
+ controlnet_cond: torch.Tensor,
599
+ conditioning_scale: float = 1.0,
600
+ timestep_cond: Optional[torch.Tensor] = None,
601
+ attention_mask: Optional[torch.Tensor] = None,
602
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
603
+ conditioning_mask: Optional[torch.Tensor] = None,
604
+ guess_mode: bool = False,
605
+ return_dict: bool = True,
606
+ ) -> Union[SparseControlNetOutput, Tuple[Tuple[torch.Tensor, ...], torch.Tensor]]:
607
+ """
608
+ The [`SparseControlNetModel`] forward method.
609
+
610
+ Args:
611
+ sample (`torch.Tensor`):
612
+ The noisy input tensor.
613
+ timestep (`Union[torch.Tensor, float, int]`):
614
+ The number of timesteps to denoise an input.
615
+ encoder_hidden_states (`torch.Tensor`):
616
+ The encoder hidden states.
617
+ controlnet_cond (`torch.Tensor`):
618
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
619
+ conditioning_scale (`float`, defaults to `1.0`):
620
+ The scale factor for ControlNet outputs.
621
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
622
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
623
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
624
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
625
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
626
+ embeddings.
627
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
628
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
629
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
630
+ negative values to the attention scores corresponding to "discard" tokens.
631
+ added_cond_kwargs (`dict`):
632
+ Additional conditions for the Stable Diffusion XL UNet.
633
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
634
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
635
+ guess_mode (`bool`, defaults to `False`):
636
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
637
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
638
+ return_dict (`bool`, defaults to `True`):
639
+ Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
640
+ Returns:
641
+ [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
642
+ If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
643
+ returned where the first element is the sample tensor.
644
+ """
645
+ sample_batch_size, sample_channels, sample_num_frames, sample_height, sample_width = sample.shape
646
+ sample = torch.zeros_like(sample)
647
+
648
+ # check channel order
649
+ channel_order = self.config.controlnet_conditioning_channel_order
650
+
651
+ if channel_order == "rgb":
652
+ # in rgb order by default
653
+ ...
654
+ elif channel_order == "bgr":
655
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
656
+ else:
657
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
658
+
659
+ # prepare attention_mask
660
+ if attention_mask is not None:
661
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
662
+ attention_mask = attention_mask.unsqueeze(1)
663
+
664
+ # 1. time
665
+ timesteps = timestep
666
+ if not torch.is_tensor(timesteps):
667
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
668
+ # This would be a good case for the `match` statement (Python 3.10+)
669
+ is_mps = sample.device.type == "mps"
670
+ is_npu = sample.device.type == "npu"
671
+ if isinstance(timestep, float):
672
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
673
+ else:
674
+ dtype = torch.int32 if (is_mps or is_npu) else torch.int64
675
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
676
+ elif len(timesteps.shape) == 0:
677
+ timesteps = timesteps[None].to(sample.device)
678
+
679
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
680
+ timesteps = timesteps.expand(sample.shape[0])
681
+
682
+ t_emb = self.time_proj(timesteps)
683
+
684
+ # timesteps does not contain any weights and will always return f32 tensors
685
+ # but time_embedding might actually be running in fp16. so we need to cast here.
686
+ # there might be better ways to encapsulate this.
687
+ t_emb = t_emb.to(dtype=sample.dtype)
688
+
689
+ emb = self.time_embedding(t_emb, timestep_cond)
690
+ emb = emb.repeat_interleave(sample_num_frames, dim=0, output_size=emb.shape[0] * sample_num_frames)
691
+
692
+ # 2. pre-process
693
+ batch_size, channels, num_frames, height, width = sample.shape
694
+
695
+ sample = sample.permute(0, 2, 1, 3, 4).reshape(batch_size * num_frames, channels, height, width)
696
+ sample = self.conv_in(sample)
697
+
698
+ batch_frames, channels, height, width = sample.shape
699
+ sample = sample[:, None].reshape(sample_batch_size, sample_num_frames, channels, height, width)
700
+
701
+ if self.concat_conditioning_mask:
702
+ controlnet_cond = torch.cat([controlnet_cond, conditioning_mask], dim=1)
703
+
704
+ batch_size, channels, num_frames, height, width = controlnet_cond.shape
705
+ controlnet_cond = controlnet_cond.permute(0, 2, 1, 3, 4).reshape(
706
+ batch_size * num_frames, channels, height, width
707
+ )
708
+ controlnet_cond = self.controlnet_cond_embedding(controlnet_cond)
709
+ batch_frames, channels, height, width = controlnet_cond.shape
710
+ controlnet_cond = controlnet_cond[:, None].reshape(batch_size, num_frames, channels, height, width)
711
+
712
+ sample = sample + controlnet_cond
713
+
714
+ batch_size, num_frames, channels, height, width = sample.shape
715
+ sample = sample.reshape(sample_batch_size * sample_num_frames, channels, height, width)
716
+
717
+ # 3. down
718
+ down_block_res_samples = (sample,)
719
+ for downsample_block in self.down_blocks:
720
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
721
+ sample, res_samples = downsample_block(
722
+ hidden_states=sample,
723
+ temb=emb,
724
+ encoder_hidden_states=encoder_hidden_states,
725
+ attention_mask=attention_mask,
726
+ num_frames=num_frames,
727
+ cross_attention_kwargs=cross_attention_kwargs,
728
+ )
729
+ else:
730
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb, num_frames=num_frames)
731
+
732
+ down_block_res_samples += res_samples
733
+
734
+ # 4. mid
735
+ if self.mid_block is not None:
736
+ if hasattr(self.mid_block, "has_cross_attention") and self.mid_block.has_cross_attention:
737
+ sample = self.mid_block(
738
+ sample,
739
+ emb,
740
+ encoder_hidden_states=encoder_hidden_states,
741
+ attention_mask=attention_mask,
742
+ cross_attention_kwargs=cross_attention_kwargs,
743
+ )
744
+ else:
745
+ sample = self.mid_block(sample, emb)
746
+
747
+ # 5. Control net blocks
748
+ controlnet_down_block_res_samples = ()
749
+
750
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
751
+ down_block_res_sample = controlnet_block(down_block_res_sample)
752
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
753
+
754
+ down_block_res_samples = controlnet_down_block_res_samples
755
+ mid_block_res_sample = self.controlnet_mid_block(sample)
756
+
757
+ # 6. scaling
758
+ if guess_mode and not self.config.global_pool_conditions:
759
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
760
+ scales = scales * conditioning_scale
761
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
762
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
763
+ else:
764
+ down_block_res_samples = [sample * conditioning_scale for sample in down_block_res_samples]
765
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale
766
+
767
+ if self.config.global_pool_conditions:
768
+ down_block_res_samples = [
769
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
770
+ ]
771
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
772
+
773
+ if not return_dict:
774
+ return (down_block_res_samples, mid_block_res_sample)
775
+
776
+ return SparseControlNetOutput(
777
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
778
+ )
779
+
780
+
781
+ # Copied from diffusers.models.controlnets.controlnet.zero_module
782
+ def zero_module(module: nn.Module) -> nn.Module:
783
+ for p in module.parameters():
784
+ nn.init.zeros_(p)
785
+ return module
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_union.py ADDED
@@ -0,0 +1,841 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Dict, List, Optional, Tuple, Union
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ...configuration_utils import ConfigMixin, register_to_config
20
+ from ...loaders.single_file_model import FromOriginalModelMixin
21
+ from ...utils import logging
22
+ from ..attention_processor import (
23
+ ADDED_KV_ATTENTION_PROCESSORS,
24
+ CROSS_ATTENTION_PROCESSORS,
25
+ AttentionProcessor,
26
+ AttnAddedKVProcessor,
27
+ AttnProcessor,
28
+ )
29
+ from ..embeddings import TextImageTimeEmbedding, TextTimeEmbedding, TimestepEmbedding, Timesteps
30
+ from ..modeling_utils import ModelMixin
31
+ from ..unets.unet_2d_blocks import (
32
+ UNetMidBlock2DCrossAttn,
33
+ get_down_block,
34
+ )
35
+ from ..unets.unet_2d_condition import UNet2DConditionModel
36
+ from .controlnet import ControlNetConditioningEmbedding, ControlNetOutput, zero_module
37
+
38
+
39
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
40
+
41
+
42
+ class QuickGELU(nn.Module):
43
+ """
44
+ Applies GELU approximation that is fast but somewhat inaccurate. See: https://github.com/hendrycks/GELUs
45
+ """
46
+
47
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
48
+ return input * torch.sigmoid(1.702 * input)
49
+
50
+
51
+ class ResidualAttentionMlp(nn.Module):
52
+ def __init__(self, d_model: int):
53
+ super().__init__()
54
+ self.c_fc = nn.Linear(d_model, d_model * 4)
55
+ self.gelu = QuickGELU()
56
+ self.c_proj = nn.Linear(d_model * 4, d_model)
57
+
58
+ def forward(self, x: torch.Tensor):
59
+ x = self.c_fc(x)
60
+ x = self.gelu(x)
61
+ x = self.c_proj(x)
62
+ return x
63
+
64
+
65
+ class ResidualAttentionBlock(nn.Module):
66
+ def __init__(self, d_model: int, n_head: int, attn_mask: torch.Tensor = None):
67
+ super().__init__()
68
+ self.attn = nn.MultiheadAttention(d_model, n_head)
69
+ self.ln_1 = nn.LayerNorm(d_model)
70
+ self.mlp = ResidualAttentionMlp(d_model)
71
+ self.ln_2 = nn.LayerNorm(d_model)
72
+ self.attn_mask = attn_mask
73
+
74
+ def attention(self, x: torch.Tensor):
75
+ self.attn_mask = self.attn_mask.to(dtype=x.dtype, device=x.device) if self.attn_mask is not None else None
76
+ return self.attn(x, x, x, need_weights=False, attn_mask=self.attn_mask)[0]
77
+
78
+ def forward(self, x: torch.Tensor):
79
+ x = x + self.attention(self.ln_1(x))
80
+ x = x + self.mlp(self.ln_2(x))
81
+ return x
82
+
83
+
84
+ class ControlNetUnionModel(ModelMixin, ConfigMixin, FromOriginalModelMixin):
85
+ """
86
+ A ControlNetUnion model.
87
+
88
+ Args:
89
+ in_channels (`int`, defaults to 4):
90
+ The number of channels in the input sample.
91
+ flip_sin_to_cos (`bool`, defaults to `True`):
92
+ Whether to flip the sin to cos in the time embedding.
93
+ freq_shift (`int`, defaults to 0):
94
+ The frequency shift to apply to the time embedding.
95
+ down_block_types (`tuple[str]`, defaults to `("CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D")`):
96
+ The tuple of downsample blocks to use.
97
+ only_cross_attention (`Union[bool, Tuple[bool]]`, defaults to `False`):
98
+ block_out_channels (`tuple[int]`, defaults to `(320, 640, 1280, 1280)`):
99
+ The tuple of output channels for each block.
100
+ layers_per_block (`int`, defaults to 2):
101
+ The number of layers per block.
102
+ downsample_padding (`int`, defaults to 1):
103
+ The padding to use for the downsampling convolution.
104
+ mid_block_scale_factor (`float`, defaults to 1):
105
+ The scale factor to use for the mid block.
106
+ act_fn (`str`, defaults to "silu"):
107
+ The activation function to use.
108
+ norm_num_groups (`int`, *optional*, defaults to 32):
109
+ The number of groups to use for the normalization. If None, normalization and activation layers is skipped
110
+ in post-processing.
111
+ norm_eps (`float`, defaults to 1e-5):
112
+ The epsilon to use for the normalization.
113
+ cross_attention_dim (`int`, defaults to 1280):
114
+ The dimension of the cross attention features.
115
+ transformer_layers_per_block (`int` or `Tuple[int]`, *optional*, defaults to 1):
116
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
117
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.CrossAttnUpBlock2D`],
118
+ [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
119
+ encoder_hid_dim (`int`, *optional*, defaults to None):
120
+ If `encoder_hid_dim_type` is defined, `encoder_hidden_states` will be projected from `encoder_hid_dim`
121
+ dimension to `cross_attention_dim`.
122
+ encoder_hid_dim_type (`str`, *optional*, defaults to `None`):
123
+ If given, the `encoder_hidden_states` and potentially other embeddings are down-projected to text
124
+ embeddings of dimension `cross_attention` according to `encoder_hid_dim_type`.
125
+ attention_head_dim (`Union[int, Tuple[int]]`, defaults to 8):
126
+ The dimension of the attention heads.
127
+ use_linear_projection (`bool`, defaults to `False`):
128
+ class_embed_type (`str`, *optional*, defaults to `None`):
129
+ The type of class embedding to use which is ultimately summed with the time embeddings. Choose from None,
130
+ `"timestep"`, `"identity"`, `"projection"`, or `"simple_projection"`.
131
+ addition_embed_type (`str`, *optional*, defaults to `None`):
132
+ Configures an optional embedding which will be summed with the time embeddings. Choose from `None` or
133
+ "text". "text" will use the `TextTimeEmbedding` layer.
134
+ num_class_embeds (`int`, *optional*, defaults to 0):
135
+ Input dimension of the learnable embedding matrix to be projected to `time_embed_dim`, when performing
136
+ class conditioning with `class_embed_type` equal to `None`.
137
+ upcast_attention (`bool`, defaults to `False`):
138
+ resnet_time_scale_shift (`str`, defaults to `"default"`):
139
+ Time scale shift config for ResNet blocks (see `ResnetBlock2D`). Choose from `default` or `scale_shift`.
140
+ projection_class_embeddings_input_dim (`int`, *optional*, defaults to `None`):
141
+ The dimension of the `class_labels` input when `class_embed_type="projection"`. Required when
142
+ `class_embed_type="projection"`.
143
+ controlnet_conditioning_channel_order (`str`, defaults to `"rgb"`):
144
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
145
+ conditioning_embedding_out_channels (`tuple[int]`, *optional*, defaults to `(48, 96, 192, 384)`):
146
+ The tuple of output channel for each block in the `conditioning_embedding` layer.
147
+ global_pool_conditions (`bool`, defaults to `False`):
148
+ """
149
+
150
+ _supports_gradient_checkpointing = True
151
+
152
+ @register_to_config
153
+ def __init__(
154
+ self,
155
+ in_channels: int = 4,
156
+ conditioning_channels: int = 3,
157
+ flip_sin_to_cos: bool = True,
158
+ freq_shift: int = 0,
159
+ down_block_types: Tuple[str, ...] = (
160
+ "CrossAttnDownBlock2D",
161
+ "CrossAttnDownBlock2D",
162
+ "CrossAttnDownBlock2D",
163
+ "DownBlock2D",
164
+ ),
165
+ only_cross_attention: Union[bool, Tuple[bool]] = False,
166
+ block_out_channels: Tuple[int, ...] = (320, 640, 1280, 1280),
167
+ layers_per_block: int = 2,
168
+ downsample_padding: int = 1,
169
+ mid_block_scale_factor: float = 1,
170
+ act_fn: str = "silu",
171
+ norm_num_groups: Optional[int] = 32,
172
+ norm_eps: float = 1e-5,
173
+ cross_attention_dim: int = 1280,
174
+ transformer_layers_per_block: Union[int, Tuple[int, ...]] = 1,
175
+ encoder_hid_dim: Optional[int] = None,
176
+ encoder_hid_dim_type: Optional[str] = None,
177
+ attention_head_dim: Union[int, Tuple[int, ...]] = 8,
178
+ num_attention_heads: Optional[Union[int, Tuple[int, ...]]] = None,
179
+ use_linear_projection: bool = False,
180
+ class_embed_type: Optional[str] = None,
181
+ addition_embed_type: Optional[str] = None,
182
+ addition_time_embed_dim: Optional[int] = None,
183
+ num_class_embeds: Optional[int] = None,
184
+ upcast_attention: bool = False,
185
+ resnet_time_scale_shift: str = "default",
186
+ projection_class_embeddings_input_dim: Optional[int] = None,
187
+ controlnet_conditioning_channel_order: str = "rgb",
188
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (48, 96, 192, 384),
189
+ global_pool_conditions: bool = False,
190
+ addition_embed_type_num_heads: int = 64,
191
+ num_control_type: int = 6,
192
+ num_trans_channel: int = 320,
193
+ num_trans_head: int = 8,
194
+ num_trans_layer: int = 1,
195
+ num_proj_channel: int = 320,
196
+ ):
197
+ super().__init__()
198
+
199
+ # If `num_attention_heads` is not defined (which is the case for most models)
200
+ # it will default to `attention_head_dim`. This looks weird upon first reading it and it is.
201
+ # The reason for this behavior is to correct for incorrectly named variables that were introduced
202
+ # when this library was created. The incorrect naming was only discovered much later in https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131
203
+ # Changing `attention_head_dim` to `num_attention_heads` for 40,000+ configurations is too backwards breaking
204
+ # which is why we correct for the naming here.
205
+ num_attention_heads = num_attention_heads or attention_head_dim
206
+
207
+ # Check inputs
208
+ if len(block_out_channels) != len(down_block_types):
209
+ raise ValueError(
210
+ 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}."
211
+ )
212
+
213
+ if not isinstance(only_cross_attention, bool) and len(only_cross_attention) != len(down_block_types):
214
+ raise ValueError(
215
+ 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}."
216
+ )
217
+
218
+ if not isinstance(num_attention_heads, int) and len(num_attention_heads) != len(down_block_types):
219
+ raise ValueError(
220
+ 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}."
221
+ )
222
+
223
+ if isinstance(transformer_layers_per_block, int):
224
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
225
+
226
+ # input
227
+ conv_in_kernel = 3
228
+ conv_in_padding = (conv_in_kernel - 1) // 2
229
+ self.conv_in = nn.Conv2d(
230
+ in_channels, block_out_channels[0], kernel_size=conv_in_kernel, padding=conv_in_padding
231
+ )
232
+
233
+ # time
234
+ time_embed_dim = block_out_channels[0] * 4
235
+ self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift)
236
+ timestep_input_dim = block_out_channels[0]
237
+ self.time_embedding = TimestepEmbedding(
238
+ timestep_input_dim,
239
+ time_embed_dim,
240
+ act_fn=act_fn,
241
+ )
242
+
243
+ if encoder_hid_dim_type is not None:
244
+ raise ValueError(f"encoder_hid_dim_type: {encoder_hid_dim_type} must be None.")
245
+ else:
246
+ self.encoder_hid_proj = None
247
+
248
+ # class embedding
249
+ if class_embed_type is None and num_class_embeds is not None:
250
+ self.class_embedding = nn.Embedding(num_class_embeds, time_embed_dim)
251
+ elif class_embed_type == "timestep":
252
+ self.class_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim)
253
+ elif class_embed_type == "identity":
254
+ self.class_embedding = nn.Identity(time_embed_dim, time_embed_dim)
255
+ elif class_embed_type == "projection":
256
+ if projection_class_embeddings_input_dim is None:
257
+ raise ValueError(
258
+ "`class_embed_type`: 'projection' requires `projection_class_embeddings_input_dim` be set"
259
+ )
260
+ # The projection `class_embed_type` is the same as the timestep `class_embed_type` except
261
+ # 1. the `class_labels` inputs are not first converted to sinusoidal embeddings
262
+ # 2. it projects from an arbitrary input dimension.
263
+ #
264
+ # Note that `TimestepEmbedding` is quite general, being mainly linear layers and activations.
265
+ # When used for embedding actual timesteps, the timesteps are first converted to sinusoidal embeddings.
266
+ # As a result, `TimestepEmbedding` can be passed arbitrary vectors.
267
+ self.class_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
268
+ else:
269
+ self.class_embedding = None
270
+
271
+ if addition_embed_type == "text":
272
+ if encoder_hid_dim is not None:
273
+ text_time_embedding_from_dim = encoder_hid_dim
274
+ else:
275
+ text_time_embedding_from_dim = cross_attention_dim
276
+
277
+ self.add_embedding = TextTimeEmbedding(
278
+ text_time_embedding_from_dim, time_embed_dim, num_heads=addition_embed_type_num_heads
279
+ )
280
+ elif addition_embed_type == "text_image":
281
+ # text_embed_dim and image_embed_dim DON'T have to be `cross_attention_dim`. To not clutter the __init__ too much
282
+ # they are set to `cross_attention_dim` here as this is exactly the required dimension for the currently only use
283
+ # case when `addition_embed_type == "text_image"` (Kandinsky 2.1)`
284
+ self.add_embedding = TextImageTimeEmbedding(
285
+ text_embed_dim=cross_attention_dim, image_embed_dim=cross_attention_dim, time_embed_dim=time_embed_dim
286
+ )
287
+ elif addition_embed_type == "text_time":
288
+ self.add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
289
+ self.add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
290
+
291
+ elif addition_embed_type is not None:
292
+ raise ValueError(f"addition_embed_type: {addition_embed_type} must be None, 'text' or 'text_image'.")
293
+
294
+ # control net conditioning embedding
295
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
296
+ conditioning_embedding_channels=block_out_channels[0],
297
+ block_out_channels=conditioning_embedding_out_channels,
298
+ conditioning_channels=conditioning_channels,
299
+ )
300
+
301
+ task_scale_factor = num_trans_channel**0.5
302
+ self.task_embedding = nn.Parameter(task_scale_factor * torch.randn(num_control_type, num_trans_channel))
303
+ self.transformer_layes = nn.ModuleList(
304
+ [ResidualAttentionBlock(num_trans_channel, num_trans_head) for _ in range(num_trans_layer)]
305
+ )
306
+ self.spatial_ch_projs = zero_module(nn.Linear(num_trans_channel, num_proj_channel))
307
+ self.control_type_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos, freq_shift)
308
+ self.control_add_embedding = TimestepEmbedding(addition_time_embed_dim * num_control_type, time_embed_dim)
309
+
310
+ self.down_blocks = nn.ModuleList([])
311
+ self.controlnet_down_blocks = nn.ModuleList([])
312
+
313
+ if isinstance(only_cross_attention, bool):
314
+ only_cross_attention = [only_cross_attention] * len(down_block_types)
315
+
316
+ if isinstance(attention_head_dim, int):
317
+ attention_head_dim = (attention_head_dim,) * len(down_block_types)
318
+
319
+ if isinstance(num_attention_heads, int):
320
+ num_attention_heads = (num_attention_heads,) * len(down_block_types)
321
+
322
+ # down
323
+ output_channel = block_out_channels[0]
324
+
325
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
326
+ controlnet_block = zero_module(controlnet_block)
327
+ self.controlnet_down_blocks.append(controlnet_block)
328
+
329
+ for i, down_block_type in enumerate(down_block_types):
330
+ input_channel = output_channel
331
+ output_channel = block_out_channels[i]
332
+ is_final_block = i == len(block_out_channels) - 1
333
+
334
+ down_block = get_down_block(
335
+ down_block_type,
336
+ num_layers=layers_per_block,
337
+ transformer_layers_per_block=transformer_layers_per_block[i],
338
+ in_channels=input_channel,
339
+ out_channels=output_channel,
340
+ temb_channels=time_embed_dim,
341
+ add_downsample=not is_final_block,
342
+ resnet_eps=norm_eps,
343
+ resnet_act_fn=act_fn,
344
+ resnet_groups=norm_num_groups,
345
+ cross_attention_dim=cross_attention_dim,
346
+ num_attention_heads=num_attention_heads[i],
347
+ attention_head_dim=attention_head_dim[i] if attention_head_dim[i] is not None else output_channel,
348
+ downsample_padding=downsample_padding,
349
+ use_linear_projection=use_linear_projection,
350
+ only_cross_attention=only_cross_attention[i],
351
+ upcast_attention=upcast_attention,
352
+ resnet_time_scale_shift=resnet_time_scale_shift,
353
+ )
354
+ self.down_blocks.append(down_block)
355
+
356
+ for _ in range(layers_per_block):
357
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
358
+ controlnet_block = zero_module(controlnet_block)
359
+ self.controlnet_down_blocks.append(controlnet_block)
360
+
361
+ if not is_final_block:
362
+ controlnet_block = nn.Conv2d(output_channel, output_channel, kernel_size=1)
363
+ controlnet_block = zero_module(controlnet_block)
364
+ self.controlnet_down_blocks.append(controlnet_block)
365
+
366
+ # mid
367
+ mid_block_channel = block_out_channels[-1]
368
+
369
+ controlnet_block = nn.Conv2d(mid_block_channel, mid_block_channel, kernel_size=1)
370
+ controlnet_block = zero_module(controlnet_block)
371
+ self.controlnet_mid_block = controlnet_block
372
+
373
+ self.mid_block = UNetMidBlock2DCrossAttn(
374
+ transformer_layers_per_block=transformer_layers_per_block[-1],
375
+ in_channels=mid_block_channel,
376
+ temb_channels=time_embed_dim,
377
+ resnet_eps=norm_eps,
378
+ resnet_act_fn=act_fn,
379
+ output_scale_factor=mid_block_scale_factor,
380
+ resnet_time_scale_shift=resnet_time_scale_shift,
381
+ cross_attention_dim=cross_attention_dim,
382
+ num_attention_heads=num_attention_heads[-1],
383
+ resnet_groups=norm_num_groups,
384
+ use_linear_projection=use_linear_projection,
385
+ upcast_attention=upcast_attention,
386
+ )
387
+
388
+ @classmethod
389
+ def from_unet(
390
+ cls,
391
+ unet: UNet2DConditionModel,
392
+ controlnet_conditioning_channel_order: str = "rgb",
393
+ conditioning_embedding_out_channels: Optional[Tuple[int, ...]] = (16, 32, 96, 256),
394
+ load_weights_from_unet: bool = True,
395
+ ):
396
+ r"""
397
+ Instantiate a [`ControlNetUnionModel`] from [`UNet2DConditionModel`].
398
+
399
+ Parameters:
400
+ unet (`UNet2DConditionModel`):
401
+ The UNet model weights to copy to the [`ControlNetUnionModel`]. All configuration options are also
402
+ copied where applicable.
403
+ """
404
+ transformer_layers_per_block = (
405
+ unet.config.transformer_layers_per_block if "transformer_layers_per_block" in unet.config else 1
406
+ )
407
+ encoder_hid_dim = unet.config.encoder_hid_dim if "encoder_hid_dim" in unet.config else None
408
+ encoder_hid_dim_type = unet.config.encoder_hid_dim_type if "encoder_hid_dim_type" in unet.config else None
409
+ addition_embed_type = unet.config.addition_embed_type if "addition_embed_type" in unet.config else None
410
+ addition_time_embed_dim = (
411
+ unet.config.addition_time_embed_dim if "addition_time_embed_dim" in unet.config else None
412
+ )
413
+
414
+ controlnet = cls(
415
+ encoder_hid_dim=encoder_hid_dim,
416
+ encoder_hid_dim_type=encoder_hid_dim_type,
417
+ addition_embed_type=addition_embed_type,
418
+ addition_time_embed_dim=addition_time_embed_dim,
419
+ transformer_layers_per_block=transformer_layers_per_block,
420
+ in_channels=unet.config.in_channels,
421
+ flip_sin_to_cos=unet.config.flip_sin_to_cos,
422
+ freq_shift=unet.config.freq_shift,
423
+ down_block_types=unet.config.down_block_types,
424
+ only_cross_attention=unet.config.only_cross_attention,
425
+ block_out_channels=unet.config.block_out_channels,
426
+ layers_per_block=unet.config.layers_per_block,
427
+ downsample_padding=unet.config.downsample_padding,
428
+ mid_block_scale_factor=unet.config.mid_block_scale_factor,
429
+ act_fn=unet.config.act_fn,
430
+ norm_num_groups=unet.config.norm_num_groups,
431
+ norm_eps=unet.config.norm_eps,
432
+ cross_attention_dim=unet.config.cross_attention_dim,
433
+ attention_head_dim=unet.config.attention_head_dim,
434
+ num_attention_heads=unet.config.num_attention_heads,
435
+ use_linear_projection=unet.config.use_linear_projection,
436
+ class_embed_type=unet.config.class_embed_type,
437
+ num_class_embeds=unet.config.num_class_embeds,
438
+ upcast_attention=unet.config.upcast_attention,
439
+ resnet_time_scale_shift=unet.config.resnet_time_scale_shift,
440
+ projection_class_embeddings_input_dim=unet.config.projection_class_embeddings_input_dim,
441
+ controlnet_conditioning_channel_order=controlnet_conditioning_channel_order,
442
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
443
+ )
444
+
445
+ if load_weights_from_unet:
446
+ controlnet.conv_in.load_state_dict(unet.conv_in.state_dict())
447
+ controlnet.time_proj.load_state_dict(unet.time_proj.state_dict())
448
+ controlnet.time_embedding.load_state_dict(unet.time_embedding.state_dict())
449
+
450
+ if controlnet.class_embedding:
451
+ controlnet.class_embedding.load_state_dict(unet.class_embedding.state_dict())
452
+
453
+ controlnet.down_blocks.load_state_dict(unet.down_blocks.state_dict(), strict=False)
454
+ controlnet.mid_block.load_state_dict(unet.mid_block.state_dict(), strict=False)
455
+
456
+ return controlnet
457
+
458
+ @property
459
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
460
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
461
+ r"""
462
+ Returns:
463
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
464
+ indexed by its weight name.
465
+ """
466
+ # set recursively
467
+ processors = {}
468
+
469
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
470
+ if hasattr(module, "get_processor"):
471
+ processors[f"{name}.processor"] = module.get_processor()
472
+
473
+ for sub_name, child in module.named_children():
474
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
475
+
476
+ return processors
477
+
478
+ for name, module in self.named_children():
479
+ fn_recursive_add_processors(name, module, processors)
480
+
481
+ return processors
482
+
483
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
484
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
485
+ r"""
486
+ Sets the attention processor to use to compute attention.
487
+
488
+ Parameters:
489
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
490
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
491
+ for **all** `Attention` layers.
492
+
493
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
494
+ processor. This is strongly recommended when setting trainable attention processors.
495
+
496
+ """
497
+ count = len(self.attn_processors.keys())
498
+
499
+ if isinstance(processor, dict) and len(processor) != count:
500
+ raise ValueError(
501
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
502
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
503
+ )
504
+
505
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
506
+ if hasattr(module, "set_processor"):
507
+ if not isinstance(processor, dict):
508
+ module.set_processor(processor)
509
+ else:
510
+ module.set_processor(processor.pop(f"{name}.processor"))
511
+
512
+ for sub_name, child in module.named_children():
513
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
514
+
515
+ for name, module in self.named_children():
516
+ fn_recursive_attn_processor(name, module, processor)
517
+
518
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
519
+ def set_default_attn_processor(self):
520
+ """
521
+ Disables custom attention processors and sets the default attention implementation.
522
+ """
523
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
524
+ processor = AttnAddedKVProcessor()
525
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
526
+ processor = AttnProcessor()
527
+ else:
528
+ raise ValueError(
529
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
530
+ )
531
+
532
+ self.set_attn_processor(processor)
533
+
534
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attention_slice
535
+ def set_attention_slice(self, slice_size: Union[str, int, List[int]]) -> None:
536
+ r"""
537
+ Enable sliced attention computation.
538
+
539
+ When this option is enabled, the attention module splits the input tensor in slices to compute attention in
540
+ several steps. This is useful for saving some memory in exchange for a small decrease in speed.
541
+
542
+ Args:
543
+ slice_size (`str` or `int` or `list(int)`, *optional*, defaults to `"auto"`):
544
+ When `"auto"`, input to the attention heads is halved, so attention is computed in two steps. If
545
+ `"max"`, maximum amount of memory is saved by running only one slice at a time. If a number is
546
+ provided, uses as many slices as `attention_head_dim // slice_size`. In this case, `attention_head_dim`
547
+ must be a multiple of `slice_size`.
548
+ """
549
+ sliceable_head_dims = []
550
+
551
+ def fn_recursive_retrieve_sliceable_dims(module: torch.nn.Module):
552
+ if hasattr(module, "set_attention_slice"):
553
+ sliceable_head_dims.append(module.sliceable_head_dim)
554
+
555
+ for child in module.children():
556
+ fn_recursive_retrieve_sliceable_dims(child)
557
+
558
+ # retrieve number of attention layers
559
+ for module in self.children():
560
+ fn_recursive_retrieve_sliceable_dims(module)
561
+
562
+ num_sliceable_layers = len(sliceable_head_dims)
563
+
564
+ if slice_size == "auto":
565
+ # half the attention head size is usually a good trade-off between
566
+ # speed and memory
567
+ slice_size = [dim // 2 for dim in sliceable_head_dims]
568
+ elif slice_size == "max":
569
+ # make smallest slice possible
570
+ slice_size = num_sliceable_layers * [1]
571
+
572
+ slice_size = num_sliceable_layers * [slice_size] if not isinstance(slice_size, list) else slice_size
573
+
574
+ if len(slice_size) != len(sliceable_head_dims):
575
+ raise ValueError(
576
+ f"You have provided {len(slice_size)}, but {self.config} has {len(sliceable_head_dims)} different"
577
+ f" attention layers. Make sure to match `len(slice_size)` to be {len(sliceable_head_dims)}."
578
+ )
579
+
580
+ for i in range(len(slice_size)):
581
+ size = slice_size[i]
582
+ dim = sliceable_head_dims[i]
583
+ if size is not None and size > dim:
584
+ raise ValueError(f"size {size} has to be smaller or equal to {dim}.")
585
+
586
+ # Recursively walk through all the children.
587
+ # Any children which exposes the set_attention_slice method
588
+ # gets the message
589
+ def fn_recursive_set_attention_slice(module: torch.nn.Module, slice_size: List[int]):
590
+ if hasattr(module, "set_attention_slice"):
591
+ module.set_attention_slice(slice_size.pop())
592
+
593
+ for child in module.children():
594
+ fn_recursive_set_attention_slice(child, slice_size)
595
+
596
+ reversed_slice_size = list(reversed(slice_size))
597
+ for module in self.children():
598
+ fn_recursive_set_attention_slice(module, reversed_slice_size)
599
+
600
+ def forward(
601
+ self,
602
+ sample: torch.Tensor,
603
+ timestep: Union[torch.Tensor, float, int],
604
+ encoder_hidden_states: torch.Tensor,
605
+ controlnet_cond: List[torch.Tensor],
606
+ control_type: torch.Tensor,
607
+ control_type_idx: List[int],
608
+ conditioning_scale: Union[float, List[float]] = 1.0,
609
+ class_labels: Optional[torch.Tensor] = None,
610
+ timestep_cond: Optional[torch.Tensor] = None,
611
+ attention_mask: Optional[torch.Tensor] = None,
612
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
613
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
614
+ from_multi: bool = False,
615
+ guess_mode: bool = False,
616
+ return_dict: bool = True,
617
+ ) -> Union[ControlNetOutput, Tuple[Tuple[torch.Tensor, ...], torch.Tensor]]:
618
+ """
619
+ The [`ControlNetUnionModel`] forward method.
620
+
621
+ Args:
622
+ sample (`torch.Tensor`):
623
+ The noisy input tensor.
624
+ timestep (`Union[torch.Tensor, float, int]`):
625
+ The number of timesteps to denoise an input.
626
+ encoder_hidden_states (`torch.Tensor`):
627
+ The encoder hidden states.
628
+ controlnet_cond (`List[torch.Tensor]`):
629
+ The conditional input tensors.
630
+ control_type (`torch.Tensor`):
631
+ A tensor of shape `(batch, num_control_type)` with values `0` or `1` depending on whether the control
632
+ type is used.
633
+ control_type_idx (`List[int]`):
634
+ The indices of `control_type`.
635
+ conditioning_scale (`float`, defaults to `1.0`):
636
+ The scale factor for ControlNet outputs.
637
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
638
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
639
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
640
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
641
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
642
+ embeddings.
643
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
644
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
645
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
646
+ negative values to the attention scores corresponding to "discard" tokens.
647
+ added_cond_kwargs (`dict`):
648
+ Additional conditions for the Stable Diffusion XL UNet.
649
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
650
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
651
+ from_multi (`bool`, defaults to `False`):
652
+ Use standard scaling when called from `MultiControlNetUnionModel`.
653
+ guess_mode (`bool`, defaults to `False`):
654
+ In this mode, the ControlNet encoder tries its best to recognize the input content of the input even if
655
+ you remove all prompts. A `guidance_scale` between 3.0 and 5.0 is recommended.
656
+ return_dict (`bool`, defaults to `True`):
657
+ Whether or not to return a [`~models.controlnet.ControlNetOutput`] instead of a plain tuple.
658
+
659
+ Returns:
660
+ [`~models.controlnet.ControlNetOutput`] **or** `tuple`:
661
+ If `return_dict` is `True`, a [`~models.controlnet.ControlNetOutput`] is returned, otherwise a tuple is
662
+ returned where the first element is the sample tensor.
663
+ """
664
+ if isinstance(conditioning_scale, float):
665
+ conditioning_scale = [conditioning_scale] * len(controlnet_cond)
666
+
667
+ # check channel order
668
+ channel_order = self.config.controlnet_conditioning_channel_order
669
+
670
+ if channel_order != "rgb":
671
+ raise ValueError(f"unknown `controlnet_conditioning_channel_order`: {channel_order}")
672
+
673
+ # prepare attention_mask
674
+ if attention_mask is not None:
675
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
676
+ attention_mask = attention_mask.unsqueeze(1)
677
+
678
+ # 1. time
679
+ timesteps = timestep
680
+ if not torch.is_tensor(timesteps):
681
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
682
+ # This would be a good case for the `match` statement (Python 3.10+)
683
+ is_mps = sample.device.type == "mps"
684
+ is_npu = sample.device.type == "npu"
685
+ if isinstance(timestep, float):
686
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
687
+ else:
688
+ dtype = torch.int32 if (is_mps or is_npu) else torch.int64
689
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
690
+ elif len(timesteps.shape) == 0:
691
+ timesteps = timesteps[None].to(sample.device)
692
+
693
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
694
+ timesteps = timesteps.expand(sample.shape[0])
695
+
696
+ t_emb = self.time_proj(timesteps)
697
+
698
+ # timesteps does not contain any weights and will always return f32 tensors
699
+ # but time_embedding might actually be running in fp16. so we need to cast here.
700
+ # there might be better ways to encapsulate this.
701
+ t_emb = t_emb.to(dtype=sample.dtype)
702
+
703
+ emb = self.time_embedding(t_emb, timestep_cond)
704
+ aug_emb = None
705
+
706
+ if self.class_embedding is not None:
707
+ if class_labels is None:
708
+ raise ValueError("class_labels should be provided when num_class_embeds > 0")
709
+
710
+ if self.config.class_embed_type == "timestep":
711
+ class_labels = self.time_proj(class_labels)
712
+
713
+ class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
714
+ emb = emb + class_emb
715
+
716
+ if self.config.addition_embed_type is not None:
717
+ if self.config.addition_embed_type == "text":
718
+ aug_emb = self.add_embedding(encoder_hidden_states)
719
+
720
+ elif self.config.addition_embed_type == "text_time":
721
+ if "text_embeds" not in added_cond_kwargs:
722
+ raise ValueError(
723
+ 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`"
724
+ )
725
+ text_embeds = added_cond_kwargs.get("text_embeds")
726
+ if "time_ids" not in added_cond_kwargs:
727
+ raise ValueError(
728
+ 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`"
729
+ )
730
+ time_ids = added_cond_kwargs.get("time_ids")
731
+ time_embeds = self.add_time_proj(time_ids.flatten())
732
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
733
+
734
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
735
+ add_embeds = add_embeds.to(emb.dtype)
736
+ aug_emb = self.add_embedding(add_embeds)
737
+
738
+ control_embeds = self.control_type_proj(control_type.flatten())
739
+ control_embeds = control_embeds.reshape((t_emb.shape[0], -1))
740
+ control_embeds = control_embeds.to(emb.dtype)
741
+ control_emb = self.control_add_embedding(control_embeds)
742
+ emb = emb + control_emb
743
+ emb = emb + aug_emb if aug_emb is not None else emb
744
+
745
+ # 2. pre-process
746
+ sample = self.conv_in(sample)
747
+
748
+ inputs = []
749
+ condition_list = []
750
+
751
+ for cond, control_idx, scale in zip(controlnet_cond, control_type_idx, conditioning_scale):
752
+ condition = self.controlnet_cond_embedding(cond)
753
+ feat_seq = torch.mean(condition, dim=(2, 3))
754
+ feat_seq = feat_seq + self.task_embedding[control_idx]
755
+ if from_multi:
756
+ inputs.append(feat_seq.unsqueeze(1))
757
+ condition_list.append(condition)
758
+ else:
759
+ inputs.append(feat_seq.unsqueeze(1) * scale)
760
+ condition_list.append(condition * scale)
761
+
762
+ condition = sample
763
+ feat_seq = torch.mean(condition, dim=(2, 3))
764
+ inputs.append(feat_seq.unsqueeze(1))
765
+ condition_list.append(condition)
766
+
767
+ x = torch.cat(inputs, dim=1)
768
+ for layer in self.transformer_layes:
769
+ x = layer(x)
770
+
771
+ controlnet_cond_fuser = sample * 0.0
772
+ for (idx, condition), scale in zip(enumerate(condition_list[:-1]), conditioning_scale):
773
+ alpha = self.spatial_ch_projs(x[:, idx])
774
+ alpha = alpha.unsqueeze(-1).unsqueeze(-1)
775
+ if from_multi:
776
+ controlnet_cond_fuser += condition + alpha
777
+ else:
778
+ controlnet_cond_fuser += condition + alpha * scale
779
+
780
+ sample = sample + controlnet_cond_fuser
781
+
782
+ # 3. down
783
+ down_block_res_samples = (sample,)
784
+ for downsample_block in self.down_blocks:
785
+ if hasattr(downsample_block, "has_cross_attention") and downsample_block.has_cross_attention:
786
+ sample, res_samples = downsample_block(
787
+ hidden_states=sample,
788
+ temb=emb,
789
+ encoder_hidden_states=encoder_hidden_states,
790
+ attention_mask=attention_mask,
791
+ cross_attention_kwargs=cross_attention_kwargs,
792
+ )
793
+ else:
794
+ sample, res_samples = downsample_block(hidden_states=sample, temb=emb)
795
+
796
+ down_block_res_samples += res_samples
797
+
798
+ # 4. mid
799
+ if self.mid_block is not None:
800
+ sample = self.mid_block(
801
+ sample,
802
+ emb,
803
+ encoder_hidden_states=encoder_hidden_states,
804
+ attention_mask=attention_mask,
805
+ cross_attention_kwargs=cross_attention_kwargs,
806
+ )
807
+
808
+ # 5. Control net blocks
809
+ controlnet_down_block_res_samples = ()
810
+
811
+ for down_block_res_sample, controlnet_block in zip(down_block_res_samples, self.controlnet_down_blocks):
812
+ down_block_res_sample = controlnet_block(down_block_res_sample)
813
+ controlnet_down_block_res_samples = controlnet_down_block_res_samples + (down_block_res_sample,)
814
+
815
+ down_block_res_samples = controlnet_down_block_res_samples
816
+
817
+ mid_block_res_sample = self.controlnet_mid_block(sample)
818
+
819
+ # 6. scaling
820
+ if guess_mode and not self.config.global_pool_conditions:
821
+ scales = torch.logspace(-1, 0, len(down_block_res_samples) + 1, device=sample.device) # 0.1 to 1.0
822
+ if from_multi:
823
+ scales = scales * conditioning_scale[0]
824
+ down_block_res_samples = [sample * scale for sample, scale in zip(down_block_res_samples, scales)]
825
+ mid_block_res_sample = mid_block_res_sample * scales[-1] # last one
826
+ elif from_multi:
827
+ down_block_res_samples = [sample * conditioning_scale[0] for sample in down_block_res_samples]
828
+ mid_block_res_sample = mid_block_res_sample * conditioning_scale[0]
829
+
830
+ if self.config.global_pool_conditions:
831
+ down_block_res_samples = [
832
+ torch.mean(sample, dim=(2, 3), keepdim=True) for sample in down_block_res_samples
833
+ ]
834
+ mid_block_res_sample = torch.mean(mid_block_res_sample, dim=(2, 3), keepdim=True)
835
+
836
+ if not return_dict:
837
+ return (down_block_res_samples, mid_block_res_sample)
838
+
839
+ return ControlNetOutput(
840
+ down_block_res_samples=down_block_res_samples, mid_block_res_sample=mid_block_res_sample
841
+ )
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/controlnet_xs.py ADDED
@@ -0,0 +1,1907 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from dataclasses import dataclass
15
+ from math import gcd
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.utils.checkpoint
20
+ from torch import Tensor, nn
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...utils import BaseOutput, logging
24
+ from ...utils.torch_utils import apply_freeu
25
+ from ..attention_processor import (
26
+ ADDED_KV_ATTENTION_PROCESSORS,
27
+ CROSS_ATTENTION_PROCESSORS,
28
+ Attention,
29
+ AttentionProcessor,
30
+ AttnAddedKVProcessor,
31
+ AttnProcessor,
32
+ FusedAttnProcessor2_0,
33
+ )
34
+ from ..embeddings import TimestepEmbedding, Timesteps
35
+ from ..modeling_utils import ModelMixin
36
+ from ..unets.unet_2d_blocks import (
37
+ CrossAttnDownBlock2D,
38
+ CrossAttnUpBlock2D,
39
+ Downsample2D,
40
+ ResnetBlock2D,
41
+ Transformer2DModel,
42
+ UNetMidBlock2DCrossAttn,
43
+ Upsample2D,
44
+ )
45
+ from ..unets.unet_2d_condition import UNet2DConditionModel
46
+ from .controlnet import ControlNetConditioningEmbedding
47
+
48
+
49
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
50
+
51
+
52
+ @dataclass
53
+ class ControlNetXSOutput(BaseOutput):
54
+ """
55
+ The output of [`UNetControlNetXSModel`].
56
+
57
+ Args:
58
+ sample (`Tensor` of shape `(batch_size, num_channels, height, width)`):
59
+ The output of the `UNetControlNetXSModel`. Unlike `ControlNetOutput` this is NOT to be added to the base
60
+ model output, but is already the final output.
61
+ """
62
+
63
+ sample: Tensor = None
64
+
65
+
66
+ class DownBlockControlNetXSAdapter(nn.Module):
67
+ """Components that together with corresponding components from the base model will form a
68
+ `ControlNetXSCrossAttnDownBlock2D`"""
69
+
70
+ def __init__(
71
+ self,
72
+ resnets: nn.ModuleList,
73
+ base_to_ctrl: nn.ModuleList,
74
+ ctrl_to_base: nn.ModuleList,
75
+ attentions: Optional[nn.ModuleList] = None,
76
+ downsampler: Optional[nn.Conv2d] = None,
77
+ ):
78
+ super().__init__()
79
+ self.resnets = resnets
80
+ self.base_to_ctrl = base_to_ctrl
81
+ self.ctrl_to_base = ctrl_to_base
82
+ self.attentions = attentions
83
+ self.downsamplers = downsampler
84
+
85
+
86
+ class MidBlockControlNetXSAdapter(nn.Module):
87
+ """Components that together with corresponding components from the base model will form a
88
+ `ControlNetXSCrossAttnMidBlock2D`"""
89
+
90
+ def __init__(self, midblock: UNetMidBlock2DCrossAttn, base_to_ctrl: nn.ModuleList, ctrl_to_base: nn.ModuleList):
91
+ super().__init__()
92
+ self.midblock = midblock
93
+ self.base_to_ctrl = base_to_ctrl
94
+ self.ctrl_to_base = ctrl_to_base
95
+
96
+
97
+ class UpBlockControlNetXSAdapter(nn.Module):
98
+ """Components that together with corresponding components from the base model will form a `ControlNetXSCrossAttnUpBlock2D`"""
99
+
100
+ def __init__(self, ctrl_to_base: nn.ModuleList):
101
+ super().__init__()
102
+ self.ctrl_to_base = ctrl_to_base
103
+
104
+
105
+ def get_down_block_adapter(
106
+ base_in_channels: int,
107
+ base_out_channels: int,
108
+ ctrl_in_channels: int,
109
+ ctrl_out_channels: int,
110
+ temb_channels: int,
111
+ max_norm_num_groups: Optional[int] = 32,
112
+ has_crossattn=True,
113
+ transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
114
+ num_attention_heads: Optional[int] = 1,
115
+ cross_attention_dim: Optional[int] = 1024,
116
+ add_downsample: bool = True,
117
+ upcast_attention: Optional[bool] = False,
118
+ use_linear_projection: Optional[bool] = True,
119
+ ):
120
+ num_layers = 2 # only support sd + sdxl
121
+
122
+ resnets = []
123
+ attentions = []
124
+ ctrl_to_base = []
125
+ base_to_ctrl = []
126
+
127
+ if isinstance(transformer_layers_per_block, int):
128
+ transformer_layers_per_block = [transformer_layers_per_block] * num_layers
129
+
130
+ for i in range(num_layers):
131
+ base_in_channels = base_in_channels if i == 0 else base_out_channels
132
+ ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
133
+
134
+ # Before the resnet/attention application, information is concatted from base to control.
135
+ # Concat doesn't require change in number of channels
136
+ base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
137
+
138
+ resnets.append(
139
+ ResnetBlock2D(
140
+ in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
141
+ out_channels=ctrl_out_channels,
142
+ temb_channels=temb_channels,
143
+ groups=find_largest_factor(ctrl_in_channels + base_in_channels, max_factor=max_norm_num_groups),
144
+ groups_out=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
145
+ eps=1e-5,
146
+ )
147
+ )
148
+
149
+ if has_crossattn:
150
+ attentions.append(
151
+ Transformer2DModel(
152
+ num_attention_heads,
153
+ ctrl_out_channels // num_attention_heads,
154
+ in_channels=ctrl_out_channels,
155
+ num_layers=transformer_layers_per_block[i],
156
+ cross_attention_dim=cross_attention_dim,
157
+ use_linear_projection=use_linear_projection,
158
+ upcast_attention=upcast_attention,
159
+ norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=max_norm_num_groups),
160
+ )
161
+ )
162
+
163
+ # After the resnet/attention application, information is added from control to base
164
+ # Addition requires change in number of channels
165
+ ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
166
+
167
+ if add_downsample:
168
+ # Before the downsampler application, information is concatted from base to control
169
+ # Concat doesn't require change in number of channels
170
+ base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
171
+
172
+ downsamplers = Downsample2D(
173
+ ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
174
+ )
175
+
176
+ # After the downsampler application, information is added from control to base
177
+ # Addition requires change in number of channels
178
+ ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
179
+ else:
180
+ downsamplers = None
181
+
182
+ down_block_components = DownBlockControlNetXSAdapter(
183
+ resnets=nn.ModuleList(resnets),
184
+ base_to_ctrl=nn.ModuleList(base_to_ctrl),
185
+ ctrl_to_base=nn.ModuleList(ctrl_to_base),
186
+ )
187
+
188
+ if has_crossattn:
189
+ down_block_components.attentions = nn.ModuleList(attentions)
190
+ if downsamplers is not None:
191
+ down_block_components.downsamplers = downsamplers
192
+
193
+ return down_block_components
194
+
195
+
196
+ def get_mid_block_adapter(
197
+ base_channels: int,
198
+ ctrl_channels: int,
199
+ temb_channels: Optional[int] = None,
200
+ max_norm_num_groups: Optional[int] = 32,
201
+ transformer_layers_per_block: int = 1,
202
+ num_attention_heads: Optional[int] = 1,
203
+ cross_attention_dim: Optional[int] = 1024,
204
+ upcast_attention: bool = False,
205
+ use_linear_projection: bool = True,
206
+ ):
207
+ # Before the midblock application, information is concatted from base to control.
208
+ # Concat doesn't require change in number of channels
209
+ base_to_ctrl = make_zero_conv(base_channels, base_channels)
210
+
211
+ midblock = UNetMidBlock2DCrossAttn(
212
+ transformer_layers_per_block=transformer_layers_per_block,
213
+ in_channels=ctrl_channels + base_channels,
214
+ out_channels=ctrl_channels,
215
+ temb_channels=temb_channels,
216
+ # number or norm groups must divide both in_channels and out_channels
217
+ resnet_groups=find_largest_factor(gcd(ctrl_channels, ctrl_channels + base_channels), max_norm_num_groups),
218
+ cross_attention_dim=cross_attention_dim,
219
+ num_attention_heads=num_attention_heads,
220
+ use_linear_projection=use_linear_projection,
221
+ upcast_attention=upcast_attention,
222
+ )
223
+
224
+ # After the midblock application, information is added from control to base
225
+ # Addition requires change in number of channels
226
+ ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
227
+
228
+ return MidBlockControlNetXSAdapter(base_to_ctrl=base_to_ctrl, midblock=midblock, ctrl_to_base=ctrl_to_base)
229
+
230
+
231
+ def get_up_block_adapter(
232
+ out_channels: int,
233
+ prev_output_channel: int,
234
+ ctrl_skip_channels: List[int],
235
+ ):
236
+ ctrl_to_base = []
237
+ num_layers = 3 # only support sd + sdxl
238
+ for i in range(num_layers):
239
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
240
+ ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
241
+
242
+ return UpBlockControlNetXSAdapter(ctrl_to_base=nn.ModuleList(ctrl_to_base))
243
+
244
+
245
+ class ControlNetXSAdapter(ModelMixin, ConfigMixin):
246
+ r"""
247
+ A `ControlNetXSAdapter` model. To use it, pass it into a `UNetControlNetXSModel` (together with a
248
+ `UNet2DConditionModel` base model).
249
+
250
+ This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
251
+ methods implemented for all models (such as downloading or saving).
252
+
253
+ Like `UNetControlNetXSModel`, `ControlNetXSAdapter` is compatible with StableDiffusion and StableDiffusion-XL. It's
254
+ default parameters are compatible with StableDiffusion.
255
+
256
+ Parameters:
257
+ conditioning_channels (`int`, defaults to 3):
258
+ Number of channels of conditioning input (e.g. an image)
259
+ conditioning_channel_order (`str`, defaults to `"rgb"`):
260
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
261
+ conditioning_embedding_out_channels (`tuple[int]`, defaults to `(16, 32, 96, 256)`):
262
+ The tuple of output channels for each block in the `controlnet_cond_embedding` layer.
263
+ time_embedding_mix (`float`, defaults to 1.0):
264
+ If 0, then only the control adapters's time embedding is used. If 1, then only the base unet's time
265
+ embedding is used. Otherwise, both are combined.
266
+ learn_time_embedding (`bool`, defaults to `False`):
267
+ Whether a time embedding should be learned. If yes, `UNetControlNetXSModel` will combine the time
268
+ embeddings of the base model and the control adapter. If no, `UNetControlNetXSModel` will use the base
269
+ model's time embedding.
270
+ num_attention_heads (`list[int]`, defaults to `[4]`):
271
+ The number of attention heads.
272
+ block_out_channels (`list[int]`, defaults to `[4, 8, 16, 16]`):
273
+ The tuple of output channels for each block.
274
+ base_block_out_channels (`list[int]`, defaults to `[320, 640, 1280, 1280]`):
275
+ The tuple of output channels for each block in the base unet.
276
+ cross_attention_dim (`int`, defaults to 1024):
277
+ The dimension of the cross attention features.
278
+ down_block_types (`list[str]`, defaults to `["CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "CrossAttnDownBlock2D", "DownBlock2D"]`):
279
+ The tuple of downsample blocks to use.
280
+ sample_size (`int`, defaults to 96):
281
+ Height and width of input/output sample.
282
+ transformer_layers_per_block (`Union[int, Tuple[int]]`, defaults to 1):
283
+ The number of transformer blocks of type [`~models.attention.BasicTransformerBlock`]. Only relevant for
284
+ [`~models.unet_2d_blocks.CrossAttnDownBlock2D`], [`~models.unet_2d_blocks.UNetMidBlock2DCrossAttn`].
285
+ upcast_attention (`bool`, defaults to `True`):
286
+ Whether the attention computation should always be upcasted.
287
+ max_norm_num_groups (`int`, defaults to 32):
288
+ Maximum number of groups in group normal. The actual number will be the largest divisor of the respective
289
+ channels, that is <= max_norm_num_groups.
290
+ """
291
+
292
+ @register_to_config
293
+ def __init__(
294
+ self,
295
+ conditioning_channels: int = 3,
296
+ conditioning_channel_order: str = "rgb",
297
+ conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
298
+ time_embedding_mix: float = 1.0,
299
+ learn_time_embedding: bool = False,
300
+ num_attention_heads: Union[int, Tuple[int]] = 4,
301
+ block_out_channels: Tuple[int] = (4, 8, 16, 16),
302
+ base_block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
303
+ cross_attention_dim: int = 1024,
304
+ down_block_types: Tuple[str] = (
305
+ "CrossAttnDownBlock2D",
306
+ "CrossAttnDownBlock2D",
307
+ "CrossAttnDownBlock2D",
308
+ "DownBlock2D",
309
+ ),
310
+ sample_size: Optional[int] = 96,
311
+ transformer_layers_per_block: Union[int, Tuple[int]] = 1,
312
+ upcast_attention: bool = True,
313
+ max_norm_num_groups: int = 32,
314
+ use_linear_projection: bool = True,
315
+ ):
316
+ super().__init__()
317
+
318
+ time_embedding_input_dim = base_block_out_channels[0]
319
+ time_embedding_dim = base_block_out_channels[0] * 4
320
+
321
+ # Check inputs
322
+ if conditioning_channel_order not in ["rgb", "bgr"]:
323
+ raise ValueError(f"unknown `conditioning_channel_order`: {conditioning_channel_order}")
324
+
325
+ if len(block_out_channels) != len(down_block_types):
326
+ raise ValueError(
327
+ 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}."
328
+ )
329
+
330
+ if not isinstance(transformer_layers_per_block, (list, tuple)):
331
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
332
+ if not isinstance(cross_attention_dim, (list, tuple)):
333
+ cross_attention_dim = [cross_attention_dim] * len(down_block_types)
334
+ # see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why `ControlNetXSAdapter` takes `num_attention_heads` instead of `attention_head_dim`
335
+ if not isinstance(num_attention_heads, (list, tuple)):
336
+ num_attention_heads = [num_attention_heads] * len(down_block_types)
337
+
338
+ if len(num_attention_heads) != len(down_block_types):
339
+ raise ValueError(
340
+ 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}."
341
+ )
342
+
343
+ # 5 - Create conditioning hint embedding
344
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
345
+ conditioning_embedding_channels=block_out_channels[0],
346
+ block_out_channels=conditioning_embedding_out_channels,
347
+ conditioning_channels=conditioning_channels,
348
+ )
349
+
350
+ # time
351
+ if learn_time_embedding:
352
+ self.time_embedding = TimestepEmbedding(time_embedding_input_dim, time_embedding_dim)
353
+ else:
354
+ self.time_embedding = None
355
+
356
+ self.down_blocks = nn.ModuleList([])
357
+ self.up_connections = nn.ModuleList([])
358
+
359
+ # input
360
+ self.conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
361
+ self.control_to_base_for_conv_in = make_zero_conv(block_out_channels[0], base_block_out_channels[0])
362
+
363
+ # down
364
+ base_out_channels = base_block_out_channels[0]
365
+ ctrl_out_channels = block_out_channels[0]
366
+ for i, down_block_type in enumerate(down_block_types):
367
+ base_in_channels = base_out_channels
368
+ base_out_channels = base_block_out_channels[i]
369
+ ctrl_in_channels = ctrl_out_channels
370
+ ctrl_out_channels = block_out_channels[i]
371
+ has_crossattn = "CrossAttn" in down_block_type
372
+ is_final_block = i == len(down_block_types) - 1
373
+
374
+ self.down_blocks.append(
375
+ get_down_block_adapter(
376
+ base_in_channels=base_in_channels,
377
+ base_out_channels=base_out_channels,
378
+ ctrl_in_channels=ctrl_in_channels,
379
+ ctrl_out_channels=ctrl_out_channels,
380
+ temb_channels=time_embedding_dim,
381
+ max_norm_num_groups=max_norm_num_groups,
382
+ has_crossattn=has_crossattn,
383
+ transformer_layers_per_block=transformer_layers_per_block[i],
384
+ num_attention_heads=num_attention_heads[i],
385
+ cross_attention_dim=cross_attention_dim[i],
386
+ add_downsample=not is_final_block,
387
+ upcast_attention=upcast_attention,
388
+ use_linear_projection=use_linear_projection,
389
+ )
390
+ )
391
+
392
+ # mid
393
+ self.mid_block = get_mid_block_adapter(
394
+ base_channels=base_block_out_channels[-1],
395
+ ctrl_channels=block_out_channels[-1],
396
+ temb_channels=time_embedding_dim,
397
+ transformer_layers_per_block=transformer_layers_per_block[-1],
398
+ num_attention_heads=num_attention_heads[-1],
399
+ cross_attention_dim=cross_attention_dim[-1],
400
+ upcast_attention=upcast_attention,
401
+ use_linear_projection=use_linear_projection,
402
+ )
403
+
404
+ # up
405
+ # The skip connection channels are the output of the conv_in and of all the down subblocks
406
+ ctrl_skip_channels = [block_out_channels[0]]
407
+ for i, out_channels in enumerate(block_out_channels):
408
+ number_of_subblocks = (
409
+ 3 if i < len(block_out_channels) - 1 else 2
410
+ ) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
411
+ ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
412
+
413
+ reversed_base_block_out_channels = list(reversed(base_block_out_channels))
414
+
415
+ base_out_channels = reversed_base_block_out_channels[0]
416
+ for i in range(len(down_block_types)):
417
+ prev_base_output_channel = base_out_channels
418
+ base_out_channels = reversed_base_block_out_channels[i]
419
+ ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
420
+
421
+ self.up_connections.append(
422
+ get_up_block_adapter(
423
+ out_channels=base_out_channels,
424
+ prev_output_channel=prev_base_output_channel,
425
+ ctrl_skip_channels=ctrl_skip_channels_,
426
+ )
427
+ )
428
+
429
+ @classmethod
430
+ def from_unet(
431
+ cls,
432
+ unet: UNet2DConditionModel,
433
+ size_ratio: Optional[float] = None,
434
+ block_out_channels: Optional[List[int]] = None,
435
+ num_attention_heads: Optional[List[int]] = None,
436
+ learn_time_embedding: bool = False,
437
+ time_embedding_mix: int = 1.0,
438
+ conditioning_channels: int = 3,
439
+ conditioning_channel_order: str = "rgb",
440
+ conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
441
+ ):
442
+ r"""
443
+ Instantiate a [`ControlNetXSAdapter`] from a [`UNet2DConditionModel`].
444
+
445
+ Parameters:
446
+ unet (`UNet2DConditionModel`):
447
+ The UNet model we want to control. The dimensions of the ControlNetXSAdapter will be adapted to it.
448
+ size_ratio (float, *optional*, defaults to `None`):
449
+ When given, block_out_channels is set to a fraction of the base model's block_out_channels. Either this
450
+ or `block_out_channels` must be given.
451
+ block_out_channels (`List[int]`, *optional*, defaults to `None`):
452
+ Down blocks output channels in control model. Either this or `size_ratio` must be given.
453
+ num_attention_heads (`List[int]`, *optional*, defaults to `None`):
454
+ The dimension of the attention heads. The naming seems a bit confusing and it is, see
455
+ https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
456
+ learn_time_embedding (`bool`, defaults to `False`):
457
+ Whether the `ControlNetXSAdapter` should learn a time embedding.
458
+ time_embedding_mix (`float`, defaults to 1.0):
459
+ If 0, then only the control adapter's time embedding is used. If 1, then only the base unet's time
460
+ embedding is used. Otherwise, both are combined.
461
+ conditioning_channels (`int`, defaults to 3):
462
+ Number of channels of conditioning input (e.g. an image)
463
+ conditioning_channel_order (`str`, defaults to `"rgb"`):
464
+ The channel order of conditional image. Will convert to `rgb` if it's `bgr`.
465
+ conditioning_embedding_out_channels (`Tuple[int]`, defaults to `(16, 32, 96, 256)`):
466
+ The tuple of output channel for each block in the `controlnet_cond_embedding` layer.
467
+ """
468
+
469
+ # Check input
470
+ fixed_size = block_out_channels is not None
471
+ relative_size = size_ratio is not None
472
+ if not (fixed_size ^ relative_size):
473
+ raise ValueError(
474
+ "Pass exactly one of `block_out_channels` (for absolute sizing) or `size_ratio` (for relative sizing)."
475
+ )
476
+
477
+ # Create model
478
+ block_out_channels = block_out_channels or [int(b * size_ratio) for b in unet.config.block_out_channels]
479
+ if num_attention_heads is None:
480
+ # The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
481
+ num_attention_heads = unet.config.attention_head_dim
482
+
483
+ model = cls(
484
+ conditioning_channels=conditioning_channels,
485
+ conditioning_channel_order=conditioning_channel_order,
486
+ conditioning_embedding_out_channels=conditioning_embedding_out_channels,
487
+ time_embedding_mix=time_embedding_mix,
488
+ learn_time_embedding=learn_time_embedding,
489
+ num_attention_heads=num_attention_heads,
490
+ block_out_channels=block_out_channels,
491
+ base_block_out_channels=unet.config.block_out_channels,
492
+ cross_attention_dim=unet.config.cross_attention_dim,
493
+ down_block_types=unet.config.down_block_types,
494
+ sample_size=unet.config.sample_size,
495
+ transformer_layers_per_block=unet.config.transformer_layers_per_block,
496
+ upcast_attention=unet.config.upcast_attention,
497
+ max_norm_num_groups=unet.config.norm_num_groups,
498
+ use_linear_projection=unet.config.use_linear_projection,
499
+ )
500
+
501
+ # ensure that the ControlNetXSAdapter is the same dtype as the UNet2DConditionModel
502
+ model.to(unet.dtype)
503
+
504
+ return model
505
+
506
+ def forward(self, *args, **kwargs):
507
+ raise ValueError(
508
+ "A ControlNetXSAdapter cannot be run by itself. Use it together with a UNet2DConditionModel to instantiate a UNetControlNetXSModel."
509
+ )
510
+
511
+
512
+ class UNetControlNetXSModel(ModelMixin, ConfigMixin):
513
+ r"""
514
+ A UNet fused with a ControlNet-XS adapter model
515
+
516
+ This model inherits from [`ModelMixin`] and [`ConfigMixin`]. Check the superclass documentation for it's generic
517
+ methods implemented for all models (such as downloading or saving).
518
+
519
+ `UNetControlNetXSModel` is compatible with StableDiffusion and StableDiffusion-XL. It's default parameters are
520
+ compatible with StableDiffusion.
521
+
522
+ It's parameters are either passed to the underlying `UNet2DConditionModel` or used exactly like in
523
+ `ControlNetXSAdapter` . See their documentation for details.
524
+ """
525
+
526
+ _supports_gradient_checkpointing = True
527
+
528
+ @register_to_config
529
+ def __init__(
530
+ self,
531
+ # unet configs
532
+ sample_size: Optional[int] = 96,
533
+ down_block_types: Tuple[str] = (
534
+ "CrossAttnDownBlock2D",
535
+ "CrossAttnDownBlock2D",
536
+ "CrossAttnDownBlock2D",
537
+ "DownBlock2D",
538
+ ),
539
+ up_block_types: Tuple[str] = ("UpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D", "CrossAttnUpBlock2D"),
540
+ block_out_channels: Tuple[int] = (320, 640, 1280, 1280),
541
+ norm_num_groups: Optional[int] = 32,
542
+ cross_attention_dim: Union[int, Tuple[int]] = 1024,
543
+ transformer_layers_per_block: Union[int, Tuple[int]] = 1,
544
+ num_attention_heads: Union[int, Tuple[int]] = 8,
545
+ addition_embed_type: Optional[str] = None,
546
+ addition_time_embed_dim: Optional[int] = None,
547
+ upcast_attention: bool = True,
548
+ use_linear_projection: bool = True,
549
+ time_cond_proj_dim: Optional[int] = None,
550
+ projection_class_embeddings_input_dim: Optional[int] = None,
551
+ # additional controlnet configs
552
+ time_embedding_mix: float = 1.0,
553
+ ctrl_conditioning_channels: int = 3,
554
+ ctrl_conditioning_embedding_out_channels: Tuple[int] = (16, 32, 96, 256),
555
+ ctrl_conditioning_channel_order: str = "rgb",
556
+ ctrl_learn_time_embedding: bool = False,
557
+ ctrl_block_out_channels: Tuple[int] = (4, 8, 16, 16),
558
+ ctrl_num_attention_heads: Union[int, Tuple[int]] = 4,
559
+ ctrl_max_norm_num_groups: int = 32,
560
+ ):
561
+ super().__init__()
562
+
563
+ if time_embedding_mix < 0 or time_embedding_mix > 1:
564
+ raise ValueError("`time_embedding_mix` needs to be between 0 and 1.")
565
+ if time_embedding_mix < 1 and not ctrl_learn_time_embedding:
566
+ raise ValueError("To use `time_embedding_mix` < 1, `ctrl_learn_time_embedding` must be `True`")
567
+
568
+ if addition_embed_type is not None and addition_embed_type != "text_time":
569
+ raise ValueError(
570
+ "As `UNetControlNetXSModel` currently only supports StableDiffusion and StableDiffusion-XL, `addition_embed_type` must be `None` or `'text_time'`."
571
+ )
572
+
573
+ if not isinstance(transformer_layers_per_block, (list, tuple)):
574
+ transformer_layers_per_block = [transformer_layers_per_block] * len(down_block_types)
575
+ if not isinstance(cross_attention_dim, (list, tuple)):
576
+ cross_attention_dim = [cross_attention_dim] * len(down_block_types)
577
+ if not isinstance(num_attention_heads, (list, tuple)):
578
+ num_attention_heads = [num_attention_heads] * len(down_block_types)
579
+ if not isinstance(ctrl_num_attention_heads, (list, tuple)):
580
+ ctrl_num_attention_heads = [ctrl_num_attention_heads] * len(down_block_types)
581
+
582
+ base_num_attention_heads = num_attention_heads
583
+
584
+ self.in_channels = 4
585
+
586
+ # # Input
587
+ self.base_conv_in = nn.Conv2d(4, block_out_channels[0], kernel_size=3, padding=1)
588
+ self.controlnet_cond_embedding = ControlNetConditioningEmbedding(
589
+ conditioning_embedding_channels=ctrl_block_out_channels[0],
590
+ block_out_channels=ctrl_conditioning_embedding_out_channels,
591
+ conditioning_channels=ctrl_conditioning_channels,
592
+ )
593
+ self.ctrl_conv_in = nn.Conv2d(4, ctrl_block_out_channels[0], kernel_size=3, padding=1)
594
+ self.control_to_base_for_conv_in = make_zero_conv(ctrl_block_out_channels[0], block_out_channels[0])
595
+
596
+ # # Time
597
+ time_embed_input_dim = block_out_channels[0]
598
+ time_embed_dim = block_out_channels[0] * 4
599
+
600
+ self.base_time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos=True, downscale_freq_shift=0)
601
+ self.base_time_embedding = TimestepEmbedding(
602
+ time_embed_input_dim,
603
+ time_embed_dim,
604
+ cond_proj_dim=time_cond_proj_dim,
605
+ )
606
+ if ctrl_learn_time_embedding:
607
+ self.ctrl_time_embedding = TimestepEmbedding(
608
+ in_channels=time_embed_input_dim, time_embed_dim=time_embed_dim
609
+ )
610
+ else:
611
+ self.ctrl_time_embedding = None
612
+
613
+ if addition_embed_type is None:
614
+ self.base_add_time_proj = None
615
+ self.base_add_embedding = None
616
+ else:
617
+ self.base_add_time_proj = Timesteps(addition_time_embed_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
618
+ self.base_add_embedding = TimestepEmbedding(projection_class_embeddings_input_dim, time_embed_dim)
619
+
620
+ # # Create down blocks
621
+ down_blocks = []
622
+ base_out_channels = block_out_channels[0]
623
+ ctrl_out_channels = ctrl_block_out_channels[0]
624
+ for i, down_block_type in enumerate(down_block_types):
625
+ base_in_channels = base_out_channels
626
+ base_out_channels = block_out_channels[i]
627
+ ctrl_in_channels = ctrl_out_channels
628
+ ctrl_out_channels = ctrl_block_out_channels[i]
629
+ has_crossattn = "CrossAttn" in down_block_type
630
+ is_final_block = i == len(down_block_types) - 1
631
+
632
+ down_blocks.append(
633
+ ControlNetXSCrossAttnDownBlock2D(
634
+ base_in_channels=base_in_channels,
635
+ base_out_channels=base_out_channels,
636
+ ctrl_in_channels=ctrl_in_channels,
637
+ ctrl_out_channels=ctrl_out_channels,
638
+ temb_channels=time_embed_dim,
639
+ norm_num_groups=norm_num_groups,
640
+ ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
641
+ has_crossattn=has_crossattn,
642
+ transformer_layers_per_block=transformer_layers_per_block[i],
643
+ base_num_attention_heads=base_num_attention_heads[i],
644
+ ctrl_num_attention_heads=ctrl_num_attention_heads[i],
645
+ cross_attention_dim=cross_attention_dim[i],
646
+ add_downsample=not is_final_block,
647
+ upcast_attention=upcast_attention,
648
+ use_linear_projection=use_linear_projection,
649
+ )
650
+ )
651
+
652
+ # # Create mid block
653
+ self.mid_block = ControlNetXSCrossAttnMidBlock2D(
654
+ base_channels=block_out_channels[-1],
655
+ ctrl_channels=ctrl_block_out_channels[-1],
656
+ temb_channels=time_embed_dim,
657
+ norm_num_groups=norm_num_groups,
658
+ ctrl_max_norm_num_groups=ctrl_max_norm_num_groups,
659
+ transformer_layers_per_block=transformer_layers_per_block[-1],
660
+ base_num_attention_heads=base_num_attention_heads[-1],
661
+ ctrl_num_attention_heads=ctrl_num_attention_heads[-1],
662
+ cross_attention_dim=cross_attention_dim[-1],
663
+ upcast_attention=upcast_attention,
664
+ use_linear_projection=use_linear_projection,
665
+ )
666
+
667
+ # # Create up blocks
668
+ up_blocks = []
669
+ rev_transformer_layers_per_block = list(reversed(transformer_layers_per_block))
670
+ rev_num_attention_heads = list(reversed(base_num_attention_heads))
671
+ rev_cross_attention_dim = list(reversed(cross_attention_dim))
672
+
673
+ # The skip connection channels are the output of the conv_in and of all the down subblocks
674
+ ctrl_skip_channels = [ctrl_block_out_channels[0]]
675
+ for i, out_channels in enumerate(ctrl_block_out_channels):
676
+ number_of_subblocks = (
677
+ 3 if i < len(ctrl_block_out_channels) - 1 else 2
678
+ ) # every block has 3 subblocks, except last one, which has 2 as it has no downsampler
679
+ ctrl_skip_channels.extend([out_channels] * number_of_subblocks)
680
+
681
+ reversed_block_out_channels = list(reversed(block_out_channels))
682
+
683
+ out_channels = reversed_block_out_channels[0]
684
+ for i, up_block_type in enumerate(up_block_types):
685
+ prev_output_channel = out_channels
686
+ out_channels = reversed_block_out_channels[i]
687
+ in_channels = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)]
688
+ ctrl_skip_channels_ = [ctrl_skip_channels.pop() for _ in range(3)]
689
+
690
+ has_crossattn = "CrossAttn" in up_block_type
691
+ is_final_block = i == len(block_out_channels) - 1
692
+
693
+ up_blocks.append(
694
+ ControlNetXSCrossAttnUpBlock2D(
695
+ in_channels=in_channels,
696
+ out_channels=out_channels,
697
+ prev_output_channel=prev_output_channel,
698
+ ctrl_skip_channels=ctrl_skip_channels_,
699
+ temb_channels=time_embed_dim,
700
+ resolution_idx=i,
701
+ has_crossattn=has_crossattn,
702
+ transformer_layers_per_block=rev_transformer_layers_per_block[i],
703
+ num_attention_heads=rev_num_attention_heads[i],
704
+ cross_attention_dim=rev_cross_attention_dim[i],
705
+ add_upsample=not is_final_block,
706
+ upcast_attention=upcast_attention,
707
+ norm_num_groups=norm_num_groups,
708
+ use_linear_projection=use_linear_projection,
709
+ )
710
+ )
711
+
712
+ self.down_blocks = nn.ModuleList(down_blocks)
713
+ self.up_blocks = nn.ModuleList(up_blocks)
714
+
715
+ self.base_conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=norm_num_groups)
716
+ self.base_conv_act = nn.SiLU()
717
+ self.base_conv_out = nn.Conv2d(block_out_channels[0], 4, kernel_size=3, padding=1)
718
+
719
+ @classmethod
720
+ def from_unet(
721
+ cls,
722
+ unet: UNet2DConditionModel,
723
+ controlnet: Optional[ControlNetXSAdapter] = None,
724
+ size_ratio: Optional[float] = None,
725
+ ctrl_block_out_channels: Optional[List[float]] = None,
726
+ time_embedding_mix: Optional[float] = None,
727
+ ctrl_optional_kwargs: Optional[Dict] = None,
728
+ ):
729
+ r"""
730
+ Instantiate a [`UNetControlNetXSModel`] from a [`UNet2DConditionModel`] and an optional [`ControlNetXSAdapter`]
731
+ .
732
+
733
+ Parameters:
734
+ unet (`UNet2DConditionModel`):
735
+ The UNet model we want to control.
736
+ controlnet (`ControlNetXSAdapter`):
737
+ The ConntrolNet-XS adapter with which the UNet will be fused. If none is given, a new ConntrolNet-XS
738
+ adapter will be created.
739
+ size_ratio (float, *optional*, defaults to `None`):
740
+ Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
741
+ ctrl_block_out_channels (`List[int]`, *optional*, defaults to `None`):
742
+ Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details,
743
+ where this parameter is called `block_out_channels`.
744
+ time_embedding_mix (`float`, *optional*, defaults to None):
745
+ Used to contruct the controlnet if none is given. See [`ControlNetXSAdapter.from_unet`] for details.
746
+ ctrl_optional_kwargs (`Dict`, *optional*, defaults to `None`):
747
+ Passed to the `init` of the new controlent if no controlent was given.
748
+ """
749
+ if controlnet is None:
750
+ controlnet = ControlNetXSAdapter.from_unet(
751
+ unet, size_ratio, ctrl_block_out_channels, **ctrl_optional_kwargs
752
+ )
753
+ else:
754
+ if any(
755
+ o is not None for o in (size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs)
756
+ ):
757
+ raise ValueError(
758
+ "When a controlnet is passed, none of these parameters should be passed: size_ratio, ctrl_block_out_channels, time_embedding_mix, ctrl_optional_kwargs."
759
+ )
760
+
761
+ # # get params
762
+ params_for_unet = [
763
+ "sample_size",
764
+ "down_block_types",
765
+ "up_block_types",
766
+ "block_out_channels",
767
+ "norm_num_groups",
768
+ "cross_attention_dim",
769
+ "transformer_layers_per_block",
770
+ "addition_embed_type",
771
+ "addition_time_embed_dim",
772
+ "upcast_attention",
773
+ "use_linear_projection",
774
+ "time_cond_proj_dim",
775
+ "projection_class_embeddings_input_dim",
776
+ ]
777
+ params_for_unet = {k: v for k, v in unet.config.items() if k in params_for_unet}
778
+ # The naming seems a bit confusing and it is, see https://github.com/huggingface/diffusers/issues/2011#issuecomment-1547958131 for why.
779
+ params_for_unet["num_attention_heads"] = unet.config.attention_head_dim
780
+
781
+ params_for_controlnet = [
782
+ "conditioning_channels",
783
+ "conditioning_embedding_out_channels",
784
+ "conditioning_channel_order",
785
+ "learn_time_embedding",
786
+ "block_out_channels",
787
+ "num_attention_heads",
788
+ "max_norm_num_groups",
789
+ ]
790
+ params_for_controlnet = {"ctrl_" + k: v for k, v in controlnet.config.items() if k in params_for_controlnet}
791
+ params_for_controlnet["time_embedding_mix"] = controlnet.config.time_embedding_mix
792
+
793
+ # # create model
794
+ model = cls.from_config({**params_for_unet, **params_for_controlnet})
795
+
796
+ # # load weights
797
+ # from unet
798
+ modules_from_unet = [
799
+ "time_embedding",
800
+ "conv_in",
801
+ "conv_norm_out",
802
+ "conv_out",
803
+ ]
804
+ for m in modules_from_unet:
805
+ getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
806
+
807
+ optional_modules_from_unet = [
808
+ "add_time_proj",
809
+ "add_embedding",
810
+ ]
811
+ for m in optional_modules_from_unet:
812
+ if hasattr(unet, m) and getattr(unet, m) is not None:
813
+ getattr(model, "base_" + m).load_state_dict(getattr(unet, m).state_dict())
814
+
815
+ # from controlnet
816
+ model.controlnet_cond_embedding.load_state_dict(controlnet.controlnet_cond_embedding.state_dict())
817
+ model.ctrl_conv_in.load_state_dict(controlnet.conv_in.state_dict())
818
+ if controlnet.time_embedding is not None:
819
+ model.ctrl_time_embedding.load_state_dict(controlnet.time_embedding.state_dict())
820
+ model.control_to_base_for_conv_in.load_state_dict(controlnet.control_to_base_for_conv_in.state_dict())
821
+
822
+ # from both
823
+ model.down_blocks = nn.ModuleList(
824
+ ControlNetXSCrossAttnDownBlock2D.from_modules(b, c)
825
+ for b, c in zip(unet.down_blocks, controlnet.down_blocks)
826
+ )
827
+ model.mid_block = ControlNetXSCrossAttnMidBlock2D.from_modules(unet.mid_block, controlnet.mid_block)
828
+ model.up_blocks = nn.ModuleList(
829
+ ControlNetXSCrossAttnUpBlock2D.from_modules(b, c)
830
+ for b, c in zip(unet.up_blocks, controlnet.up_connections)
831
+ )
832
+
833
+ # ensure that the UNetControlNetXSModel is the same dtype as the UNet2DConditionModel
834
+ model.to(unet.dtype)
835
+
836
+ return model
837
+
838
+ def freeze_unet_params(self) -> None:
839
+ """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
840
+ tuning."""
841
+ # Freeze everything
842
+ for param in self.parameters():
843
+ param.requires_grad = True
844
+
845
+ # Unfreeze ControlNetXSAdapter
846
+ base_parts = [
847
+ "base_time_proj",
848
+ "base_time_embedding",
849
+ "base_add_time_proj",
850
+ "base_add_embedding",
851
+ "base_conv_in",
852
+ "base_conv_norm_out",
853
+ "base_conv_act",
854
+ "base_conv_out",
855
+ ]
856
+ base_parts = [getattr(self, part) for part in base_parts if getattr(self, part) is not None]
857
+ for part in base_parts:
858
+ for param in part.parameters():
859
+ param.requires_grad = False
860
+
861
+ for d in self.down_blocks:
862
+ d.freeze_base_params()
863
+ self.mid_block.freeze_base_params()
864
+ for u in self.up_blocks:
865
+ u.freeze_base_params()
866
+
867
+ @property
868
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
869
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
870
+ r"""
871
+ Returns:
872
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
873
+ indexed by its weight name.
874
+ """
875
+ # set recursively
876
+ processors = {}
877
+
878
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
879
+ if hasattr(module, "get_processor"):
880
+ processors[f"{name}.processor"] = module.get_processor()
881
+
882
+ for sub_name, child in module.named_children():
883
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
884
+
885
+ return processors
886
+
887
+ for name, module in self.named_children():
888
+ fn_recursive_add_processors(name, module, processors)
889
+
890
+ return processors
891
+
892
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
893
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
894
+ r"""
895
+ Sets the attention processor to use to compute attention.
896
+
897
+ Parameters:
898
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
899
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
900
+ for **all** `Attention` layers.
901
+
902
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
903
+ processor. This is strongly recommended when setting trainable attention processors.
904
+
905
+ """
906
+ count = len(self.attn_processors.keys())
907
+
908
+ if isinstance(processor, dict) and len(processor) != count:
909
+ raise ValueError(
910
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
911
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
912
+ )
913
+
914
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
915
+ if hasattr(module, "set_processor"):
916
+ if not isinstance(processor, dict):
917
+ module.set_processor(processor)
918
+ else:
919
+ module.set_processor(processor.pop(f"{name}.processor"))
920
+
921
+ for sub_name, child in module.named_children():
922
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
923
+
924
+ for name, module in self.named_children():
925
+ fn_recursive_attn_processor(name, module, processor)
926
+
927
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
928
+ def set_default_attn_processor(self):
929
+ """
930
+ Disables custom attention processors and sets the default attention implementation.
931
+ """
932
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
933
+ processor = AttnAddedKVProcessor()
934
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
935
+ processor = AttnProcessor()
936
+ else:
937
+ raise ValueError(
938
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
939
+ )
940
+
941
+ self.set_attn_processor(processor)
942
+
943
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.enable_freeu
944
+ def enable_freeu(self, s1: float, s2: float, b1: float, b2: float):
945
+ r"""Enables the FreeU mechanism from https://arxiv.org/abs/2309.11497.
946
+
947
+ The suffixes after the scaling factors represent the stage blocks where they are being applied.
948
+
949
+ Please refer to the [official repository](https://github.com/ChenyangSi/FreeU) for combinations of values that
950
+ are known to work well for different pipelines such as Stable Diffusion v1, v2, and Stable Diffusion XL.
951
+
952
+ Args:
953
+ s1 (`float`):
954
+ Scaling factor for stage 1 to attenuate the contributions of the skip features. This is done to
955
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
956
+ s2 (`float`):
957
+ Scaling factor for stage 2 to attenuate the contributions of the skip features. This is done to
958
+ mitigate the "oversmoothing effect" in the enhanced denoising process.
959
+ b1 (`float`): Scaling factor for stage 1 to amplify the contributions of backbone features.
960
+ b2 (`float`): Scaling factor for stage 2 to amplify the contributions of backbone features.
961
+ """
962
+ for i, upsample_block in enumerate(self.up_blocks):
963
+ setattr(upsample_block, "s1", s1)
964
+ setattr(upsample_block, "s2", s2)
965
+ setattr(upsample_block, "b1", b1)
966
+ setattr(upsample_block, "b2", b2)
967
+
968
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.disable_freeu
969
+ def disable_freeu(self):
970
+ """Disables the FreeU mechanism."""
971
+ freeu_keys = {"s1", "s2", "b1", "b2"}
972
+ for i, upsample_block in enumerate(self.up_blocks):
973
+ for k in freeu_keys:
974
+ if hasattr(upsample_block, k) or getattr(upsample_block, k, None) is not None:
975
+ setattr(upsample_block, k, None)
976
+
977
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
978
+ def fuse_qkv_projections(self):
979
+ """
980
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
981
+ are fused. For cross-attention modules, key and value projection matrices are fused.
982
+
983
+ <Tip warning={true}>
984
+
985
+ This API is 🧪 experimental.
986
+
987
+ </Tip>
988
+ """
989
+ self.original_attn_processors = None
990
+
991
+ for _, attn_processor in self.attn_processors.items():
992
+ if "Added" in str(attn_processor.__class__.__name__):
993
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
994
+
995
+ self.original_attn_processors = self.attn_processors
996
+
997
+ for module in self.modules():
998
+ if isinstance(module, Attention):
999
+ module.fuse_projections(fuse=True)
1000
+
1001
+ self.set_attn_processor(FusedAttnProcessor2_0())
1002
+
1003
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
1004
+ def unfuse_qkv_projections(self):
1005
+ """Disables the fused QKV projection if enabled.
1006
+
1007
+ <Tip warning={true}>
1008
+
1009
+ This API is 🧪 experimental.
1010
+
1011
+ </Tip>
1012
+
1013
+ """
1014
+ if self.original_attn_processors is not None:
1015
+ self.set_attn_processor(self.original_attn_processors)
1016
+
1017
+ def forward(
1018
+ self,
1019
+ sample: Tensor,
1020
+ timestep: Union[torch.Tensor, float, int],
1021
+ encoder_hidden_states: torch.Tensor,
1022
+ controlnet_cond: Optional[torch.Tensor] = None,
1023
+ conditioning_scale: Optional[float] = 1.0,
1024
+ class_labels: Optional[torch.Tensor] = None,
1025
+ timestep_cond: Optional[torch.Tensor] = None,
1026
+ attention_mask: Optional[torch.Tensor] = None,
1027
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1028
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
1029
+ return_dict: bool = True,
1030
+ apply_control: bool = True,
1031
+ ) -> Union[ControlNetXSOutput, Tuple]:
1032
+ """
1033
+ The [`ControlNetXSModel`] forward method.
1034
+
1035
+ Args:
1036
+ sample (`Tensor`):
1037
+ The noisy input tensor.
1038
+ timestep (`Union[torch.Tensor, float, int]`):
1039
+ The number of timesteps to denoise an input.
1040
+ encoder_hidden_states (`torch.Tensor`):
1041
+ The encoder hidden states.
1042
+ controlnet_cond (`Tensor`):
1043
+ The conditional input tensor of shape `(batch_size, sequence_length, hidden_size)`.
1044
+ conditioning_scale (`float`, defaults to `1.0`):
1045
+ How much the control model affects the base model outputs.
1046
+ class_labels (`torch.Tensor`, *optional*, defaults to `None`):
1047
+ Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
1048
+ timestep_cond (`torch.Tensor`, *optional*, defaults to `None`):
1049
+ Additional conditional embeddings for timestep. If provided, the embeddings will be summed with the
1050
+ timestep_embedding passed through the `self.time_embedding` layer to obtain the final timestep
1051
+ embeddings.
1052
+ attention_mask (`torch.Tensor`, *optional*, defaults to `None`):
1053
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
1054
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
1055
+ negative values to the attention scores corresponding to "discard" tokens.
1056
+ cross_attention_kwargs (`dict[str]`, *optional*, defaults to `None`):
1057
+ A kwargs dictionary that if specified is passed along to the `AttnProcessor`.
1058
+ added_cond_kwargs (`dict`):
1059
+ Additional conditions for the Stable Diffusion XL UNet.
1060
+ return_dict (`bool`, defaults to `True`):
1061
+ Whether or not to return a [`~models.controlnets.controlnet.ControlNetOutput`] instead of a plain
1062
+ tuple.
1063
+ apply_control (`bool`, defaults to `True`):
1064
+ If `False`, the input is run only through the base model.
1065
+
1066
+ Returns:
1067
+ [`~models.controlnetxs.ControlNetXSOutput`] **or** `tuple`:
1068
+ If `return_dict` is `True`, a [`~models.controlnetxs.ControlNetXSOutput`] is returned, otherwise a
1069
+ tuple is returned where the first element is the sample tensor.
1070
+ """
1071
+
1072
+ # check channel order
1073
+ if self.config.ctrl_conditioning_channel_order == "bgr":
1074
+ controlnet_cond = torch.flip(controlnet_cond, dims=[1])
1075
+
1076
+ # prepare attention_mask
1077
+ if attention_mask is not None:
1078
+ attention_mask = (1 - attention_mask.to(sample.dtype)) * -10000.0
1079
+ attention_mask = attention_mask.unsqueeze(1)
1080
+
1081
+ # 1. time
1082
+ timesteps = timestep
1083
+ if not torch.is_tensor(timesteps):
1084
+ # TODO: this requires sync between CPU and GPU. So try to pass timesteps as tensors if you can
1085
+ # This would be a good case for the `match` statement (Python 3.10+)
1086
+ is_mps = sample.device.type == "mps"
1087
+ is_npu = sample.device.type == "npu"
1088
+ if isinstance(timestep, float):
1089
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
1090
+ else:
1091
+ dtype = torch.int32 if (is_mps or is_npu) else torch.int64
1092
+ timesteps = torch.tensor([timesteps], dtype=dtype, device=sample.device)
1093
+ elif len(timesteps.shape) == 0:
1094
+ timesteps = timesteps[None].to(sample.device)
1095
+
1096
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
1097
+ timesteps = timesteps.expand(sample.shape[0])
1098
+
1099
+ t_emb = self.base_time_proj(timesteps)
1100
+
1101
+ # timesteps does not contain any weights and will always return f32 tensors
1102
+ # but time_embedding might actually be running in fp16. so we need to cast here.
1103
+ # there might be better ways to encapsulate this.
1104
+ t_emb = t_emb.to(dtype=sample.dtype)
1105
+
1106
+ if self.config.ctrl_learn_time_embedding and apply_control:
1107
+ ctrl_temb = self.ctrl_time_embedding(t_emb, timestep_cond)
1108
+ base_temb = self.base_time_embedding(t_emb, timestep_cond)
1109
+ interpolation_param = self.config.time_embedding_mix**0.3
1110
+
1111
+ temb = ctrl_temb * interpolation_param + base_temb * (1 - interpolation_param)
1112
+ else:
1113
+ temb = self.base_time_embedding(t_emb)
1114
+
1115
+ # added time & text embeddings
1116
+ aug_emb = None
1117
+
1118
+ if self.config.addition_embed_type is None:
1119
+ pass
1120
+ elif self.config.addition_embed_type == "text_time":
1121
+ # SDXL - style
1122
+ if "text_embeds" not in added_cond_kwargs:
1123
+ raise ValueError(
1124
+ 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`"
1125
+ )
1126
+ text_embeds = added_cond_kwargs.get("text_embeds")
1127
+ if "time_ids" not in added_cond_kwargs:
1128
+ raise ValueError(
1129
+ 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`"
1130
+ )
1131
+ time_ids = added_cond_kwargs.get("time_ids")
1132
+ time_embeds = self.base_add_time_proj(time_ids.flatten())
1133
+ time_embeds = time_embeds.reshape((text_embeds.shape[0], -1))
1134
+ add_embeds = torch.concat([text_embeds, time_embeds], dim=-1)
1135
+ add_embeds = add_embeds.to(temb.dtype)
1136
+ aug_emb = self.base_add_embedding(add_embeds)
1137
+ else:
1138
+ raise ValueError(
1139
+ f"ControlNet-XS currently only supports StableDiffusion and StableDiffusion-XL, so addition_embed_type = {self.config.addition_embed_type} is currently not supported."
1140
+ )
1141
+
1142
+ temb = temb + aug_emb if aug_emb is not None else temb
1143
+
1144
+ # text embeddings
1145
+ cemb = encoder_hidden_states
1146
+
1147
+ # Preparation
1148
+ h_ctrl = h_base = sample
1149
+ hs_base, hs_ctrl = [], []
1150
+
1151
+ # Cross Control
1152
+ guided_hint = self.controlnet_cond_embedding(controlnet_cond)
1153
+
1154
+ # 1 - conv in & down
1155
+
1156
+ h_base = self.base_conv_in(h_base)
1157
+ h_ctrl = self.ctrl_conv_in(h_ctrl)
1158
+ if guided_hint is not None:
1159
+ h_ctrl += guided_hint
1160
+ if apply_control:
1161
+ h_base = h_base + self.control_to_base_for_conv_in(h_ctrl) * conditioning_scale # add ctrl -> base
1162
+
1163
+ hs_base.append(h_base)
1164
+ hs_ctrl.append(h_ctrl)
1165
+
1166
+ for down in self.down_blocks:
1167
+ h_base, h_ctrl, residual_hb, residual_hc = down(
1168
+ hidden_states_base=h_base,
1169
+ hidden_states_ctrl=h_ctrl,
1170
+ temb=temb,
1171
+ encoder_hidden_states=cemb,
1172
+ conditioning_scale=conditioning_scale,
1173
+ cross_attention_kwargs=cross_attention_kwargs,
1174
+ attention_mask=attention_mask,
1175
+ apply_control=apply_control,
1176
+ )
1177
+ hs_base.extend(residual_hb)
1178
+ hs_ctrl.extend(residual_hc)
1179
+
1180
+ # 2 - mid
1181
+ h_base, h_ctrl = self.mid_block(
1182
+ hidden_states_base=h_base,
1183
+ hidden_states_ctrl=h_ctrl,
1184
+ temb=temb,
1185
+ encoder_hidden_states=cemb,
1186
+ conditioning_scale=conditioning_scale,
1187
+ cross_attention_kwargs=cross_attention_kwargs,
1188
+ attention_mask=attention_mask,
1189
+ apply_control=apply_control,
1190
+ )
1191
+
1192
+ # 3 - up
1193
+ for up in self.up_blocks:
1194
+ n_resnets = len(up.resnets)
1195
+ skips_hb = hs_base[-n_resnets:]
1196
+ skips_hc = hs_ctrl[-n_resnets:]
1197
+ hs_base = hs_base[:-n_resnets]
1198
+ hs_ctrl = hs_ctrl[:-n_resnets]
1199
+ h_base = up(
1200
+ hidden_states=h_base,
1201
+ res_hidden_states_tuple_base=skips_hb,
1202
+ res_hidden_states_tuple_ctrl=skips_hc,
1203
+ temb=temb,
1204
+ encoder_hidden_states=cemb,
1205
+ conditioning_scale=conditioning_scale,
1206
+ cross_attention_kwargs=cross_attention_kwargs,
1207
+ attention_mask=attention_mask,
1208
+ apply_control=apply_control,
1209
+ )
1210
+
1211
+ # 4 - conv out
1212
+ h_base = self.base_conv_norm_out(h_base)
1213
+ h_base = self.base_conv_act(h_base)
1214
+ h_base = self.base_conv_out(h_base)
1215
+
1216
+ if not return_dict:
1217
+ return (h_base,)
1218
+
1219
+ return ControlNetXSOutput(sample=h_base)
1220
+
1221
+
1222
+ class ControlNetXSCrossAttnDownBlock2D(nn.Module):
1223
+ def __init__(
1224
+ self,
1225
+ base_in_channels: int,
1226
+ base_out_channels: int,
1227
+ ctrl_in_channels: int,
1228
+ ctrl_out_channels: int,
1229
+ temb_channels: int,
1230
+ norm_num_groups: int = 32,
1231
+ ctrl_max_norm_num_groups: int = 32,
1232
+ has_crossattn=True,
1233
+ transformer_layers_per_block: Optional[Union[int, Tuple[int]]] = 1,
1234
+ base_num_attention_heads: Optional[int] = 1,
1235
+ ctrl_num_attention_heads: Optional[int] = 1,
1236
+ cross_attention_dim: Optional[int] = 1024,
1237
+ add_downsample: bool = True,
1238
+ upcast_attention: Optional[bool] = False,
1239
+ use_linear_projection: Optional[bool] = True,
1240
+ ):
1241
+ super().__init__()
1242
+ base_resnets = []
1243
+ base_attentions = []
1244
+ ctrl_resnets = []
1245
+ ctrl_attentions = []
1246
+ ctrl_to_base = []
1247
+ base_to_ctrl = []
1248
+
1249
+ num_layers = 2 # only support sd + sdxl
1250
+
1251
+ if isinstance(transformer_layers_per_block, int):
1252
+ transformer_layers_per_block = [transformer_layers_per_block] * num_layers
1253
+
1254
+ for i in range(num_layers):
1255
+ base_in_channels = base_in_channels if i == 0 else base_out_channels
1256
+ ctrl_in_channels = ctrl_in_channels if i == 0 else ctrl_out_channels
1257
+
1258
+ # Before the resnet/attention application, information is concatted from base to control.
1259
+ # Concat doesn't require change in number of channels
1260
+ base_to_ctrl.append(make_zero_conv(base_in_channels, base_in_channels))
1261
+
1262
+ base_resnets.append(
1263
+ ResnetBlock2D(
1264
+ in_channels=base_in_channels,
1265
+ out_channels=base_out_channels,
1266
+ temb_channels=temb_channels,
1267
+ groups=norm_num_groups,
1268
+ )
1269
+ )
1270
+ ctrl_resnets.append(
1271
+ ResnetBlock2D(
1272
+ in_channels=ctrl_in_channels + base_in_channels, # information from base is concatted to ctrl
1273
+ out_channels=ctrl_out_channels,
1274
+ temb_channels=temb_channels,
1275
+ groups=find_largest_factor(
1276
+ ctrl_in_channels + base_in_channels, max_factor=ctrl_max_norm_num_groups
1277
+ ),
1278
+ groups_out=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
1279
+ eps=1e-5,
1280
+ )
1281
+ )
1282
+
1283
+ if has_crossattn:
1284
+ base_attentions.append(
1285
+ Transformer2DModel(
1286
+ base_num_attention_heads,
1287
+ base_out_channels // base_num_attention_heads,
1288
+ in_channels=base_out_channels,
1289
+ num_layers=transformer_layers_per_block[i],
1290
+ cross_attention_dim=cross_attention_dim,
1291
+ use_linear_projection=use_linear_projection,
1292
+ upcast_attention=upcast_attention,
1293
+ norm_num_groups=norm_num_groups,
1294
+ )
1295
+ )
1296
+ ctrl_attentions.append(
1297
+ Transformer2DModel(
1298
+ ctrl_num_attention_heads,
1299
+ ctrl_out_channels // ctrl_num_attention_heads,
1300
+ in_channels=ctrl_out_channels,
1301
+ num_layers=transformer_layers_per_block[i],
1302
+ cross_attention_dim=cross_attention_dim,
1303
+ use_linear_projection=use_linear_projection,
1304
+ upcast_attention=upcast_attention,
1305
+ norm_num_groups=find_largest_factor(ctrl_out_channels, max_factor=ctrl_max_norm_num_groups),
1306
+ )
1307
+ )
1308
+
1309
+ # After the resnet/attention application, information is added from control to base
1310
+ # Addition requires change in number of channels
1311
+ ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
1312
+
1313
+ if add_downsample:
1314
+ # Before the downsampler application, information is concatted from base to control
1315
+ # Concat doesn't require change in number of channels
1316
+ base_to_ctrl.append(make_zero_conv(base_out_channels, base_out_channels))
1317
+
1318
+ self.base_downsamplers = Downsample2D(
1319
+ base_out_channels, use_conv=True, out_channels=base_out_channels, name="op"
1320
+ )
1321
+ self.ctrl_downsamplers = Downsample2D(
1322
+ ctrl_out_channels + base_out_channels, use_conv=True, out_channels=ctrl_out_channels, name="op"
1323
+ )
1324
+
1325
+ # After the downsampler application, information is added from control to base
1326
+ # Addition requires change in number of channels
1327
+ ctrl_to_base.append(make_zero_conv(ctrl_out_channels, base_out_channels))
1328
+ else:
1329
+ self.base_downsamplers = None
1330
+ self.ctrl_downsamplers = None
1331
+
1332
+ self.base_resnets = nn.ModuleList(base_resnets)
1333
+ self.ctrl_resnets = nn.ModuleList(ctrl_resnets)
1334
+ self.base_attentions = nn.ModuleList(base_attentions) if has_crossattn else [None] * num_layers
1335
+ self.ctrl_attentions = nn.ModuleList(ctrl_attentions) if has_crossattn else [None] * num_layers
1336
+ self.base_to_ctrl = nn.ModuleList(base_to_ctrl)
1337
+ self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
1338
+
1339
+ self.gradient_checkpointing = False
1340
+
1341
+ @classmethod
1342
+ def from_modules(cls, base_downblock: CrossAttnDownBlock2D, ctrl_downblock: DownBlockControlNetXSAdapter):
1343
+ # get params
1344
+ def get_first_cross_attention(block):
1345
+ return block.attentions[0].transformer_blocks[0].attn2
1346
+
1347
+ base_in_channels = base_downblock.resnets[0].in_channels
1348
+ base_out_channels = base_downblock.resnets[0].out_channels
1349
+ ctrl_in_channels = (
1350
+ ctrl_downblock.resnets[0].in_channels - base_in_channels
1351
+ ) # base channels are concatted to ctrl channels in init
1352
+ ctrl_out_channels = ctrl_downblock.resnets[0].out_channels
1353
+ temb_channels = base_downblock.resnets[0].time_emb_proj.in_features
1354
+ num_groups = base_downblock.resnets[0].norm1.num_groups
1355
+ ctrl_num_groups = ctrl_downblock.resnets[0].norm1.num_groups
1356
+ if hasattr(base_downblock, "attentions"):
1357
+ has_crossattn = True
1358
+ transformer_layers_per_block = len(base_downblock.attentions[0].transformer_blocks)
1359
+ base_num_attention_heads = get_first_cross_attention(base_downblock).heads
1360
+ ctrl_num_attention_heads = get_first_cross_attention(ctrl_downblock).heads
1361
+ cross_attention_dim = get_first_cross_attention(base_downblock).cross_attention_dim
1362
+ upcast_attention = get_first_cross_attention(base_downblock).upcast_attention
1363
+ use_linear_projection = base_downblock.attentions[0].use_linear_projection
1364
+ else:
1365
+ has_crossattn = False
1366
+ transformer_layers_per_block = None
1367
+ base_num_attention_heads = None
1368
+ ctrl_num_attention_heads = None
1369
+ cross_attention_dim = None
1370
+ upcast_attention = None
1371
+ use_linear_projection = None
1372
+ add_downsample = base_downblock.downsamplers is not None
1373
+
1374
+ # create model
1375
+ model = cls(
1376
+ base_in_channels=base_in_channels,
1377
+ base_out_channels=base_out_channels,
1378
+ ctrl_in_channels=ctrl_in_channels,
1379
+ ctrl_out_channels=ctrl_out_channels,
1380
+ temb_channels=temb_channels,
1381
+ norm_num_groups=num_groups,
1382
+ ctrl_max_norm_num_groups=ctrl_num_groups,
1383
+ has_crossattn=has_crossattn,
1384
+ transformer_layers_per_block=transformer_layers_per_block,
1385
+ base_num_attention_heads=base_num_attention_heads,
1386
+ ctrl_num_attention_heads=ctrl_num_attention_heads,
1387
+ cross_attention_dim=cross_attention_dim,
1388
+ add_downsample=add_downsample,
1389
+ upcast_attention=upcast_attention,
1390
+ use_linear_projection=use_linear_projection,
1391
+ )
1392
+
1393
+ # # load weights
1394
+ model.base_resnets.load_state_dict(base_downblock.resnets.state_dict())
1395
+ model.ctrl_resnets.load_state_dict(ctrl_downblock.resnets.state_dict())
1396
+ if has_crossattn:
1397
+ model.base_attentions.load_state_dict(base_downblock.attentions.state_dict())
1398
+ model.ctrl_attentions.load_state_dict(ctrl_downblock.attentions.state_dict())
1399
+ if add_downsample:
1400
+ model.base_downsamplers.load_state_dict(base_downblock.downsamplers[0].state_dict())
1401
+ model.ctrl_downsamplers.load_state_dict(ctrl_downblock.downsamplers.state_dict())
1402
+ model.base_to_ctrl.load_state_dict(ctrl_downblock.base_to_ctrl.state_dict())
1403
+ model.ctrl_to_base.load_state_dict(ctrl_downblock.ctrl_to_base.state_dict())
1404
+
1405
+ return model
1406
+
1407
+ def freeze_base_params(self) -> None:
1408
+ """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
1409
+ tuning."""
1410
+ # Unfreeze everything
1411
+ for param in self.parameters():
1412
+ param.requires_grad = True
1413
+
1414
+ # Freeze base part
1415
+ base_parts = [self.base_resnets]
1416
+ if isinstance(self.base_attentions, nn.ModuleList): # attentions can be a list of Nones
1417
+ base_parts.append(self.base_attentions)
1418
+ if self.base_downsamplers is not None:
1419
+ base_parts.append(self.base_downsamplers)
1420
+ for part in base_parts:
1421
+ for param in part.parameters():
1422
+ param.requires_grad = False
1423
+
1424
+ def forward(
1425
+ self,
1426
+ hidden_states_base: Tensor,
1427
+ temb: Tensor,
1428
+ encoder_hidden_states: Optional[Tensor] = None,
1429
+ hidden_states_ctrl: Optional[Tensor] = None,
1430
+ conditioning_scale: Optional[float] = 1.0,
1431
+ attention_mask: Optional[Tensor] = None,
1432
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1433
+ encoder_attention_mask: Optional[Tensor] = None,
1434
+ apply_control: bool = True,
1435
+ ) -> Tuple[Tensor, Tensor, Tuple[Tensor, ...], Tuple[Tensor, ...]]:
1436
+ if cross_attention_kwargs is not None:
1437
+ if cross_attention_kwargs.get("scale", None) is not None:
1438
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
1439
+
1440
+ h_base = hidden_states_base
1441
+ h_ctrl = hidden_states_ctrl
1442
+
1443
+ base_output_states = ()
1444
+ ctrl_output_states = ()
1445
+
1446
+ base_blocks = list(zip(self.base_resnets, self.base_attentions))
1447
+ ctrl_blocks = list(zip(self.ctrl_resnets, self.ctrl_attentions))
1448
+
1449
+ for (b_res, b_attn), (c_res, c_attn), b2c, c2b in zip(
1450
+ base_blocks, ctrl_blocks, self.base_to_ctrl, self.ctrl_to_base
1451
+ ):
1452
+ # concat base -> ctrl
1453
+ if apply_control:
1454
+ h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
1455
+
1456
+ # apply base subblock
1457
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
1458
+ h_base = self._gradient_checkpointing_func(b_res, h_base, temb)
1459
+ else:
1460
+ h_base = b_res(h_base, temb)
1461
+
1462
+ if b_attn is not None:
1463
+ h_base = b_attn(
1464
+ h_base,
1465
+ encoder_hidden_states=encoder_hidden_states,
1466
+ cross_attention_kwargs=cross_attention_kwargs,
1467
+ attention_mask=attention_mask,
1468
+ encoder_attention_mask=encoder_attention_mask,
1469
+ return_dict=False,
1470
+ )[0]
1471
+
1472
+ # apply ctrl subblock
1473
+ if apply_control:
1474
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
1475
+ h_ctrl = self._gradient_checkpointing_func(c_res, h_ctrl, temb)
1476
+ else:
1477
+ h_ctrl = c_res(h_ctrl, temb)
1478
+ if c_attn is not None:
1479
+ h_ctrl = c_attn(
1480
+ h_ctrl,
1481
+ encoder_hidden_states=encoder_hidden_states,
1482
+ cross_attention_kwargs=cross_attention_kwargs,
1483
+ attention_mask=attention_mask,
1484
+ encoder_attention_mask=encoder_attention_mask,
1485
+ return_dict=False,
1486
+ )[0]
1487
+
1488
+ # add ctrl -> base
1489
+ if apply_control:
1490
+ h_base = h_base + c2b(h_ctrl) * conditioning_scale
1491
+
1492
+ base_output_states = base_output_states + (h_base,)
1493
+ ctrl_output_states = ctrl_output_states + (h_ctrl,)
1494
+
1495
+ if self.base_downsamplers is not None: # if we have a base_downsampler, then also a ctrl_downsampler
1496
+ b2c = self.base_to_ctrl[-1]
1497
+ c2b = self.ctrl_to_base[-1]
1498
+
1499
+ # concat base -> ctrl
1500
+ if apply_control:
1501
+ h_ctrl = torch.cat([h_ctrl, b2c(h_base)], dim=1)
1502
+ # apply base subblock
1503
+ h_base = self.base_downsamplers(h_base)
1504
+ # apply ctrl subblock
1505
+ if apply_control:
1506
+ h_ctrl = self.ctrl_downsamplers(h_ctrl)
1507
+ # add ctrl -> base
1508
+ if apply_control:
1509
+ h_base = h_base + c2b(h_ctrl) * conditioning_scale
1510
+
1511
+ base_output_states = base_output_states + (h_base,)
1512
+ ctrl_output_states = ctrl_output_states + (h_ctrl,)
1513
+
1514
+ return h_base, h_ctrl, base_output_states, ctrl_output_states
1515
+
1516
+
1517
+ class ControlNetXSCrossAttnMidBlock2D(nn.Module):
1518
+ def __init__(
1519
+ self,
1520
+ base_channels: int,
1521
+ ctrl_channels: int,
1522
+ temb_channels: Optional[int] = None,
1523
+ norm_num_groups: int = 32,
1524
+ ctrl_max_norm_num_groups: int = 32,
1525
+ transformer_layers_per_block: int = 1,
1526
+ base_num_attention_heads: Optional[int] = 1,
1527
+ ctrl_num_attention_heads: Optional[int] = 1,
1528
+ cross_attention_dim: Optional[int] = 1024,
1529
+ upcast_attention: bool = False,
1530
+ use_linear_projection: Optional[bool] = True,
1531
+ ):
1532
+ super().__init__()
1533
+
1534
+ # Before the midblock application, information is concatted from base to control.
1535
+ # Concat doesn't require change in number of channels
1536
+ self.base_to_ctrl = make_zero_conv(base_channels, base_channels)
1537
+
1538
+ self.base_midblock = UNetMidBlock2DCrossAttn(
1539
+ transformer_layers_per_block=transformer_layers_per_block,
1540
+ in_channels=base_channels,
1541
+ temb_channels=temb_channels,
1542
+ resnet_groups=norm_num_groups,
1543
+ cross_attention_dim=cross_attention_dim,
1544
+ num_attention_heads=base_num_attention_heads,
1545
+ use_linear_projection=use_linear_projection,
1546
+ upcast_attention=upcast_attention,
1547
+ )
1548
+
1549
+ self.ctrl_midblock = UNetMidBlock2DCrossAttn(
1550
+ transformer_layers_per_block=transformer_layers_per_block,
1551
+ in_channels=ctrl_channels + base_channels,
1552
+ out_channels=ctrl_channels,
1553
+ temb_channels=temb_channels,
1554
+ # number or norm groups must divide both in_channels and out_channels
1555
+ resnet_groups=find_largest_factor(
1556
+ gcd(ctrl_channels, ctrl_channels + base_channels), ctrl_max_norm_num_groups
1557
+ ),
1558
+ cross_attention_dim=cross_attention_dim,
1559
+ num_attention_heads=ctrl_num_attention_heads,
1560
+ use_linear_projection=use_linear_projection,
1561
+ upcast_attention=upcast_attention,
1562
+ )
1563
+
1564
+ # After the midblock application, information is added from control to base
1565
+ # Addition requires change in number of channels
1566
+ self.ctrl_to_base = make_zero_conv(ctrl_channels, base_channels)
1567
+
1568
+ self.gradient_checkpointing = False
1569
+
1570
+ @classmethod
1571
+ def from_modules(
1572
+ cls,
1573
+ base_midblock: UNetMidBlock2DCrossAttn,
1574
+ ctrl_midblock: MidBlockControlNetXSAdapter,
1575
+ ):
1576
+ base_to_ctrl = ctrl_midblock.base_to_ctrl
1577
+ ctrl_to_base = ctrl_midblock.ctrl_to_base
1578
+ ctrl_midblock = ctrl_midblock.midblock
1579
+
1580
+ # get params
1581
+ def get_first_cross_attention(midblock):
1582
+ return midblock.attentions[0].transformer_blocks[0].attn2
1583
+
1584
+ base_channels = ctrl_to_base.out_channels
1585
+ ctrl_channels = ctrl_to_base.in_channels
1586
+ transformer_layers_per_block = len(base_midblock.attentions[0].transformer_blocks)
1587
+ temb_channels = base_midblock.resnets[0].time_emb_proj.in_features
1588
+ num_groups = base_midblock.resnets[0].norm1.num_groups
1589
+ ctrl_num_groups = ctrl_midblock.resnets[0].norm1.num_groups
1590
+ base_num_attention_heads = get_first_cross_attention(base_midblock).heads
1591
+ ctrl_num_attention_heads = get_first_cross_attention(ctrl_midblock).heads
1592
+ cross_attention_dim = get_first_cross_attention(base_midblock).cross_attention_dim
1593
+ upcast_attention = get_first_cross_attention(base_midblock).upcast_attention
1594
+ use_linear_projection = base_midblock.attentions[0].use_linear_projection
1595
+
1596
+ # create model
1597
+ model = cls(
1598
+ base_channels=base_channels,
1599
+ ctrl_channels=ctrl_channels,
1600
+ temb_channels=temb_channels,
1601
+ norm_num_groups=num_groups,
1602
+ ctrl_max_norm_num_groups=ctrl_num_groups,
1603
+ transformer_layers_per_block=transformer_layers_per_block,
1604
+ base_num_attention_heads=base_num_attention_heads,
1605
+ ctrl_num_attention_heads=ctrl_num_attention_heads,
1606
+ cross_attention_dim=cross_attention_dim,
1607
+ upcast_attention=upcast_attention,
1608
+ use_linear_projection=use_linear_projection,
1609
+ )
1610
+
1611
+ # load weights
1612
+ model.base_to_ctrl.load_state_dict(base_to_ctrl.state_dict())
1613
+ model.base_midblock.load_state_dict(base_midblock.state_dict())
1614
+ model.ctrl_midblock.load_state_dict(ctrl_midblock.state_dict())
1615
+ model.ctrl_to_base.load_state_dict(ctrl_to_base.state_dict())
1616
+
1617
+ return model
1618
+
1619
+ def freeze_base_params(self) -> None:
1620
+ """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
1621
+ tuning."""
1622
+ # Unfreeze everything
1623
+ for param in self.parameters():
1624
+ param.requires_grad = True
1625
+
1626
+ # Freeze base part
1627
+ for param in self.base_midblock.parameters():
1628
+ param.requires_grad = False
1629
+
1630
+ def forward(
1631
+ self,
1632
+ hidden_states_base: Tensor,
1633
+ temb: Tensor,
1634
+ encoder_hidden_states: Tensor,
1635
+ hidden_states_ctrl: Optional[Tensor] = None,
1636
+ conditioning_scale: Optional[float] = 1.0,
1637
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1638
+ attention_mask: Optional[Tensor] = None,
1639
+ encoder_attention_mask: Optional[Tensor] = None,
1640
+ apply_control: bool = True,
1641
+ ) -> Tuple[Tensor, Tensor]:
1642
+ if cross_attention_kwargs is not None:
1643
+ if cross_attention_kwargs.get("scale", None) is not None:
1644
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
1645
+
1646
+ h_base = hidden_states_base
1647
+ h_ctrl = hidden_states_ctrl
1648
+
1649
+ joint_args = {
1650
+ "temb": temb,
1651
+ "encoder_hidden_states": encoder_hidden_states,
1652
+ "attention_mask": attention_mask,
1653
+ "cross_attention_kwargs": cross_attention_kwargs,
1654
+ "encoder_attention_mask": encoder_attention_mask,
1655
+ }
1656
+
1657
+ if apply_control:
1658
+ h_ctrl = torch.cat([h_ctrl, self.base_to_ctrl(h_base)], dim=1) # concat base -> ctrl
1659
+ h_base = self.base_midblock(h_base, **joint_args) # apply base mid block
1660
+ if apply_control:
1661
+ h_ctrl = self.ctrl_midblock(h_ctrl, **joint_args) # apply ctrl mid block
1662
+ h_base = h_base + self.ctrl_to_base(h_ctrl) * conditioning_scale # add ctrl -> base
1663
+
1664
+ return h_base, h_ctrl
1665
+
1666
+
1667
+ class ControlNetXSCrossAttnUpBlock2D(nn.Module):
1668
+ def __init__(
1669
+ self,
1670
+ in_channels: int,
1671
+ out_channels: int,
1672
+ prev_output_channel: int,
1673
+ ctrl_skip_channels: List[int],
1674
+ temb_channels: int,
1675
+ norm_num_groups: int = 32,
1676
+ resolution_idx: Optional[int] = None,
1677
+ has_crossattn=True,
1678
+ transformer_layers_per_block: int = 1,
1679
+ num_attention_heads: int = 1,
1680
+ cross_attention_dim: int = 1024,
1681
+ add_upsample: bool = True,
1682
+ upcast_attention: bool = False,
1683
+ use_linear_projection: Optional[bool] = True,
1684
+ ):
1685
+ super().__init__()
1686
+ resnets = []
1687
+ attentions = []
1688
+ ctrl_to_base = []
1689
+
1690
+ num_layers = 3 # only support sd + sdxl
1691
+
1692
+ self.has_cross_attention = has_crossattn
1693
+ self.num_attention_heads = num_attention_heads
1694
+
1695
+ if isinstance(transformer_layers_per_block, int):
1696
+ transformer_layers_per_block = [transformer_layers_per_block] * num_layers
1697
+
1698
+ for i in range(num_layers):
1699
+ res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
1700
+ resnet_in_channels = prev_output_channel if i == 0 else out_channels
1701
+
1702
+ ctrl_to_base.append(make_zero_conv(ctrl_skip_channels[i], resnet_in_channels))
1703
+
1704
+ resnets.append(
1705
+ ResnetBlock2D(
1706
+ in_channels=resnet_in_channels + res_skip_channels,
1707
+ out_channels=out_channels,
1708
+ temb_channels=temb_channels,
1709
+ groups=norm_num_groups,
1710
+ )
1711
+ )
1712
+
1713
+ if has_crossattn:
1714
+ attentions.append(
1715
+ Transformer2DModel(
1716
+ num_attention_heads,
1717
+ out_channels // num_attention_heads,
1718
+ in_channels=out_channels,
1719
+ num_layers=transformer_layers_per_block[i],
1720
+ cross_attention_dim=cross_attention_dim,
1721
+ use_linear_projection=use_linear_projection,
1722
+ upcast_attention=upcast_attention,
1723
+ norm_num_groups=norm_num_groups,
1724
+ )
1725
+ )
1726
+
1727
+ self.resnets = nn.ModuleList(resnets)
1728
+ self.attentions = nn.ModuleList(attentions) if has_crossattn else [None] * num_layers
1729
+ self.ctrl_to_base = nn.ModuleList(ctrl_to_base)
1730
+
1731
+ if add_upsample:
1732
+ self.upsamplers = Upsample2D(out_channels, use_conv=True, out_channels=out_channels)
1733
+ else:
1734
+ self.upsamplers = None
1735
+
1736
+ self.gradient_checkpointing = False
1737
+ self.resolution_idx = resolution_idx
1738
+
1739
+ @classmethod
1740
+ def from_modules(cls, base_upblock: CrossAttnUpBlock2D, ctrl_upblock: UpBlockControlNetXSAdapter):
1741
+ ctrl_to_base_skip_connections = ctrl_upblock.ctrl_to_base
1742
+
1743
+ # get params
1744
+ def get_first_cross_attention(block):
1745
+ return block.attentions[0].transformer_blocks[0].attn2
1746
+
1747
+ out_channels = base_upblock.resnets[0].out_channels
1748
+ in_channels = base_upblock.resnets[-1].in_channels - out_channels
1749
+ prev_output_channels = base_upblock.resnets[0].in_channels - out_channels
1750
+ ctrl_skip_channelss = [c.in_channels for c in ctrl_to_base_skip_connections]
1751
+ temb_channels = base_upblock.resnets[0].time_emb_proj.in_features
1752
+ num_groups = base_upblock.resnets[0].norm1.num_groups
1753
+ resolution_idx = base_upblock.resolution_idx
1754
+ if hasattr(base_upblock, "attentions"):
1755
+ has_crossattn = True
1756
+ transformer_layers_per_block = len(base_upblock.attentions[0].transformer_blocks)
1757
+ num_attention_heads = get_first_cross_attention(base_upblock).heads
1758
+ cross_attention_dim = get_first_cross_attention(base_upblock).cross_attention_dim
1759
+ upcast_attention = get_first_cross_attention(base_upblock).upcast_attention
1760
+ use_linear_projection = base_upblock.attentions[0].use_linear_projection
1761
+ else:
1762
+ has_crossattn = False
1763
+ transformer_layers_per_block = None
1764
+ num_attention_heads = None
1765
+ cross_attention_dim = None
1766
+ upcast_attention = None
1767
+ use_linear_projection = None
1768
+ add_upsample = base_upblock.upsamplers is not None
1769
+
1770
+ # create model
1771
+ model = cls(
1772
+ in_channels=in_channels,
1773
+ out_channels=out_channels,
1774
+ prev_output_channel=prev_output_channels,
1775
+ ctrl_skip_channels=ctrl_skip_channelss,
1776
+ temb_channels=temb_channels,
1777
+ norm_num_groups=num_groups,
1778
+ resolution_idx=resolution_idx,
1779
+ has_crossattn=has_crossattn,
1780
+ transformer_layers_per_block=transformer_layers_per_block,
1781
+ num_attention_heads=num_attention_heads,
1782
+ cross_attention_dim=cross_attention_dim,
1783
+ add_upsample=add_upsample,
1784
+ upcast_attention=upcast_attention,
1785
+ use_linear_projection=use_linear_projection,
1786
+ )
1787
+
1788
+ # load weights
1789
+ model.resnets.load_state_dict(base_upblock.resnets.state_dict())
1790
+ if has_crossattn:
1791
+ model.attentions.load_state_dict(base_upblock.attentions.state_dict())
1792
+ if add_upsample:
1793
+ model.upsamplers.load_state_dict(base_upblock.upsamplers[0].state_dict())
1794
+ model.ctrl_to_base.load_state_dict(ctrl_to_base_skip_connections.state_dict())
1795
+
1796
+ return model
1797
+
1798
+ def freeze_base_params(self) -> None:
1799
+ """Freeze the weights of the parts belonging to the base UNet2DConditionModel, and leave everything else unfrozen for fine
1800
+ tuning."""
1801
+ # Unfreeze everything
1802
+ for param in self.parameters():
1803
+ param.requires_grad = True
1804
+
1805
+ # Freeze base part
1806
+ base_parts = [self.resnets]
1807
+ if isinstance(self.attentions, nn.ModuleList): # attentions can be a list of Nones
1808
+ base_parts.append(self.attentions)
1809
+ if self.upsamplers is not None:
1810
+ base_parts.append(self.upsamplers)
1811
+ for part in base_parts:
1812
+ for param in part.parameters():
1813
+ param.requires_grad = False
1814
+
1815
+ def forward(
1816
+ self,
1817
+ hidden_states: Tensor,
1818
+ res_hidden_states_tuple_base: Tuple[Tensor, ...],
1819
+ res_hidden_states_tuple_ctrl: Tuple[Tensor, ...],
1820
+ temb: Tensor,
1821
+ encoder_hidden_states: Optional[Tensor] = None,
1822
+ conditioning_scale: Optional[float] = 1.0,
1823
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
1824
+ attention_mask: Optional[Tensor] = None,
1825
+ upsample_size: Optional[int] = None,
1826
+ encoder_attention_mask: Optional[Tensor] = None,
1827
+ apply_control: bool = True,
1828
+ ) -> Tensor:
1829
+ if cross_attention_kwargs is not None:
1830
+ if cross_attention_kwargs.get("scale", None) is not None:
1831
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
1832
+
1833
+ is_freeu_enabled = (
1834
+ getattr(self, "s1", None)
1835
+ and getattr(self, "s2", None)
1836
+ and getattr(self, "b1", None)
1837
+ and getattr(self, "b2", None)
1838
+ )
1839
+
1840
+ def maybe_apply_freeu_to_subblock(hidden_states, res_h_base):
1841
+ # FreeU: Only operate on the first two stages
1842
+ if is_freeu_enabled:
1843
+ return apply_freeu(
1844
+ self.resolution_idx,
1845
+ hidden_states,
1846
+ res_h_base,
1847
+ s1=self.s1,
1848
+ s2=self.s2,
1849
+ b1=self.b1,
1850
+ b2=self.b2,
1851
+ )
1852
+ else:
1853
+ return hidden_states, res_h_base
1854
+
1855
+ for resnet, attn, c2b, res_h_base, res_h_ctrl in zip(
1856
+ self.resnets,
1857
+ self.attentions,
1858
+ self.ctrl_to_base,
1859
+ reversed(res_hidden_states_tuple_base),
1860
+ reversed(res_hidden_states_tuple_ctrl),
1861
+ ):
1862
+ if apply_control:
1863
+ hidden_states += c2b(res_h_ctrl) * conditioning_scale
1864
+
1865
+ hidden_states, res_h_base = maybe_apply_freeu_to_subblock(hidden_states, res_h_base)
1866
+ hidden_states = torch.cat([hidden_states, res_h_base], dim=1)
1867
+
1868
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
1869
+ hidden_states = self._gradient_checkpointing_func(resnet, hidden_states, temb)
1870
+ else:
1871
+ hidden_states = resnet(hidden_states, temb)
1872
+
1873
+ if attn is not None:
1874
+ hidden_states = attn(
1875
+ hidden_states,
1876
+ encoder_hidden_states=encoder_hidden_states,
1877
+ cross_attention_kwargs=cross_attention_kwargs,
1878
+ attention_mask=attention_mask,
1879
+ encoder_attention_mask=encoder_attention_mask,
1880
+ return_dict=False,
1881
+ )[0]
1882
+
1883
+ if self.upsamplers is not None:
1884
+ hidden_states = self.upsamplers(hidden_states, upsample_size)
1885
+
1886
+ return hidden_states
1887
+
1888
+
1889
+ def make_zero_conv(in_channels, out_channels=None):
1890
+ return zero_module(nn.Conv2d(in_channels, out_channels, 1, padding=0))
1891
+
1892
+
1893
+ def zero_module(module):
1894
+ for p in module.parameters():
1895
+ nn.init.zeros_(p)
1896
+ return module
1897
+
1898
+
1899
+ def find_largest_factor(number, max_factor):
1900
+ factor = max_factor
1901
+ if factor >= number:
1902
+ return number
1903
+ while factor != 0:
1904
+ residual = number % factor
1905
+ if residual == 0:
1906
+ return factor
1907
+ factor -= 1
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/multicontrolnet.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ from ...models.controlnets.controlnet import ControlNetModel, ControlNetOutput
8
+ from ...models.modeling_utils import ModelMixin
9
+ from ...utils import logging
10
+
11
+
12
+ logger = logging.get_logger(__name__)
13
+
14
+
15
+ class MultiControlNetModel(ModelMixin):
16
+ r"""
17
+ Multiple `ControlNetModel` wrapper class for Multi-ControlNet
18
+
19
+ This module is a wrapper for multiple instances of the `ControlNetModel`. The `forward()` API is designed to be
20
+ compatible with `ControlNetModel`.
21
+
22
+ Args:
23
+ controlnets (`List[ControlNetModel]`):
24
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
25
+ `ControlNetModel` as a list.
26
+ """
27
+
28
+ def __init__(self, controlnets: Union[List[ControlNetModel], Tuple[ControlNetModel]]):
29
+ super().__init__()
30
+ self.nets = nn.ModuleList(controlnets)
31
+
32
+ def forward(
33
+ self,
34
+ sample: torch.Tensor,
35
+ timestep: Union[torch.Tensor, float, int],
36
+ encoder_hidden_states: torch.Tensor,
37
+ controlnet_cond: List[torch.tensor],
38
+ conditioning_scale: List[float],
39
+ class_labels: Optional[torch.Tensor] = None,
40
+ timestep_cond: Optional[torch.Tensor] = None,
41
+ attention_mask: Optional[torch.Tensor] = None,
42
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
43
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
44
+ guess_mode: bool = False,
45
+ return_dict: bool = True,
46
+ ) -> Union[ControlNetOutput, Tuple]:
47
+ for i, (image, scale, controlnet) in enumerate(zip(controlnet_cond, conditioning_scale, self.nets)):
48
+ down_samples, mid_sample = controlnet(
49
+ sample=sample,
50
+ timestep=timestep,
51
+ encoder_hidden_states=encoder_hidden_states,
52
+ controlnet_cond=image,
53
+ conditioning_scale=scale,
54
+ class_labels=class_labels,
55
+ timestep_cond=timestep_cond,
56
+ attention_mask=attention_mask,
57
+ added_cond_kwargs=added_cond_kwargs,
58
+ cross_attention_kwargs=cross_attention_kwargs,
59
+ guess_mode=guess_mode,
60
+ return_dict=return_dict,
61
+ )
62
+
63
+ # merge samples
64
+ if i == 0:
65
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
66
+ else:
67
+ down_block_res_samples = [
68
+ samples_prev + samples_curr
69
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
70
+ ]
71
+ mid_block_res_sample += mid_sample
72
+
73
+ return down_block_res_samples, mid_block_res_sample
74
+
75
+ def save_pretrained(
76
+ self,
77
+ save_directory: Union[str, os.PathLike],
78
+ is_main_process: bool = True,
79
+ save_function: Callable = None,
80
+ safe_serialization: bool = True,
81
+ variant: Optional[str] = None,
82
+ ):
83
+ """
84
+ Save a model and its configuration file to a directory, so that it can be re-loaded using the
85
+ `[`~models.controlnets.multicontrolnet.MultiControlNetModel.from_pretrained`]` class method.
86
+
87
+ Arguments:
88
+ save_directory (`str` or `os.PathLike`):
89
+ Directory to which to save. Will be created if it doesn't exist.
90
+ is_main_process (`bool`, *optional*, defaults to `True`):
91
+ Whether the process calling this is the main process or not. Useful when in distributed training like
92
+ TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on
93
+ the main process to avoid race conditions.
94
+ save_function (`Callable`):
95
+ The function to use to save the state dictionary. Useful on distributed training like TPUs when one
96
+ need to replace `torch.save` by another method. Can be configured with the environment variable
97
+ `DIFFUSERS_SAVE_MODE`.
98
+ safe_serialization (`bool`, *optional*, defaults to `True`):
99
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
100
+ variant (`str`, *optional*):
101
+ If specified, weights are saved in the format pytorch_model.<variant>.bin.
102
+ """
103
+ for idx, controlnet in enumerate(self.nets):
104
+ suffix = "" if idx == 0 else f"_{idx}"
105
+ controlnet.save_pretrained(
106
+ save_directory + suffix,
107
+ is_main_process=is_main_process,
108
+ save_function=save_function,
109
+ safe_serialization=safe_serialization,
110
+ variant=variant,
111
+ )
112
+
113
+ @classmethod
114
+ def from_pretrained(cls, pretrained_model_path: Optional[Union[str, os.PathLike]], **kwargs):
115
+ r"""
116
+ Instantiate a pretrained MultiControlNet model from multiple pre-trained controlnet models.
117
+
118
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
119
+ the model, you should first set it back in training mode with `model.train()`.
120
+
121
+ The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
122
+ pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
123
+ task.
124
+
125
+ The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
126
+ weights are discarded.
127
+
128
+ Parameters:
129
+ pretrained_model_path (`os.PathLike`):
130
+ A path to a *directory* containing model weights saved using
131
+ [`~models.controlnets.multicontrolnet.MultiControlNetModel.save_pretrained`], e.g.,
132
+ `./my_model_directory/controlnet`.
133
+ torch_dtype (`str` or `torch.dtype`, *optional*):
134
+ Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype
135
+ will be automatically derived from the model's weights.
136
+ output_loading_info(`bool`, *optional*, defaults to `False`):
137
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
138
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
139
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
140
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
141
+ same device.
142
+
143
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
144
+ more information about each option see [designing a device
145
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
146
+ max_memory (`Dict`, *optional*):
147
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
148
+ GPU and the available CPU RAM if unset.
149
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
150
+ Speed up model loading by not initializing the weights and only loading the pre-trained weights. This
151
+ also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the
152
+ model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch,
153
+ setting this argument to `True` will raise an error.
154
+ variant (`str`, *optional*):
155
+ If specified load weights from `variant` filename, *e.g.* pytorch_model.<variant>.bin. `variant` is
156
+ ignored when using `from_flax`.
157
+ use_safetensors (`bool`, *optional*, defaults to `None`):
158
+ If set to `None`, the `safetensors` weights will be downloaded if they're available **and** if the
159
+ `safetensors` library is installed. If set to `True`, the model will be forcibly loaded from
160
+ `safetensors` weights. If set to `False`, loading will *not* use `safetensors`.
161
+ """
162
+ idx = 0
163
+ controlnets = []
164
+
165
+ # load controlnet and append to list until no controlnet directory exists anymore
166
+ # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained`
167
+ # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ...
168
+ model_path_to_load = pretrained_model_path
169
+ while os.path.isdir(model_path_to_load):
170
+ controlnet = ControlNetModel.from_pretrained(model_path_to_load, **kwargs)
171
+ controlnets.append(controlnet)
172
+
173
+ idx += 1
174
+ model_path_to_load = pretrained_model_path + f"_{idx}"
175
+
176
+ logger.info(f"{len(controlnets)} controlnets loaded from {pretrained_model_path}.")
177
+
178
+ if len(controlnets) == 0:
179
+ raise ValueError(
180
+ f"No ControlNets found under {os.path.dirname(pretrained_model_path)}. Expected at least {pretrained_model_path + '_0'}."
181
+ )
182
+
183
+ return cls(controlnets)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/controlnets/multicontrolnet_union.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
3
+
4
+ import torch
5
+ from torch import nn
6
+
7
+ from ...models.controlnets.controlnet import ControlNetOutput
8
+ from ...models.controlnets.controlnet_union import ControlNetUnionModel
9
+ from ...models.modeling_utils import ModelMixin
10
+ from ...utils import logging
11
+
12
+
13
+ logger = logging.get_logger(__name__)
14
+
15
+
16
+ class MultiControlNetUnionModel(ModelMixin):
17
+ r"""
18
+ Multiple `ControlNetUnionModel` wrapper class for Multi-ControlNet-Union.
19
+
20
+ This module is a wrapper for multiple instances of the `ControlNetUnionModel`. The `forward()` API is designed to
21
+ be compatible with `ControlNetUnionModel`.
22
+
23
+ Args:
24
+ controlnets (`List[ControlNetUnionModel]`):
25
+ Provides additional conditioning to the unet during the denoising process. You must set multiple
26
+ `ControlNetUnionModel` as a list.
27
+ """
28
+
29
+ def __init__(self, controlnets: Union[List[ControlNetUnionModel], Tuple[ControlNetUnionModel]]):
30
+ super().__init__()
31
+ self.nets = nn.ModuleList(controlnets)
32
+
33
+ def forward(
34
+ self,
35
+ sample: torch.Tensor,
36
+ timestep: Union[torch.Tensor, float, int],
37
+ encoder_hidden_states: torch.Tensor,
38
+ controlnet_cond: List[torch.tensor],
39
+ control_type: List[torch.Tensor],
40
+ control_type_idx: List[List[int]],
41
+ conditioning_scale: List[float],
42
+ class_labels: Optional[torch.Tensor] = None,
43
+ timestep_cond: Optional[torch.Tensor] = None,
44
+ attention_mask: Optional[torch.Tensor] = None,
45
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
46
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
47
+ guess_mode: bool = False,
48
+ return_dict: bool = True,
49
+ ) -> Union[ControlNetOutput, Tuple]:
50
+ down_block_res_samples, mid_block_res_sample = None, None
51
+ for i, (image, ctype, ctype_idx, scale, controlnet) in enumerate(
52
+ zip(controlnet_cond, control_type, control_type_idx, conditioning_scale, self.nets)
53
+ ):
54
+ if scale == 0.0:
55
+ continue
56
+ down_samples, mid_sample = controlnet(
57
+ sample=sample,
58
+ timestep=timestep,
59
+ encoder_hidden_states=encoder_hidden_states,
60
+ controlnet_cond=image,
61
+ control_type=ctype,
62
+ control_type_idx=ctype_idx,
63
+ conditioning_scale=scale,
64
+ class_labels=class_labels,
65
+ timestep_cond=timestep_cond,
66
+ attention_mask=attention_mask,
67
+ added_cond_kwargs=added_cond_kwargs,
68
+ cross_attention_kwargs=cross_attention_kwargs,
69
+ from_multi=True,
70
+ guess_mode=guess_mode,
71
+ return_dict=return_dict,
72
+ )
73
+
74
+ # merge samples
75
+ if down_block_res_samples is None and mid_block_res_sample is None:
76
+ down_block_res_samples, mid_block_res_sample = down_samples, mid_sample
77
+ else:
78
+ down_block_res_samples = [
79
+ samples_prev + samples_curr
80
+ for samples_prev, samples_curr in zip(down_block_res_samples, down_samples)
81
+ ]
82
+ mid_block_res_sample += mid_sample
83
+
84
+ return down_block_res_samples, mid_block_res_sample
85
+
86
+ # Copied from diffusers.models.controlnets.multicontrolnet.MultiControlNetModel.save_pretrained with ControlNet->ControlNetUnion
87
+ def save_pretrained(
88
+ self,
89
+ save_directory: Union[str, os.PathLike],
90
+ is_main_process: bool = True,
91
+ save_function: Callable = None,
92
+ safe_serialization: bool = True,
93
+ variant: Optional[str] = None,
94
+ ):
95
+ """
96
+ Save a model and its configuration file to a directory, so that it can be re-loaded using the
97
+ `[`~models.controlnets.multicontrolnet.MultiControlNetUnionModel.from_pretrained`]` class method.
98
+
99
+ Arguments:
100
+ save_directory (`str` or `os.PathLike`):
101
+ Directory to which to save. Will be created if it doesn't exist.
102
+ is_main_process (`bool`, *optional*, defaults to `True`):
103
+ Whether the process calling this is the main process or not. Useful when in distributed training like
104
+ TPUs and need to call this function on all processes. In this case, set `is_main_process=True` only on
105
+ the main process to avoid race conditions.
106
+ save_function (`Callable`):
107
+ The function to use to save the state dictionary. Useful on distributed training like TPUs when one
108
+ need to replace `torch.save` by another method. Can be configured with the environment variable
109
+ `DIFFUSERS_SAVE_MODE`.
110
+ safe_serialization (`bool`, *optional*, defaults to `True`):
111
+ Whether to save the model using `safetensors` or the traditional PyTorch way (that uses `pickle`).
112
+ variant (`str`, *optional*):
113
+ If specified, weights are saved in the format pytorch_model.<variant>.bin.
114
+ """
115
+ for idx, controlnet in enumerate(self.nets):
116
+ suffix = "" if idx == 0 else f"_{idx}"
117
+ controlnet.save_pretrained(
118
+ save_directory + suffix,
119
+ is_main_process=is_main_process,
120
+ save_function=save_function,
121
+ safe_serialization=safe_serialization,
122
+ variant=variant,
123
+ )
124
+
125
+ @classmethod
126
+ # Copied from diffusers.models.controlnets.multicontrolnet.MultiControlNetModel.from_pretrained with ControlNet->ControlNetUnion
127
+ def from_pretrained(cls, pretrained_model_path: Optional[Union[str, os.PathLike]], **kwargs):
128
+ r"""
129
+ Instantiate a pretrained MultiControlNetUnion model from multiple pre-trained controlnet models.
130
+
131
+ The model is set in evaluation mode by default using `model.eval()` (Dropout modules are deactivated). To train
132
+ the model, you should first set it back in training mode with `model.train()`.
133
+
134
+ The warning *Weights from XXX not initialized from pretrained model* means that the weights of XXX do not come
135
+ pretrained with the rest of the model. It is up to you to train those weights with a downstream fine-tuning
136
+ task.
137
+
138
+ The warning *Weights from XXX not used in YYY* means that the layer XXX is not used by YYY, therefore those
139
+ weights are discarded.
140
+
141
+ Parameters:
142
+ pretrained_model_path (`os.PathLike`):
143
+ A path to a *directory* containing model weights saved using
144
+ [`~models.controlnets.multicontrolnet.MultiControlNetUnionModel.save_pretrained`], e.g.,
145
+ `./my_model_directory/controlnet`.
146
+ torch_dtype (`str` or `torch.dtype`, *optional*):
147
+ Override the default `torch.dtype` and load the model under this dtype. If `"auto"` is passed the dtype
148
+ will be automatically derived from the model's weights.
149
+ output_loading_info(`bool`, *optional*, defaults to `False`):
150
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
151
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
152
+ A map that specifies where each submodule should go. It doesn't need to be refined to each
153
+ parameter/buffer name, once a given module name is inside, every submodule of it will be sent to the
154
+ same device.
155
+
156
+ To have Accelerate compute the most optimized `device_map` automatically, set `device_map="auto"`. For
157
+ more information about each option see [designing a device
158
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
159
+ max_memory (`Dict`, *optional*):
160
+ A dictionary device identifier to maximum memory. Will default to the maximum memory available for each
161
+ GPU and the available CPU RAM if unset.
162
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
163
+ Speed up model loading by not initializing the weights and only loading the pre-trained weights. This
164
+ also tries to not use more than 1x model size in CPU memory (including peak memory) while loading the
165
+ model. This is only supported when torch version >= 1.9.0. If you are using an older version of torch,
166
+ setting this argument to `True` will raise an error.
167
+ variant (`str`, *optional*):
168
+ If specified load weights from `variant` filename, *e.g.* pytorch_model.<variant>.bin. `variant` is
169
+ ignored when using `from_flax`.
170
+ use_safetensors (`bool`, *optional*, defaults to `None`):
171
+ If set to `None`, the `safetensors` weights will be downloaded if they're available **and** if the
172
+ `safetensors` library is installed. If set to `True`, the model will be forcibly loaded from
173
+ `safetensors` weights. If set to `False`, loading will *not* use `safetensors`.
174
+ """
175
+ idx = 0
176
+ controlnets = []
177
+
178
+ # load controlnet and append to list until no controlnet directory exists anymore
179
+ # first controlnet has to be saved under `./mydirectory/controlnet` to be compliant with `DiffusionPipeline.from_prertained`
180
+ # second, third, ... controlnets have to be saved under `./mydirectory/controlnet_1`, `./mydirectory/controlnet_2`, ...
181
+ model_path_to_load = pretrained_model_path
182
+ while os.path.isdir(model_path_to_load):
183
+ controlnet = ControlNetUnionModel.from_pretrained(model_path_to_load, **kwargs)
184
+ controlnets.append(controlnet)
185
+
186
+ idx += 1
187
+ model_path_to_load = pretrained_model_path + f"_{idx}"
188
+
189
+ logger.info(f"{len(controlnets)} controlnets loaded from {pretrained_model_path}.")
190
+
191
+ if len(controlnets) == 0:
192
+ raise ValueError(
193
+ f"No ControlNetUnions found under {os.path.dirname(pretrained_model_path)}. Expected at least {pretrained_model_path + '_0'}."
194
+ )
195
+
196
+ return cls(controlnets)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/downsampling.py ADDED
@@ -0,0 +1,401 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional, Tuple
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from ..utils import deprecate
22
+ from .normalization import RMSNorm
23
+ from .upsampling import upfirdn2d_native
24
+
25
+
26
+ class Downsample1D(nn.Module):
27
+ """A 1D downsampling layer with an optional convolution.
28
+
29
+ Parameters:
30
+ channels (`int`):
31
+ number of channels in the inputs and outputs.
32
+ use_conv (`bool`, default `False`):
33
+ option to use a convolution.
34
+ out_channels (`int`, optional):
35
+ number of output channels. Defaults to `channels`.
36
+ padding (`int`, default `1`):
37
+ padding for the convolution.
38
+ name (`str`, default `conv`):
39
+ name of the downsampling 1D layer.
40
+ """
41
+
42
+ def __init__(
43
+ self,
44
+ channels: int,
45
+ use_conv: bool = False,
46
+ out_channels: Optional[int] = None,
47
+ padding: int = 1,
48
+ name: str = "conv",
49
+ ):
50
+ super().__init__()
51
+ self.channels = channels
52
+ self.out_channels = out_channels or channels
53
+ self.use_conv = use_conv
54
+ self.padding = padding
55
+ stride = 2
56
+ self.name = name
57
+
58
+ if use_conv:
59
+ self.conv = nn.Conv1d(self.channels, self.out_channels, 3, stride=stride, padding=padding)
60
+ else:
61
+ assert self.channels == self.out_channels
62
+ self.conv = nn.AvgPool1d(kernel_size=stride, stride=stride)
63
+
64
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
65
+ assert inputs.shape[1] == self.channels
66
+ return self.conv(inputs)
67
+
68
+
69
+ class Downsample2D(nn.Module):
70
+ """A 2D downsampling layer with an optional convolution.
71
+
72
+ Parameters:
73
+ channels (`int`):
74
+ number of channels in the inputs and outputs.
75
+ use_conv (`bool`, default `False`):
76
+ option to use a convolution.
77
+ out_channels (`int`, optional):
78
+ number of output channels. Defaults to `channels`.
79
+ padding (`int`, default `1`):
80
+ padding for the convolution.
81
+ name (`str`, default `conv`):
82
+ name of the downsampling 2D layer.
83
+ """
84
+
85
+ def __init__(
86
+ self,
87
+ channels: int,
88
+ use_conv: bool = False,
89
+ out_channels: Optional[int] = None,
90
+ padding: int = 1,
91
+ name: str = "conv",
92
+ kernel_size=3,
93
+ norm_type=None,
94
+ eps=None,
95
+ elementwise_affine=None,
96
+ bias=True,
97
+ ):
98
+ super().__init__()
99
+ self.channels = channels
100
+ self.out_channels = out_channels or channels
101
+ self.use_conv = use_conv
102
+ self.padding = padding
103
+ stride = 2
104
+ self.name = name
105
+
106
+ if norm_type == "ln_norm":
107
+ self.norm = nn.LayerNorm(channels, eps, elementwise_affine)
108
+ elif norm_type == "rms_norm":
109
+ self.norm = RMSNorm(channels, eps, elementwise_affine)
110
+ elif norm_type is None:
111
+ self.norm = None
112
+ else:
113
+ raise ValueError(f"unknown norm_type: {norm_type}")
114
+
115
+ if use_conv:
116
+ conv = nn.Conv2d(
117
+ self.channels, self.out_channels, kernel_size=kernel_size, stride=stride, padding=padding, bias=bias
118
+ )
119
+ else:
120
+ assert self.channels == self.out_channels
121
+ conv = nn.AvgPool2d(kernel_size=stride, stride=stride)
122
+
123
+ # TODO(Suraj, Patrick) - clean up after weight dicts are correctly renamed
124
+ if name == "conv":
125
+ self.Conv2d_0 = conv
126
+ self.conv = conv
127
+ elif name == "Conv2d_0":
128
+ self.conv = conv
129
+ else:
130
+ self.conv = conv
131
+
132
+ def forward(self, hidden_states: torch.Tensor, *args, **kwargs) -> torch.Tensor:
133
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
134
+ 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`."
135
+ deprecate("scale", "1.0.0", deprecation_message)
136
+ assert hidden_states.shape[1] == self.channels
137
+
138
+ if self.norm is not None:
139
+ hidden_states = self.norm(hidden_states.permute(0, 2, 3, 1)).permute(0, 3, 1, 2)
140
+
141
+ if self.use_conv and self.padding == 0:
142
+ pad = (0, 1, 0, 1)
143
+ hidden_states = F.pad(hidden_states, pad, mode="constant", value=0)
144
+
145
+ assert hidden_states.shape[1] == self.channels
146
+
147
+ hidden_states = self.conv(hidden_states)
148
+
149
+ return hidden_states
150
+
151
+
152
+ class FirDownsample2D(nn.Module):
153
+ """A 2D FIR downsampling layer with an optional convolution.
154
+
155
+ Parameters:
156
+ channels (`int`):
157
+ number of channels in the inputs and outputs.
158
+ use_conv (`bool`, default `False`):
159
+ option to use a convolution.
160
+ out_channels (`int`, optional):
161
+ number of output channels. Defaults to `channels`.
162
+ fir_kernel (`tuple`, default `(1, 3, 3, 1)`):
163
+ kernel for the FIR filter.
164
+ """
165
+
166
+ def __init__(
167
+ self,
168
+ channels: Optional[int] = None,
169
+ out_channels: Optional[int] = None,
170
+ use_conv: bool = False,
171
+ fir_kernel: Tuple[int, int, int, int] = (1, 3, 3, 1),
172
+ ):
173
+ super().__init__()
174
+ out_channels = out_channels if out_channels else channels
175
+ if use_conv:
176
+ self.Conv2d_0 = nn.Conv2d(channels, out_channels, kernel_size=3, stride=1, padding=1)
177
+ self.fir_kernel = fir_kernel
178
+ self.use_conv = use_conv
179
+ self.out_channels = out_channels
180
+
181
+ def _downsample_2d(
182
+ self,
183
+ hidden_states: torch.Tensor,
184
+ weight: Optional[torch.Tensor] = None,
185
+ kernel: Optional[torch.Tensor] = None,
186
+ factor: int = 2,
187
+ gain: float = 1,
188
+ ) -> torch.Tensor:
189
+ """Fused `Conv2d()` followed by `downsample_2d()`.
190
+ Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
191
+ efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
192
+ arbitrary order.
193
+
194
+ Args:
195
+ hidden_states (`torch.Tensor`):
196
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
197
+ weight (`torch.Tensor`, *optional*):
198
+ Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
199
+ performed by `inChannels = x.shape[0] // numGroups`.
200
+ kernel (`torch.Tensor`, *optional*):
201
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
202
+ corresponds to average pooling.
203
+ factor (`int`, *optional*, default to `2`):
204
+ Integer downsampling factor.
205
+ gain (`float`, *optional*, default to `1.0`):
206
+ Scaling factor for signal magnitude.
207
+
208
+ Returns:
209
+ output (`torch.Tensor`):
210
+ Tensor of the shape `[N, C, H // factor, W // factor]` or `[N, H // factor, W // factor, C]`, and same
211
+ datatype as `x`.
212
+ """
213
+
214
+ assert isinstance(factor, int) and factor >= 1
215
+ if kernel is None:
216
+ kernel = [1] * factor
217
+
218
+ # setup kernel
219
+ kernel = torch.tensor(kernel, dtype=torch.float32)
220
+ if kernel.ndim == 1:
221
+ kernel = torch.outer(kernel, kernel)
222
+ kernel /= torch.sum(kernel)
223
+
224
+ kernel = kernel * gain
225
+
226
+ if self.use_conv:
227
+ _, _, convH, convW = weight.shape
228
+ pad_value = (kernel.shape[0] - factor) + (convW - 1)
229
+ stride_value = [factor, factor]
230
+ upfirdn_input = upfirdn2d_native(
231
+ hidden_states,
232
+ torch.tensor(kernel, device=hidden_states.device),
233
+ pad=((pad_value + 1) // 2, pad_value // 2),
234
+ )
235
+ output = F.conv2d(upfirdn_input, weight, stride=stride_value, padding=0)
236
+ else:
237
+ pad_value = kernel.shape[0] - factor
238
+ output = upfirdn2d_native(
239
+ hidden_states,
240
+ torch.tensor(kernel, device=hidden_states.device),
241
+ down=factor,
242
+ pad=((pad_value + 1) // 2, pad_value // 2),
243
+ )
244
+
245
+ return output
246
+
247
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
248
+ if self.use_conv:
249
+ downsample_input = self._downsample_2d(hidden_states, weight=self.Conv2d_0.weight, kernel=self.fir_kernel)
250
+ hidden_states = downsample_input + self.Conv2d_0.bias.reshape(1, -1, 1, 1)
251
+ else:
252
+ hidden_states = self._downsample_2d(hidden_states, kernel=self.fir_kernel, factor=2)
253
+
254
+ return hidden_states
255
+
256
+
257
+ # downsample/upsample layer used in k-upscaler, might be able to use FirDownsample2D/DirUpsample2D instead
258
+ class KDownsample2D(nn.Module):
259
+ r"""A 2D K-downsampling layer.
260
+
261
+ Parameters:
262
+ pad_mode (`str`, *optional*, default to `"reflect"`): the padding mode to use.
263
+ """
264
+
265
+ def __init__(self, pad_mode: str = "reflect"):
266
+ super().__init__()
267
+ self.pad_mode = pad_mode
268
+ kernel_1d = torch.tensor([[1 / 8, 3 / 8, 3 / 8, 1 / 8]])
269
+ self.pad = kernel_1d.shape[1] // 2 - 1
270
+ self.register_buffer("kernel", kernel_1d.T @ kernel_1d, persistent=False)
271
+
272
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
273
+ inputs = F.pad(inputs, (self.pad,) * 4, self.pad_mode)
274
+ weight = inputs.new_zeros(
275
+ [
276
+ inputs.shape[1],
277
+ inputs.shape[1],
278
+ self.kernel.shape[0],
279
+ self.kernel.shape[1],
280
+ ]
281
+ )
282
+ indices = torch.arange(inputs.shape[1], device=inputs.device)
283
+ kernel = self.kernel.to(weight)[None, :].expand(inputs.shape[1], -1, -1)
284
+ weight[indices, indices] = kernel
285
+ return F.conv2d(inputs, weight, stride=2)
286
+
287
+
288
+ class CogVideoXDownsample3D(nn.Module):
289
+ # Todo: Wait for paper relase.
290
+ r"""
291
+ A 3D Downsampling layer using in [CogVideoX]() by Tsinghua University & ZhipuAI
292
+
293
+ Args:
294
+ in_channels (`int`):
295
+ Number of channels in the input image.
296
+ out_channels (`int`):
297
+ Number of channels produced by the convolution.
298
+ kernel_size (`int`, defaults to `3`):
299
+ Size of the convolving kernel.
300
+ stride (`int`, defaults to `2`):
301
+ Stride of the convolution.
302
+ padding (`int`, defaults to `0`):
303
+ Padding added to all four sides of the input.
304
+ compress_time (`bool`, defaults to `False`):
305
+ Whether or not to compress the time dimension.
306
+ """
307
+
308
+ def __init__(
309
+ self,
310
+ in_channels: int,
311
+ out_channels: int,
312
+ kernel_size: int = 3,
313
+ stride: int = 2,
314
+ padding: int = 0,
315
+ compress_time: bool = False,
316
+ ):
317
+ super().__init__()
318
+
319
+ self.conv = nn.Conv2d(in_channels, out_channels, kernel_size=kernel_size, stride=stride, padding=padding)
320
+ self.compress_time = compress_time
321
+
322
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
323
+ if self.compress_time:
324
+ batch_size, channels, frames, height, width = x.shape
325
+
326
+ # (batch_size, channels, frames, height, width) -> (batch_size, height, width, channels, frames) -> (batch_size * height * width, channels, frames)
327
+ x = x.permute(0, 3, 4, 1, 2).reshape(batch_size * height * width, channels, frames)
328
+
329
+ if x.shape[-1] % 2 == 1:
330
+ x_first, x_rest = x[..., 0], x[..., 1:]
331
+ if x_rest.shape[-1] > 0:
332
+ # (batch_size * height * width, channels, frames - 1) -> (batch_size * height * width, channels, (frames - 1) // 2)
333
+ x_rest = F.avg_pool1d(x_rest, kernel_size=2, stride=2)
334
+
335
+ x = torch.cat([x_first[..., None], x_rest], dim=-1)
336
+ # (batch_size * height * width, channels, (frames // 2) + 1) -> (batch_size, height, width, channels, (frames // 2) + 1) -> (batch_size, channels, (frames // 2) + 1, height, width)
337
+ x = x.reshape(batch_size, height, width, channels, x.shape[-1]).permute(0, 3, 4, 1, 2)
338
+ else:
339
+ # (batch_size * height * width, channels, frames) -> (batch_size * height * width, channels, frames // 2)
340
+ x = F.avg_pool1d(x, kernel_size=2, stride=2)
341
+ # (batch_size * height * width, channels, frames // 2) -> (batch_size, height, width, channels, frames // 2) -> (batch_size, channels, frames // 2, height, width)
342
+ x = x.reshape(batch_size, height, width, channels, x.shape[-1]).permute(0, 3, 4, 1, 2)
343
+
344
+ # Pad the tensor
345
+ pad = (0, 1, 0, 1)
346
+ x = F.pad(x, pad, mode="constant", value=0)
347
+ batch_size, channels, frames, height, width = x.shape
348
+ # (batch_size, channels, frames, height, width) -> (batch_size, frames, channels, height, width) -> (batch_size * frames, channels, height, width)
349
+ x = x.permute(0, 2, 1, 3, 4).reshape(batch_size * frames, channels, height, width)
350
+ x = self.conv(x)
351
+ # (batch_size * frames, channels, height, width) -> (batch_size, frames, channels, height, width) -> (batch_size, channels, frames, height, width)
352
+ x = x.reshape(batch_size, frames, x.shape[1], x.shape[2], x.shape[3]).permute(0, 2, 1, 3, 4)
353
+ return x
354
+
355
+
356
+ def downsample_2d(
357
+ hidden_states: torch.Tensor,
358
+ kernel: Optional[torch.Tensor] = None,
359
+ factor: int = 2,
360
+ gain: float = 1,
361
+ ) -> torch.Tensor:
362
+ r"""Downsample2D a batch of 2D images with the given filter.
363
+ Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
364
+ given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
365
+ specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
366
+ shape is a multiple of the downsampling factor.
367
+
368
+ Args:
369
+ hidden_states (`torch.Tensor`)
370
+ Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
371
+ kernel (`torch.Tensor`, *optional*):
372
+ FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
373
+ corresponds to average pooling.
374
+ factor (`int`, *optional*, default to `2`):
375
+ Integer downsampling factor.
376
+ gain (`float`, *optional*, default to `1.0`):
377
+ Scaling factor for signal magnitude.
378
+
379
+ Returns:
380
+ output (`torch.Tensor`):
381
+ Tensor of the shape `[N, C, H // factor, W // factor]`
382
+ """
383
+
384
+ assert isinstance(factor, int) and factor >= 1
385
+ if kernel is None:
386
+ kernel = [1] * factor
387
+
388
+ kernel = torch.tensor(kernel, dtype=torch.float32)
389
+ if kernel.ndim == 1:
390
+ kernel = torch.outer(kernel, kernel)
391
+ kernel /= torch.sum(kernel)
392
+
393
+ kernel = kernel * gain
394
+ pad_value = kernel.shape[0] - factor
395
+ output = upfirdn2d_native(
396
+ hidden_states,
397
+ kernel.to(device=hidden_states.device),
398
+ down=factor,
399
+ pad=((pad_value + 1) // 2, pad_value // 2),
400
+ )
401
+ return output
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/embeddings.py ADDED
The diff for this file is too large to render. See raw diff
 
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/embeddings_flax.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+
16
+ import flax.linen as nn
17
+ import jax.numpy as jnp
18
+
19
+
20
+ def get_sinusoidal_embeddings(
21
+ timesteps: jnp.ndarray,
22
+ embedding_dim: int,
23
+ freq_shift: float = 1,
24
+ min_timescale: float = 1,
25
+ max_timescale: float = 1.0e4,
26
+ flip_sin_to_cos: bool = False,
27
+ scale: float = 1.0,
28
+ ) -> jnp.ndarray:
29
+ """Returns the positional encoding (same as Tensor2Tensor).
30
+
31
+ Args:
32
+ timesteps (`jnp.ndarray` of shape `(N,)`):
33
+ A 1-D array of N indices, one per batch element. These may be fractional.
34
+ embedding_dim (`int`):
35
+ The number of output channels.
36
+ freq_shift (`float`, *optional*, defaults to `1`):
37
+ Shift applied to the frequency scaling of the embeddings.
38
+ min_timescale (`float`, *optional*, defaults to `1`):
39
+ The smallest time unit used in the sinusoidal calculation (should probably be 0.0).
40
+ max_timescale (`float`, *optional*, defaults to `1.0e4`):
41
+ The largest time unit used in the sinusoidal calculation.
42
+ flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
43
+ Whether to flip the order of sinusoidal components to cosine first.
44
+ scale (`float`, *optional*, defaults to `1.0`):
45
+ A scaling factor applied to the positional embeddings.
46
+
47
+ Returns:
48
+ a Tensor of timing signals [N, num_channels]
49
+ """
50
+ assert timesteps.ndim == 1, "Timesteps should be a 1d-array"
51
+ assert embedding_dim % 2 == 0, f"Embedding dimension {embedding_dim} should be even"
52
+ num_timescales = float(embedding_dim // 2)
53
+ log_timescale_increment = math.log(max_timescale / min_timescale) / (num_timescales - freq_shift)
54
+ inv_timescales = min_timescale * jnp.exp(jnp.arange(num_timescales, dtype=jnp.float32) * -log_timescale_increment)
55
+ emb = jnp.expand_dims(timesteps, 1) * jnp.expand_dims(inv_timescales, 0)
56
+
57
+ # scale embeddings
58
+ scaled_time = scale * emb
59
+
60
+ if flip_sin_to_cos:
61
+ signal = jnp.concatenate([jnp.cos(scaled_time), jnp.sin(scaled_time)], axis=1)
62
+ else:
63
+ signal = jnp.concatenate([jnp.sin(scaled_time), jnp.cos(scaled_time)], axis=1)
64
+ signal = jnp.reshape(signal, [jnp.shape(timesteps)[0], embedding_dim])
65
+ return signal
66
+
67
+
68
+ class FlaxTimestepEmbedding(nn.Module):
69
+ r"""
70
+ Time step Embedding Module. Learns embeddings for input time steps.
71
+
72
+ Args:
73
+ time_embed_dim (`int`, *optional*, defaults to `32`):
74
+ Time step embedding dimension.
75
+ dtype (`jnp.dtype`, *optional*, defaults to `jnp.float32`):
76
+ The data type for the embedding parameters.
77
+ """
78
+
79
+ time_embed_dim: int = 32
80
+ dtype: jnp.dtype = jnp.float32
81
+
82
+ @nn.compact
83
+ def __call__(self, temb):
84
+ temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name="linear_1")(temb)
85
+ temb = nn.silu(temb)
86
+ temb = nn.Dense(self.time_embed_dim, dtype=self.dtype, name="linear_2")(temb)
87
+ return temb
88
+
89
+
90
+ class FlaxTimesteps(nn.Module):
91
+ r"""
92
+ Wrapper Module for sinusoidal Time step Embeddings as described in https://arxiv.org/abs/2006.11239
93
+
94
+ Args:
95
+ dim (`int`, *optional*, defaults to `32`):
96
+ Time step embedding dimension.
97
+ flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
98
+ Whether to flip the sinusoidal function from sine to cosine.
99
+ freq_shift (`float`, *optional*, defaults to `1`):
100
+ Frequency shift applied to the sinusoidal embeddings.
101
+ """
102
+
103
+ dim: int = 32
104
+ flip_sin_to_cos: bool = False
105
+ freq_shift: float = 1
106
+
107
+ @nn.compact
108
+ def __call__(self, timesteps):
109
+ return get_sinusoidal_embeddings(
110
+ timesteps, embedding_dim=self.dim, flip_sin_to_cos=self.flip_sin_to_cos, freq_shift=self.freq_shift
111
+ )
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/lora.py ADDED
@@ -0,0 +1,457 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ # IMPORTANT: #
17
+ ###################################################################
18
+ # ----------------------------------------------------------------#
19
+ # This file is deprecated and will be removed soon #
20
+ # (as soon as PEFT will become a required dependency for LoRA) #
21
+ # ----------------------------------------------------------------#
22
+ ###################################################################
23
+
24
+ from typing import Optional, Tuple, Union
25
+
26
+ import torch
27
+ import torch.nn.functional as F
28
+ from torch import nn
29
+
30
+ from ..utils import deprecate, logging
31
+ from ..utils.import_utils import is_transformers_available
32
+
33
+
34
+ if is_transformers_available():
35
+ from transformers import CLIPTextModel, CLIPTextModelWithProjection
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ def text_encoder_attn_modules(text_encoder: nn.Module):
42
+ attn_modules = []
43
+
44
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
45
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
46
+ name = f"text_model.encoder.layers.{i}.self_attn"
47
+ mod = layer.self_attn
48
+ attn_modules.append((name, mod))
49
+ else:
50
+ raise ValueError(f"do not know how to get attention modules for: {text_encoder.__class__.__name__}")
51
+
52
+ return attn_modules
53
+
54
+
55
+ def text_encoder_mlp_modules(text_encoder: nn.Module):
56
+ mlp_modules = []
57
+
58
+ if isinstance(text_encoder, (CLIPTextModel, CLIPTextModelWithProjection)):
59
+ for i, layer in enumerate(text_encoder.text_model.encoder.layers):
60
+ mlp_mod = layer.mlp
61
+ name = f"text_model.encoder.layers.{i}.mlp"
62
+ mlp_modules.append((name, mlp_mod))
63
+ else:
64
+ raise ValueError(f"do not know how to get mlp modules for: {text_encoder.__class__.__name__}")
65
+
66
+ return mlp_modules
67
+
68
+
69
+ def adjust_lora_scale_text_encoder(text_encoder, lora_scale: float = 1.0):
70
+ for _, attn_module in text_encoder_attn_modules(text_encoder):
71
+ if isinstance(attn_module.q_proj, PatchedLoraProjection):
72
+ attn_module.q_proj.lora_scale = lora_scale
73
+ attn_module.k_proj.lora_scale = lora_scale
74
+ attn_module.v_proj.lora_scale = lora_scale
75
+ attn_module.out_proj.lora_scale = lora_scale
76
+
77
+ for _, mlp_module in text_encoder_mlp_modules(text_encoder):
78
+ if isinstance(mlp_module.fc1, PatchedLoraProjection):
79
+ mlp_module.fc1.lora_scale = lora_scale
80
+ mlp_module.fc2.lora_scale = lora_scale
81
+
82
+
83
+ class PatchedLoraProjection(torch.nn.Module):
84
+ def __init__(self, regular_linear_layer, lora_scale=1, network_alpha=None, rank=4, dtype=None):
85
+ deprecation_message = "Use of `PatchedLoraProjection` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
86
+ deprecate("PatchedLoraProjection", "1.0.0", deprecation_message)
87
+
88
+ super().__init__()
89
+ from ..models.lora import LoRALinearLayer
90
+
91
+ self.regular_linear_layer = regular_linear_layer
92
+
93
+ device = self.regular_linear_layer.weight.device
94
+
95
+ if dtype is None:
96
+ dtype = self.regular_linear_layer.weight.dtype
97
+
98
+ self.lora_linear_layer = LoRALinearLayer(
99
+ self.regular_linear_layer.in_features,
100
+ self.regular_linear_layer.out_features,
101
+ network_alpha=network_alpha,
102
+ device=device,
103
+ dtype=dtype,
104
+ rank=rank,
105
+ )
106
+
107
+ self.lora_scale = lora_scale
108
+
109
+ # overwrite PyTorch's `state_dict` to be sure that only the 'regular_linear_layer' weights are saved
110
+ # when saving the whole text encoder model and when LoRA is unloaded or fused
111
+ def state_dict(self, *args, destination=None, prefix="", keep_vars=False):
112
+ if self.lora_linear_layer is None:
113
+ return self.regular_linear_layer.state_dict(
114
+ *args, destination=destination, prefix=prefix, keep_vars=keep_vars
115
+ )
116
+
117
+ return super().state_dict(*args, destination=destination, prefix=prefix, keep_vars=keep_vars)
118
+
119
+ def _fuse_lora(self, lora_scale=1.0, safe_fusing=False):
120
+ if self.lora_linear_layer is None:
121
+ return
122
+
123
+ dtype, device = self.regular_linear_layer.weight.data.dtype, self.regular_linear_layer.weight.data.device
124
+
125
+ w_orig = self.regular_linear_layer.weight.data.float()
126
+ w_up = self.lora_linear_layer.up.weight.data.float()
127
+ w_down = self.lora_linear_layer.down.weight.data.float()
128
+
129
+ if self.lora_linear_layer.network_alpha is not None:
130
+ w_up = w_up * self.lora_linear_layer.network_alpha / self.lora_linear_layer.rank
131
+
132
+ fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
133
+
134
+ if safe_fusing and torch.isnan(fused_weight).any().item():
135
+ raise ValueError(
136
+ "This LoRA weight seems to be broken. "
137
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
138
+ "LoRA weights will not be fused."
139
+ )
140
+
141
+ self.regular_linear_layer.weight.data = fused_weight.to(device=device, dtype=dtype)
142
+
143
+ # we can drop the lora layer now
144
+ self.lora_linear_layer = None
145
+
146
+ # offload the up and down matrices to CPU to not blow the memory
147
+ self.w_up = w_up.cpu()
148
+ self.w_down = w_down.cpu()
149
+ self.lora_scale = lora_scale
150
+
151
+ def _unfuse_lora(self):
152
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
153
+ return
154
+
155
+ fused_weight = self.regular_linear_layer.weight.data
156
+ dtype, device = fused_weight.dtype, fused_weight.device
157
+
158
+ w_up = self.w_up.to(device=device).float()
159
+ w_down = self.w_down.to(device).float()
160
+
161
+ unfused_weight = fused_weight.float() - (self.lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
162
+ self.regular_linear_layer.weight.data = unfused_weight.to(device=device, dtype=dtype)
163
+
164
+ self.w_up = None
165
+ self.w_down = None
166
+
167
+ def forward(self, input):
168
+ if self.lora_scale is None:
169
+ self.lora_scale = 1.0
170
+ if self.lora_linear_layer is None:
171
+ return self.regular_linear_layer(input)
172
+ return self.regular_linear_layer(input) + (self.lora_scale * self.lora_linear_layer(input))
173
+
174
+
175
+ class LoRALinearLayer(nn.Module):
176
+ r"""
177
+ A linear layer that is used with LoRA.
178
+
179
+ Parameters:
180
+ in_features (`int`):
181
+ Number of input features.
182
+ out_features (`int`):
183
+ Number of output features.
184
+ rank (`int`, `optional`, defaults to 4):
185
+ The rank of the LoRA layer.
186
+ network_alpha (`float`, `optional`, defaults to `None`):
187
+ The value of the network alpha used for stable learning and preventing underflow. This value has the same
188
+ meaning as the `--network_alpha` option in the kohya-ss trainer script. See
189
+ https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
190
+ device (`torch.device`, `optional`, defaults to `None`):
191
+ The device to use for the layer's weights.
192
+ dtype (`torch.dtype`, `optional`, defaults to `None`):
193
+ The dtype to use for the layer's weights.
194
+ """
195
+
196
+ def __init__(
197
+ self,
198
+ in_features: int,
199
+ out_features: int,
200
+ rank: int = 4,
201
+ network_alpha: Optional[float] = None,
202
+ device: Optional[Union[torch.device, str]] = None,
203
+ dtype: Optional[torch.dtype] = None,
204
+ ):
205
+ super().__init__()
206
+
207
+ deprecation_message = "Use of `LoRALinearLayer` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
208
+ deprecate("LoRALinearLayer", "1.0.0", deprecation_message)
209
+
210
+ self.down = nn.Linear(in_features, rank, bias=False, device=device, dtype=dtype)
211
+ self.up = nn.Linear(rank, out_features, bias=False, device=device, dtype=dtype)
212
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
213
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
214
+ self.network_alpha = network_alpha
215
+ self.rank = rank
216
+ self.out_features = out_features
217
+ self.in_features = in_features
218
+
219
+ nn.init.normal_(self.down.weight, std=1 / rank)
220
+ nn.init.zeros_(self.up.weight)
221
+
222
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
223
+ orig_dtype = hidden_states.dtype
224
+ dtype = self.down.weight.dtype
225
+
226
+ down_hidden_states = self.down(hidden_states.to(dtype))
227
+ up_hidden_states = self.up(down_hidden_states)
228
+
229
+ if self.network_alpha is not None:
230
+ up_hidden_states *= self.network_alpha / self.rank
231
+
232
+ return up_hidden_states.to(orig_dtype)
233
+
234
+
235
+ class LoRAConv2dLayer(nn.Module):
236
+ r"""
237
+ A convolutional layer that is used with LoRA.
238
+
239
+ Parameters:
240
+ in_features (`int`):
241
+ Number of input features.
242
+ out_features (`int`):
243
+ Number of output features.
244
+ rank (`int`, `optional`, defaults to 4):
245
+ The rank of the LoRA layer.
246
+ kernel_size (`int` or `tuple` of two `int`, `optional`, defaults to 1):
247
+ The kernel size of the convolution.
248
+ stride (`int` or `tuple` of two `int`, `optional`, defaults to 1):
249
+ The stride of the convolution.
250
+ padding (`int` or `tuple` of two `int` or `str`, `optional`, defaults to 0):
251
+ The padding of the convolution.
252
+ network_alpha (`float`, `optional`, defaults to `None`):
253
+ The value of the network alpha used for stable learning and preventing underflow. This value has the same
254
+ meaning as the `--network_alpha` option in the kohya-ss trainer script. See
255
+ https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
256
+ """
257
+
258
+ def __init__(
259
+ self,
260
+ in_features: int,
261
+ out_features: int,
262
+ rank: int = 4,
263
+ kernel_size: Union[int, Tuple[int, int]] = (1, 1),
264
+ stride: Union[int, Tuple[int, int]] = (1, 1),
265
+ padding: Union[int, Tuple[int, int], str] = 0,
266
+ network_alpha: Optional[float] = None,
267
+ ):
268
+ super().__init__()
269
+
270
+ deprecation_message = "Use of `LoRAConv2dLayer` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
271
+ deprecate("LoRAConv2dLayer", "1.0.0", deprecation_message)
272
+
273
+ self.down = nn.Conv2d(in_features, rank, kernel_size=kernel_size, stride=stride, padding=padding, bias=False)
274
+ # according to the official kohya_ss trainer kernel_size are always fixed for the up layer
275
+ # # see: https://github.com/bmaltais/kohya_ss/blob/2accb1305979ba62f5077a23aabac23b4c37e935/networks/lora_diffusers.py#L129
276
+ self.up = nn.Conv2d(rank, out_features, kernel_size=(1, 1), stride=(1, 1), bias=False)
277
+
278
+ # This value has the same meaning as the `--network_alpha` option in the kohya-ss trainer script.
279
+ # See https://github.com/darkstorm2150/sd-scripts/blob/main/docs/train_network_README-en.md#execute-learning
280
+ self.network_alpha = network_alpha
281
+ self.rank = rank
282
+
283
+ nn.init.normal_(self.down.weight, std=1 / rank)
284
+ nn.init.zeros_(self.up.weight)
285
+
286
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
287
+ orig_dtype = hidden_states.dtype
288
+ dtype = self.down.weight.dtype
289
+
290
+ down_hidden_states = self.down(hidden_states.to(dtype))
291
+ up_hidden_states = self.up(down_hidden_states)
292
+
293
+ if self.network_alpha is not None:
294
+ up_hidden_states *= self.network_alpha / self.rank
295
+
296
+ return up_hidden_states.to(orig_dtype)
297
+
298
+
299
+ class LoRACompatibleConv(nn.Conv2d):
300
+ """
301
+ A convolutional layer that can be used with LoRA.
302
+ """
303
+
304
+ def __init__(self, *args, lora_layer: Optional[LoRAConv2dLayer] = None, **kwargs):
305
+ deprecation_message = "Use of `LoRACompatibleConv` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
306
+ deprecate("LoRACompatibleConv", "1.0.0", deprecation_message)
307
+
308
+ super().__init__(*args, **kwargs)
309
+ self.lora_layer = lora_layer
310
+
311
+ def set_lora_layer(self, lora_layer: Optional[LoRAConv2dLayer]):
312
+ deprecation_message = "Use of `set_lora_layer()` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
313
+ deprecate("set_lora_layer", "1.0.0", deprecation_message)
314
+
315
+ self.lora_layer = lora_layer
316
+
317
+ def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
318
+ if self.lora_layer is None:
319
+ return
320
+
321
+ dtype, device = self.weight.data.dtype, self.weight.data.device
322
+
323
+ w_orig = self.weight.data.float()
324
+ w_up = self.lora_layer.up.weight.data.float()
325
+ w_down = self.lora_layer.down.weight.data.float()
326
+
327
+ if self.lora_layer.network_alpha is not None:
328
+ w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
329
+
330
+ fusion = torch.mm(w_up.flatten(start_dim=1), w_down.flatten(start_dim=1))
331
+ fusion = fusion.reshape((w_orig.shape))
332
+ fused_weight = w_orig + (lora_scale * fusion)
333
+
334
+ if safe_fusing and torch.isnan(fused_weight).any().item():
335
+ raise ValueError(
336
+ "This LoRA weight seems to be broken. "
337
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
338
+ "LoRA weights will not be fused."
339
+ )
340
+
341
+ self.weight.data = fused_weight.to(device=device, dtype=dtype)
342
+
343
+ # we can drop the lora layer now
344
+ self.lora_layer = None
345
+
346
+ # offload the up and down matrices to CPU to not blow the memory
347
+ self.w_up = w_up.cpu()
348
+ self.w_down = w_down.cpu()
349
+ self._lora_scale = lora_scale
350
+
351
+ def _unfuse_lora(self):
352
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
353
+ return
354
+
355
+ fused_weight = self.weight.data
356
+ dtype, device = fused_weight.data.dtype, fused_weight.data.device
357
+
358
+ self.w_up = self.w_up.to(device=device).float()
359
+ self.w_down = self.w_down.to(device).float()
360
+
361
+ fusion = torch.mm(self.w_up.flatten(start_dim=1), self.w_down.flatten(start_dim=1))
362
+ fusion = fusion.reshape((fused_weight.shape))
363
+ unfused_weight = fused_weight.float() - (self._lora_scale * fusion)
364
+ self.weight.data = unfused_weight.to(device=device, dtype=dtype)
365
+
366
+ self.w_up = None
367
+ self.w_down = None
368
+
369
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
370
+ if self.padding_mode != "zeros":
371
+ hidden_states = F.pad(hidden_states, self._reversed_padding_repeated_twice, mode=self.padding_mode)
372
+ padding = (0, 0)
373
+ else:
374
+ padding = self.padding
375
+
376
+ original_outputs = F.conv2d(
377
+ hidden_states, self.weight, self.bias, self.stride, padding, self.dilation, self.groups
378
+ )
379
+
380
+ if self.lora_layer is None:
381
+ return original_outputs
382
+ else:
383
+ return original_outputs + (scale * self.lora_layer(hidden_states))
384
+
385
+
386
+ class LoRACompatibleLinear(nn.Linear):
387
+ """
388
+ A Linear layer that can be used with LoRA.
389
+ """
390
+
391
+ def __init__(self, *args, lora_layer: Optional[LoRALinearLayer] = None, **kwargs):
392
+ deprecation_message = "Use of `LoRACompatibleLinear` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
393
+ deprecate("LoRACompatibleLinear", "1.0.0", deprecation_message)
394
+
395
+ super().__init__(*args, **kwargs)
396
+ self.lora_layer = lora_layer
397
+
398
+ def set_lora_layer(self, lora_layer: Optional[LoRALinearLayer]):
399
+ deprecation_message = "Use of `set_lora_layer()` is deprecated. Please switch to PEFT backend by installing PEFT: `pip install peft`."
400
+ deprecate("set_lora_layer", "1.0.0", deprecation_message)
401
+ self.lora_layer = lora_layer
402
+
403
+ def _fuse_lora(self, lora_scale: float = 1.0, safe_fusing: bool = False):
404
+ if self.lora_layer is None:
405
+ return
406
+
407
+ dtype, device = self.weight.data.dtype, self.weight.data.device
408
+
409
+ w_orig = self.weight.data.float()
410
+ w_up = self.lora_layer.up.weight.data.float()
411
+ w_down = self.lora_layer.down.weight.data.float()
412
+
413
+ if self.lora_layer.network_alpha is not None:
414
+ w_up = w_up * self.lora_layer.network_alpha / self.lora_layer.rank
415
+
416
+ fused_weight = w_orig + (lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
417
+
418
+ if safe_fusing and torch.isnan(fused_weight).any().item():
419
+ raise ValueError(
420
+ "This LoRA weight seems to be broken. "
421
+ f"Encountered NaN values when trying to fuse LoRA weights for {self}."
422
+ "LoRA weights will not be fused."
423
+ )
424
+
425
+ self.weight.data = fused_weight.to(device=device, dtype=dtype)
426
+
427
+ # we can drop the lora layer now
428
+ self.lora_layer = None
429
+
430
+ # offload the up and down matrices to CPU to not blow the memory
431
+ self.w_up = w_up.cpu()
432
+ self.w_down = w_down.cpu()
433
+ self._lora_scale = lora_scale
434
+
435
+ def _unfuse_lora(self):
436
+ if not (getattr(self, "w_up", None) is not None and getattr(self, "w_down", None) is not None):
437
+ return
438
+
439
+ fused_weight = self.weight.data
440
+ dtype, device = fused_weight.dtype, fused_weight.device
441
+
442
+ w_up = self.w_up.to(device=device).float()
443
+ w_down = self.w_down.to(device).float()
444
+
445
+ unfused_weight = fused_weight.float() - (self._lora_scale * torch.bmm(w_up[None, :], w_down[None, :])[0])
446
+ self.weight.data = unfused_weight.to(device=device, dtype=dtype)
447
+
448
+ self.w_up = None
449
+ self.w_down = None
450
+
451
+ def forward(self, hidden_states: torch.Tensor, scale: float = 1.0) -> torch.Tensor:
452
+ if self.lora_layer is None:
453
+ out = super().forward(hidden_states)
454
+ return out
455
+ else:
456
+ out = super().forward(hidden_states) + (scale * self.lora_layer(hidden_states))
457
+ return out
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/model_loading_utils.py ADDED
@@ -0,0 +1,522 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import importlib
18
+ import inspect
19
+ import os
20
+ from array import array
21
+ from collections import OrderedDict
22
+ from pathlib import Path
23
+ from typing import Dict, List, Optional, Union
24
+ from zipfile import is_zipfile
25
+
26
+ import safetensors
27
+ import torch
28
+ from huggingface_hub import DDUFEntry
29
+ from huggingface_hub.utils import EntryNotFoundError
30
+
31
+ from ..quantizers import DiffusersQuantizer
32
+ from ..utils import (
33
+ GGUF_FILE_EXTENSION,
34
+ SAFE_WEIGHTS_INDEX_NAME,
35
+ SAFETENSORS_FILE_EXTENSION,
36
+ WEIGHTS_INDEX_NAME,
37
+ _add_variant,
38
+ _get_model_file,
39
+ deprecate,
40
+ is_accelerate_available,
41
+ is_gguf_available,
42
+ is_torch_available,
43
+ is_torch_version,
44
+ logging,
45
+ )
46
+
47
+
48
+ logger = logging.get_logger(__name__)
49
+
50
+ _CLASS_REMAPPING_DICT = {
51
+ "Transformer2DModel": {
52
+ "ada_norm_zero": "DiTTransformer2DModel",
53
+ "ada_norm_single": "PixArtTransformer2DModel",
54
+ }
55
+ }
56
+
57
+
58
+ if is_accelerate_available():
59
+ from accelerate import infer_auto_device_map
60
+ from accelerate.utils import get_balanced_memory, get_max_memory, offload_weight, set_module_tensor_to_device
61
+
62
+
63
+ # Adapted from `transformers` (see modeling_utils.py)
64
+ def _determine_device_map(
65
+ model: torch.nn.Module, device_map, max_memory, torch_dtype, keep_in_fp32_modules=[], hf_quantizer=None
66
+ ):
67
+ if isinstance(device_map, str):
68
+ special_dtypes = {}
69
+ if hf_quantizer is not None:
70
+ special_dtypes.update(hf_quantizer.get_special_dtypes_update(model, torch_dtype))
71
+ special_dtypes.update(
72
+ {
73
+ name: torch.float32
74
+ for name, _ in model.named_parameters()
75
+ if any(m in name for m in keep_in_fp32_modules)
76
+ }
77
+ )
78
+
79
+ target_dtype = torch_dtype
80
+ if hf_quantizer is not None:
81
+ target_dtype = hf_quantizer.adjust_target_dtype(target_dtype)
82
+
83
+ no_split_modules = model._get_no_split_modules(device_map)
84
+ device_map_kwargs = {"no_split_module_classes": no_split_modules}
85
+
86
+ if "special_dtypes" in inspect.signature(infer_auto_device_map).parameters:
87
+ device_map_kwargs["special_dtypes"] = special_dtypes
88
+ elif len(special_dtypes) > 0:
89
+ logger.warning(
90
+ "This model has some weights that should be kept in higher precision, you need to upgrade "
91
+ "`accelerate` to properly deal with them (`pip install --upgrade accelerate`)."
92
+ )
93
+
94
+ if device_map != "sequential":
95
+ max_memory = get_balanced_memory(
96
+ model,
97
+ dtype=torch_dtype,
98
+ low_zero=(device_map == "balanced_low_0"),
99
+ max_memory=max_memory,
100
+ **device_map_kwargs,
101
+ )
102
+ else:
103
+ max_memory = get_max_memory(max_memory)
104
+
105
+ if hf_quantizer is not None:
106
+ max_memory = hf_quantizer.adjust_max_memory(max_memory)
107
+
108
+ device_map_kwargs["max_memory"] = max_memory
109
+ device_map = infer_auto_device_map(model, dtype=target_dtype, **device_map_kwargs)
110
+
111
+ if hf_quantizer is not None:
112
+ hf_quantizer.validate_environment(device_map=device_map)
113
+
114
+ return device_map
115
+
116
+
117
+ def _fetch_remapped_cls_from_config(config, old_class):
118
+ previous_class_name = old_class.__name__
119
+ remapped_class_name = _CLASS_REMAPPING_DICT.get(previous_class_name).get(config["norm_type"], None)
120
+
121
+ # Details:
122
+ # https://github.com/huggingface/diffusers/pull/7647#discussion_r1621344818
123
+ if remapped_class_name:
124
+ # load diffusers library to import compatible and original scheduler
125
+ diffusers_library = importlib.import_module(__name__.split(".")[0])
126
+ remapped_class = getattr(diffusers_library, remapped_class_name)
127
+ logger.info(
128
+ f"Changing class object to be of `{remapped_class_name}` type from `{previous_class_name}` type."
129
+ f"This is because `{previous_class_name}` is scheduled to be deprecated in a future version. Note that this"
130
+ " DOESN'T affect the final results."
131
+ )
132
+ return remapped_class
133
+ else:
134
+ return old_class
135
+
136
+
137
+ def _determine_param_device(param_name: str, device_map: Optional[Dict[str, Union[int, str, torch.device]]]):
138
+ """
139
+ Find the device of param_name from the device_map.
140
+ """
141
+ if device_map is None:
142
+ return "cpu"
143
+ else:
144
+ module_name = param_name
145
+ # find next higher level module that is defined in device_map:
146
+ # bert.lm_head.weight -> bert.lm_head -> bert -> ''
147
+ while len(module_name) > 0 and module_name not in device_map:
148
+ module_name = ".".join(module_name.split(".")[:-1])
149
+ if module_name == "" and "" not in device_map:
150
+ raise ValueError(f"{param_name} doesn't have any device set.")
151
+ return device_map[module_name]
152
+
153
+
154
+ def load_state_dict(
155
+ checkpoint_file: Union[str, os.PathLike],
156
+ dduf_entries: Optional[Dict[str, DDUFEntry]] = None,
157
+ disable_mmap: bool = False,
158
+ map_location: Union[str, torch.device] = "cpu",
159
+ ):
160
+ """
161
+ Reads a checkpoint file, returning properly formatted errors if they arise.
162
+ """
163
+ # TODO: maybe refactor a bit this part where we pass a dict here
164
+ if isinstance(checkpoint_file, dict):
165
+ return checkpoint_file
166
+ try:
167
+ file_extension = os.path.basename(checkpoint_file).split(".")[-1]
168
+ if file_extension == SAFETENSORS_FILE_EXTENSION:
169
+ if dduf_entries:
170
+ # tensors are loaded on cpu
171
+ with dduf_entries[checkpoint_file].as_mmap() as mm:
172
+ return safetensors.torch.load(mm)
173
+ if disable_mmap:
174
+ return safetensors.torch.load(open(checkpoint_file, "rb").read())
175
+ else:
176
+ return safetensors.torch.load_file(checkpoint_file, device=map_location)
177
+ elif file_extension == GGUF_FILE_EXTENSION:
178
+ return load_gguf_checkpoint(checkpoint_file)
179
+ else:
180
+ extra_args = {}
181
+ weights_only_kwarg = {"weights_only": True} if is_torch_version(">=", "1.13") else {}
182
+ # mmap can only be used with files serialized with zipfile-based format.
183
+ if (
184
+ isinstance(checkpoint_file, str)
185
+ and map_location != "meta"
186
+ and is_torch_version(">=", "2.1.0")
187
+ and is_zipfile(checkpoint_file)
188
+ and not disable_mmap
189
+ ):
190
+ extra_args = {"mmap": True}
191
+ return torch.load(checkpoint_file, map_location=map_location, **weights_only_kwarg, **extra_args)
192
+ except Exception as e:
193
+ try:
194
+ with open(checkpoint_file) as f:
195
+ if f.read().startswith("version"):
196
+ raise OSError(
197
+ "You seem to have cloned a repository without having git-lfs installed. Please install "
198
+ "git-lfs and run `git lfs install` followed by `git lfs pull` in the folder "
199
+ "you cloned."
200
+ )
201
+ else:
202
+ raise ValueError(
203
+ f"Unable to locate the file {checkpoint_file} which is necessary to load this pretrained "
204
+ "model. Make sure you have saved the model properly."
205
+ ) from e
206
+ except (UnicodeDecodeError, ValueError):
207
+ raise OSError(
208
+ f"Unable to load weights from checkpoint file for '{checkpoint_file}' at '{checkpoint_file}'. "
209
+ )
210
+
211
+
212
+ def load_model_dict_into_meta(
213
+ model,
214
+ state_dict: OrderedDict,
215
+ dtype: Optional[Union[str, torch.dtype]] = None,
216
+ model_name_or_path: Optional[str] = None,
217
+ hf_quantizer: Optional[DiffusersQuantizer] = None,
218
+ keep_in_fp32_modules: Optional[List] = None,
219
+ device_map: Optional[Dict[str, Union[int, str, torch.device]]] = None,
220
+ unexpected_keys: Optional[List[str]] = None,
221
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
222
+ offload_index: Optional[Dict] = None,
223
+ state_dict_index: Optional[Dict] = None,
224
+ state_dict_folder: Optional[Union[str, os.PathLike]] = None,
225
+ ) -> List[str]:
226
+ """
227
+ This is somewhat similar to `_load_state_dict_into_model`, but deals with a model that has some or all of its
228
+ params on a `meta` device. It replaces the model params with the data from the `state_dict`
229
+ """
230
+
231
+ is_quantized = hf_quantizer is not None
232
+ empty_state_dict = model.state_dict()
233
+
234
+ for param_name, param in state_dict.items():
235
+ if param_name not in empty_state_dict:
236
+ continue
237
+
238
+ set_module_kwargs = {}
239
+ # We convert floating dtypes to the `dtype` passed. We also want to keep the buffers/params
240
+ # in int/uint/bool and not cast them.
241
+ # TODO: revisit cases when param.dtype == torch.float8_e4m3fn
242
+ if dtype is not None and torch.is_floating_point(param):
243
+ if keep_in_fp32_modules is not None and any(
244
+ module_to_keep_in_fp32 in param_name.split(".") for module_to_keep_in_fp32 in keep_in_fp32_modules
245
+ ):
246
+ param = param.to(torch.float32)
247
+ set_module_kwargs["dtype"] = torch.float32
248
+ # For quantizers have save weights using torch.float8_e4m3fn
249
+ elif hf_quantizer is not None and param.dtype == getattr(torch, "float8_e4m3fn", None):
250
+ pass
251
+ else:
252
+ param = param.to(dtype)
253
+ set_module_kwargs["dtype"] = dtype
254
+
255
+ # For compatibility with PyTorch load_state_dict which converts state dict dtype to existing dtype in model, and which
256
+ # uses `param.copy_(input_param)` that preserves the contiguity of the parameter in the model.
257
+ # Reference: https://github.com/pytorch/pytorch/blob/db79ceb110f6646523019a59bbd7b838f43d4a86/torch/nn/modules/module.py#L2040C29-L2040C29
258
+ old_param = model
259
+ splits = param_name.split(".")
260
+ for split in splits:
261
+ old_param = getattr(old_param, split)
262
+
263
+ if not isinstance(old_param, (torch.nn.Parameter, torch.Tensor)):
264
+ old_param = None
265
+
266
+ if old_param is not None:
267
+ if dtype is None:
268
+ param = param.to(old_param.dtype)
269
+
270
+ if old_param.is_contiguous():
271
+ param = param.contiguous()
272
+
273
+ param_device = _determine_param_device(param_name, device_map)
274
+
275
+ # bnb params are flattened.
276
+ # gguf quants have a different shape based on the type of quantization applied
277
+ if empty_state_dict[param_name].shape != param.shape:
278
+ if (
279
+ is_quantized
280
+ and hf_quantizer.pre_quantized
281
+ and hf_quantizer.check_if_quantized_param(
282
+ model, param, param_name, state_dict, param_device=param_device
283
+ )
284
+ ):
285
+ hf_quantizer.check_quantized_param_shape(param_name, empty_state_dict[param_name], param)
286
+ else:
287
+ model_name_or_path_str = f"{model_name_or_path} " if model_name_or_path is not None else ""
288
+ raise ValueError(
289
+ f"Cannot load {model_name_or_path_str} because {param_name} expected shape {empty_state_dict[param_name].shape}, but got {param.shape}. If you want to instead overwrite randomly initialized weights, please make sure to pass both `low_cpu_mem_usage=False` and `ignore_mismatched_sizes=True`. For more information, see also: https://github.com/huggingface/diffusers/issues/1619#issuecomment-1345604389 as an example."
290
+ )
291
+ if param_device == "disk":
292
+ offload_index = offload_weight(param, param_name, offload_folder, offload_index)
293
+ elif param_device == "cpu" and state_dict_index is not None:
294
+ state_dict_index = offload_weight(param, param_name, state_dict_folder, state_dict_index)
295
+ elif is_quantized and (
296
+ hf_quantizer.check_if_quantized_param(model, param, param_name, state_dict, param_device=param_device)
297
+ ):
298
+ hf_quantizer.create_quantized_param(
299
+ model, param, param_name, param_device, state_dict, unexpected_keys, dtype=dtype
300
+ )
301
+ else:
302
+ set_module_tensor_to_device(model, param_name, param_device, value=param, **set_module_kwargs)
303
+
304
+ return offload_index, state_dict_index
305
+
306
+
307
+ def _load_state_dict_into_model(
308
+ model_to_load, state_dict: OrderedDict, assign_to_params_buffers: bool = False
309
+ ) -> List[str]:
310
+ # Convert old format to new format if needed from a PyTorch state_dict
311
+ # copy state_dict so _load_from_state_dict can modify it
312
+ state_dict = state_dict.copy()
313
+ error_msgs = []
314
+
315
+ # PyTorch's `_load_from_state_dict` does not copy parameters in a module's descendants
316
+ # so we need to apply the function recursively.
317
+ def load(module: torch.nn.Module, prefix: str = "", assign_to_params_buffers: bool = False):
318
+ local_metadata = {}
319
+ local_metadata["assign_to_params_buffers"] = assign_to_params_buffers
320
+ if assign_to_params_buffers and not is_torch_version(">=", "2.1"):
321
+ logger.info("You need to have torch>=2.1 in order to load the model with assign_to_params_buffers=True")
322
+ args = (state_dict, prefix, local_metadata, True, [], [], error_msgs)
323
+ module._load_from_state_dict(*args)
324
+
325
+ for name, child in module._modules.items():
326
+ if child is not None:
327
+ load(child, prefix + name + ".", assign_to_params_buffers)
328
+
329
+ load(model_to_load, assign_to_params_buffers=assign_to_params_buffers)
330
+
331
+ return error_msgs
332
+
333
+
334
+ def _fetch_index_file(
335
+ is_local,
336
+ pretrained_model_name_or_path,
337
+ subfolder,
338
+ use_safetensors,
339
+ cache_dir,
340
+ variant,
341
+ force_download,
342
+ proxies,
343
+ local_files_only,
344
+ token,
345
+ revision,
346
+ user_agent,
347
+ commit_hash,
348
+ dduf_entries: Optional[Dict[str, DDUFEntry]] = None,
349
+ ):
350
+ if is_local:
351
+ index_file = Path(
352
+ pretrained_model_name_or_path,
353
+ subfolder or "",
354
+ _add_variant(SAFE_WEIGHTS_INDEX_NAME if use_safetensors else WEIGHTS_INDEX_NAME, variant),
355
+ )
356
+ else:
357
+ index_file_in_repo = Path(
358
+ subfolder or "",
359
+ _add_variant(SAFE_WEIGHTS_INDEX_NAME if use_safetensors else WEIGHTS_INDEX_NAME, variant),
360
+ ).as_posix()
361
+ try:
362
+ index_file = _get_model_file(
363
+ pretrained_model_name_or_path,
364
+ weights_name=index_file_in_repo,
365
+ cache_dir=cache_dir,
366
+ force_download=force_download,
367
+ proxies=proxies,
368
+ local_files_only=local_files_only,
369
+ token=token,
370
+ revision=revision,
371
+ subfolder=None,
372
+ user_agent=user_agent,
373
+ commit_hash=commit_hash,
374
+ dduf_entries=dduf_entries,
375
+ )
376
+ if not dduf_entries:
377
+ index_file = Path(index_file)
378
+ except (EntryNotFoundError, EnvironmentError):
379
+ index_file = None
380
+
381
+ return index_file
382
+
383
+
384
+ def _fetch_index_file_legacy(
385
+ is_local,
386
+ pretrained_model_name_or_path,
387
+ subfolder,
388
+ use_safetensors,
389
+ cache_dir,
390
+ variant,
391
+ force_download,
392
+ proxies,
393
+ local_files_only,
394
+ token,
395
+ revision,
396
+ user_agent,
397
+ commit_hash,
398
+ dduf_entries: Optional[Dict[str, DDUFEntry]] = None,
399
+ ):
400
+ if is_local:
401
+ index_file = Path(
402
+ pretrained_model_name_or_path,
403
+ subfolder or "",
404
+ SAFE_WEIGHTS_INDEX_NAME if use_safetensors else WEIGHTS_INDEX_NAME,
405
+ ).as_posix()
406
+ splits = index_file.split(".")
407
+ split_index = -3 if ".cache" in index_file else -2
408
+ splits = splits[:-split_index] + [variant] + splits[-split_index:]
409
+ index_file = ".".join(splits)
410
+ if os.path.exists(index_file):
411
+ deprecation_message = f"This serialization format is now deprecated to standardize the serialization format between `transformers` and `diffusers`. We recommend you to remove the existing files associated with the current variant ({variant}) and re-obtain them by running a `save_pretrained()`."
412
+ deprecate("legacy_sharded_ckpts_with_variant", "1.0.0", deprecation_message, standard_warn=False)
413
+ index_file = Path(index_file)
414
+ else:
415
+ index_file = None
416
+ else:
417
+ if variant is not None:
418
+ index_file_in_repo = Path(
419
+ subfolder or "",
420
+ SAFE_WEIGHTS_INDEX_NAME if use_safetensors else WEIGHTS_INDEX_NAME,
421
+ ).as_posix()
422
+ splits = index_file_in_repo.split(".")
423
+ split_index = -2
424
+ splits = splits[:-split_index] + [variant] + splits[-split_index:]
425
+ index_file_in_repo = ".".join(splits)
426
+ try:
427
+ index_file = _get_model_file(
428
+ pretrained_model_name_or_path,
429
+ weights_name=index_file_in_repo,
430
+ cache_dir=cache_dir,
431
+ force_download=force_download,
432
+ proxies=proxies,
433
+ local_files_only=local_files_only,
434
+ token=token,
435
+ revision=revision,
436
+ subfolder=None,
437
+ user_agent=user_agent,
438
+ commit_hash=commit_hash,
439
+ dduf_entries=dduf_entries,
440
+ )
441
+ index_file = Path(index_file)
442
+ deprecation_message = f"This serialization format is now deprecated to standardize the serialization format between `transformers` and `diffusers`. We recommend you to remove the existing files associated with the current variant ({variant}) and re-obtain them by running a `save_pretrained()`."
443
+ deprecate("legacy_sharded_ckpts_with_variant", "1.0.0", deprecation_message, standard_warn=False)
444
+ except (EntryNotFoundError, EnvironmentError):
445
+ index_file = None
446
+
447
+ return index_file
448
+
449
+
450
+ def _gguf_parse_value(_value, data_type):
451
+ if not isinstance(data_type, list):
452
+ data_type = [data_type]
453
+ if len(data_type) == 1:
454
+ data_type = data_type[0]
455
+ array_data_type = None
456
+ else:
457
+ if data_type[0] != 9:
458
+ raise ValueError("Received multiple types, therefore expected the first type to indicate an array.")
459
+ data_type, array_data_type = data_type
460
+
461
+ if data_type in [0, 1, 2, 3, 4, 5, 10, 11]:
462
+ _value = int(_value[0])
463
+ elif data_type in [6, 12]:
464
+ _value = float(_value[0])
465
+ elif data_type in [7]:
466
+ _value = bool(_value[0])
467
+ elif data_type in [8]:
468
+ _value = array("B", list(_value)).tobytes().decode()
469
+ elif data_type in [9]:
470
+ _value = _gguf_parse_value(_value, array_data_type)
471
+ return _value
472
+
473
+
474
+ def load_gguf_checkpoint(gguf_checkpoint_path, return_tensors=False):
475
+ """
476
+ Load a GGUF file and return a dictionary of parsed parameters containing tensors, the parsed tokenizer and config
477
+ attributes.
478
+
479
+ Args:
480
+ gguf_checkpoint_path (`str`):
481
+ The path the to GGUF file to load
482
+ return_tensors (`bool`, defaults to `True`):
483
+ Whether to read the tensors from the file and return them. Not doing so is faster and only loads the
484
+ metadata in memory.
485
+ """
486
+
487
+ if is_gguf_available() and is_torch_available():
488
+ import gguf
489
+ from gguf import GGUFReader
490
+
491
+ from ..quantizers.gguf.utils import SUPPORTED_GGUF_QUANT_TYPES, GGUFParameter
492
+ else:
493
+ logger.error(
494
+ "Loading a GGUF checkpoint in PyTorch, requires both PyTorch and GGUF>=0.10.0 to be installed. Please see "
495
+ "https://pytorch.org/ and https://github.com/ggerganov/llama.cpp/tree/master/gguf-py for installation instructions."
496
+ )
497
+ raise ImportError("Please install torch and gguf>=0.10.0 to load a GGUF checkpoint in PyTorch.")
498
+
499
+ reader = GGUFReader(gguf_checkpoint_path)
500
+
501
+ parsed_parameters = {}
502
+ for tensor in reader.tensors:
503
+ name = tensor.name
504
+ quant_type = tensor.tensor_type
505
+
506
+ # if the tensor is a torch supported dtype do not use GGUFParameter
507
+ is_gguf_quant = quant_type not in [gguf.GGMLQuantizationType.F32, gguf.GGMLQuantizationType.F16]
508
+ if is_gguf_quant and quant_type not in SUPPORTED_GGUF_QUANT_TYPES:
509
+ _supported_quants_str = "\n".join([str(type) for type in SUPPORTED_GGUF_QUANT_TYPES])
510
+ raise ValueError(
511
+ (
512
+ f"{name} has a quantization type: {str(quant_type)} which is unsupported."
513
+ "\n\nCurrently the following quantization types are supported: \n\n"
514
+ f"{_supported_quants_str}"
515
+ "\n\nTo request support for this quantization type please open an issue here: https://github.com/huggingface/diffusers"
516
+ )
517
+ )
518
+
519
+ weights = torch.from_numpy(tensor.data.copy())
520
+ parsed_parameters[name] = GGUFParameter(weights, quant_type=quant_type) if is_gguf_quant else weights
521
+
522
+ return parsed_parameters
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_flax_pytorch_utils.py ADDED
@@ -0,0 +1,135 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch - Flax general utilities."""
16
+
17
+ import re
18
+
19
+ import jax.numpy as jnp
20
+ from flax.traverse_util import flatten_dict, unflatten_dict
21
+ from jax.random import PRNGKey
22
+
23
+ from ..utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ def rename_key(key):
30
+ regex = r"\w+[.]\d+"
31
+ pats = re.findall(regex, key)
32
+ for pat in pats:
33
+ key = key.replace(pat, "_".join(pat.split(".")))
34
+ return key
35
+
36
+
37
+ #####################
38
+ # PyTorch => Flax #
39
+ #####################
40
+
41
+
42
+ # Adapted from https://github.com/huggingface/transformers/blob/c603c80f46881ae18b2ca50770ef65fa4033eacd/src/transformers/modeling_flax_pytorch_utils.py#L69
43
+ # and https://github.com/patil-suraj/stable-diffusion-jax/blob/main/stable_diffusion_jax/convert_diffusers_to_jax.py
44
+ def rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict):
45
+ """Rename PT weight names to corresponding Flax weight names and reshape tensor if necessary"""
46
+ # conv norm or layer norm
47
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
48
+
49
+ # rename attention layers
50
+ if len(pt_tuple_key) > 1:
51
+ for rename_from, rename_to in (
52
+ ("to_out_0", "proj_attn"),
53
+ ("to_k", "key"),
54
+ ("to_v", "value"),
55
+ ("to_q", "query"),
56
+ ):
57
+ if pt_tuple_key[-2] == rename_from:
58
+ weight_name = pt_tuple_key[-1]
59
+ weight_name = "kernel" if weight_name == "weight" else weight_name
60
+ renamed_pt_tuple_key = pt_tuple_key[:-2] + (rename_to, weight_name)
61
+ if renamed_pt_tuple_key in random_flax_state_dict:
62
+ assert random_flax_state_dict[renamed_pt_tuple_key].shape == pt_tensor.T.shape
63
+ return renamed_pt_tuple_key, pt_tensor.T
64
+
65
+ if (
66
+ any("norm" in str_ for str_ in pt_tuple_key)
67
+ and (pt_tuple_key[-1] == "bias")
68
+ and (pt_tuple_key[:-1] + ("bias",) not in random_flax_state_dict)
69
+ and (pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict)
70
+ ):
71
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
72
+ return renamed_pt_tuple_key, pt_tensor
73
+ elif pt_tuple_key[-1] in ["weight", "gamma"] and pt_tuple_key[:-1] + ("scale",) in random_flax_state_dict:
74
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("scale",)
75
+ return renamed_pt_tuple_key, pt_tensor
76
+
77
+ # embedding
78
+ if pt_tuple_key[-1] == "weight" and pt_tuple_key[:-1] + ("embedding",) in random_flax_state_dict:
79
+ pt_tuple_key = pt_tuple_key[:-1] + ("embedding",)
80
+ return renamed_pt_tuple_key, pt_tensor
81
+
82
+ # conv layer
83
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
84
+ if pt_tuple_key[-1] == "weight" and pt_tensor.ndim == 4:
85
+ pt_tensor = pt_tensor.transpose(2, 3, 1, 0)
86
+ return renamed_pt_tuple_key, pt_tensor
87
+
88
+ # linear layer
89
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("kernel",)
90
+ if pt_tuple_key[-1] == "weight":
91
+ pt_tensor = pt_tensor.T
92
+ return renamed_pt_tuple_key, pt_tensor
93
+
94
+ # old PyTorch layer norm weight
95
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("weight",)
96
+ if pt_tuple_key[-1] == "gamma":
97
+ return renamed_pt_tuple_key, pt_tensor
98
+
99
+ # old PyTorch layer norm bias
100
+ renamed_pt_tuple_key = pt_tuple_key[:-1] + ("bias",)
101
+ if pt_tuple_key[-1] == "beta":
102
+ return renamed_pt_tuple_key, pt_tensor
103
+
104
+ return pt_tuple_key, pt_tensor
105
+
106
+
107
+ def convert_pytorch_state_dict_to_flax(pt_state_dict, flax_model, init_key=42):
108
+ # Step 1: Convert pytorch tensor to numpy
109
+ pt_state_dict = {k: v.numpy() for k, v in pt_state_dict.items()}
110
+
111
+ # Step 2: Since the model is stateless, get random Flax params
112
+ random_flax_params = flax_model.init_weights(PRNGKey(init_key))
113
+
114
+ random_flax_state_dict = flatten_dict(random_flax_params)
115
+ flax_state_dict = {}
116
+
117
+ # Need to change some parameters name to match Flax names
118
+ for pt_key, pt_tensor in pt_state_dict.items():
119
+ renamed_pt_key = rename_key(pt_key)
120
+ pt_tuple_key = tuple(renamed_pt_key.split("."))
121
+
122
+ # Correctly rename weight parameters
123
+ flax_key, flax_tensor = rename_key_and_reshape_tensor(pt_tuple_key, pt_tensor, random_flax_state_dict)
124
+
125
+ if flax_key in random_flax_state_dict:
126
+ if flax_tensor.shape != random_flax_state_dict[flax_key].shape:
127
+ raise ValueError(
128
+ f"PyTorch checkpoint seems to be incorrect. Weight {pt_key} was expected to be of shape "
129
+ f"{random_flax_state_dict[flax_key].shape}, but is {flax_tensor.shape}."
130
+ )
131
+
132
+ # also add unexpected weight so that warning is thrown
133
+ flax_state_dict[flax_key] = jnp.asarray(flax_tensor)
134
+
135
+ return unflatten_dict(flax_state_dict)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_flax_utils.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import os
17
+ from pickle import UnpicklingError
18
+ from typing import Any, Dict, Union
19
+
20
+ import jax
21
+ import jax.numpy as jnp
22
+ import msgpack.exceptions
23
+ from flax.core.frozen_dict import FrozenDict, unfreeze
24
+ from flax.serialization import from_bytes, to_bytes
25
+ from flax.traverse_util import flatten_dict, unflatten_dict
26
+ from huggingface_hub import create_repo, hf_hub_download
27
+ from huggingface_hub.utils import (
28
+ EntryNotFoundError,
29
+ RepositoryNotFoundError,
30
+ RevisionNotFoundError,
31
+ validate_hf_hub_args,
32
+ )
33
+ from requests import HTTPError
34
+
35
+ from .. import __version__, is_torch_available
36
+ from ..utils import (
37
+ CONFIG_NAME,
38
+ FLAX_WEIGHTS_NAME,
39
+ HUGGINGFACE_CO_RESOLVE_ENDPOINT,
40
+ WEIGHTS_NAME,
41
+ PushToHubMixin,
42
+ logging,
43
+ )
44
+ from .modeling_flax_pytorch_utils import convert_pytorch_state_dict_to_flax
45
+
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+
50
+ class FlaxModelMixin(PushToHubMixin):
51
+ r"""
52
+ Base class for all Flax models.
53
+
54
+ [`FlaxModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
55
+ saving models.
56
+
57
+ - **config_name** ([`str`]) -- Filename to save a model to when calling [`~FlaxModelMixin.save_pretrained`].
58
+ """
59
+
60
+ config_name = CONFIG_NAME
61
+ _automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
62
+ _flax_internal_args = ["name", "parent", "dtype"]
63
+
64
+ @classmethod
65
+ def _from_config(cls, config, **kwargs):
66
+ """
67
+ All context managers that the model should be initialized under go here.
68
+ """
69
+ return cls(config, **kwargs)
70
+
71
+ def _cast_floating_to(self, params: Union[Dict, FrozenDict], dtype: jnp.dtype, mask: Any = None) -> Any:
72
+ """
73
+ Helper method to cast floating-point values of given parameter `PyTree` to given `dtype`.
74
+ """
75
+
76
+ # taken from https://github.com/deepmind/jmp/blob/3a8318abc3292be38582794dbf7b094e6583b192/jmp/_src/policy.py#L27
77
+ def conditional_cast(param):
78
+ if isinstance(param, jnp.ndarray) and jnp.issubdtype(param.dtype, jnp.floating):
79
+ param = param.astype(dtype)
80
+ return param
81
+
82
+ if mask is None:
83
+ return jax.tree_map(conditional_cast, params)
84
+
85
+ flat_params = flatten_dict(params)
86
+ flat_mask, _ = jax.tree_flatten(mask)
87
+
88
+ for masked, key in zip(flat_mask, flat_params.keys()):
89
+ if masked:
90
+ param = flat_params[key]
91
+ flat_params[key] = conditional_cast(param)
92
+
93
+ return unflatten_dict(flat_params)
94
+
95
+ def to_bf16(self, params: Union[Dict, FrozenDict], mask: Any = None):
96
+ r"""
97
+ Cast the floating-point `params` to `jax.numpy.bfloat16`. This returns a new `params` tree and does not cast
98
+ the `params` in place.
99
+
100
+ This method can be used on a TPU to explicitly convert the model parameters to bfloat16 precision to do full
101
+ half-precision training or to save weights in bfloat16 for inference in order to save memory and improve speed.
102
+
103
+ Arguments:
104
+ params (`Union[Dict, FrozenDict]`):
105
+ A `PyTree` of model parameters.
106
+ mask (`Union[Dict, FrozenDict]`):
107
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
108
+ for params you want to cast, and `False` for those you want to skip.
109
+
110
+ Examples:
111
+
112
+ ```python
113
+ >>> from diffusers import FlaxUNet2DConditionModel
114
+
115
+ >>> # load model
116
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
117
+ >>> # By default, the model parameters will be in fp32 precision, to cast these to bfloat16 precision
118
+ >>> params = model.to_bf16(params)
119
+ >>> # If you don't want to cast certain parameters (for example layer norm bias and scale)
120
+ >>> # then pass the mask as follows
121
+ >>> from flax import traverse_util
122
+
123
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
124
+ >>> flat_params = traverse_util.flatten_dict(params)
125
+ >>> mask = {
126
+ ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
127
+ ... for path in flat_params
128
+ ... }
129
+ >>> mask = traverse_util.unflatten_dict(mask)
130
+ >>> params = model.to_bf16(params, mask)
131
+ ```"""
132
+ return self._cast_floating_to(params, jnp.bfloat16, mask)
133
+
134
+ def to_fp32(self, params: Union[Dict, FrozenDict], mask: Any = None):
135
+ r"""
136
+ Cast the floating-point `params` to `jax.numpy.float32`. This method can be used to explicitly convert the
137
+ model parameters to fp32 precision. This returns a new `params` tree and does not cast the `params` in place.
138
+
139
+ Arguments:
140
+ params (`Union[Dict, FrozenDict]`):
141
+ A `PyTree` of model parameters.
142
+ mask (`Union[Dict, FrozenDict]`):
143
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
144
+ for params you want to cast, and `False` for those you want to skip.
145
+
146
+ Examples:
147
+
148
+ ```python
149
+ >>> from diffusers import FlaxUNet2DConditionModel
150
+
151
+ >>> # Download model and configuration from huggingface.co
152
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
153
+ >>> # By default, the model params will be in fp32, to illustrate the use of this method,
154
+ >>> # we'll first cast to fp16 and back to fp32
155
+ >>> params = model.to_f16(params)
156
+ >>> # now cast back to fp32
157
+ >>> params = model.to_fp32(params)
158
+ ```"""
159
+ return self._cast_floating_to(params, jnp.float32, mask)
160
+
161
+ def to_fp16(self, params: Union[Dict, FrozenDict], mask: Any = None):
162
+ r"""
163
+ Cast the floating-point `params` to `jax.numpy.float16`. This returns a new `params` tree and does not cast the
164
+ `params` in place.
165
+
166
+ This method can be used on a GPU to explicitly convert the model parameters to float16 precision to do full
167
+ half-precision training or to save weights in float16 for inference in order to save memory and improve speed.
168
+
169
+ Arguments:
170
+ params (`Union[Dict, FrozenDict]`):
171
+ A `PyTree` of model parameters.
172
+ mask (`Union[Dict, FrozenDict]`):
173
+ A `PyTree` with same structure as the `params` tree. The leaves should be booleans. It should be `True`
174
+ for params you want to cast, and `False` for those you want to skip.
175
+
176
+ Examples:
177
+
178
+ ```python
179
+ >>> from diffusers import FlaxUNet2DConditionModel
180
+
181
+ >>> # load model
182
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
183
+ >>> # By default, the model params will be in fp32, to cast these to float16
184
+ >>> params = model.to_fp16(params)
185
+ >>> # If you want don't want to cast certain parameters (for example layer norm bias and scale)
186
+ >>> # then pass the mask as follows
187
+ >>> from flax import traverse_util
188
+
189
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
190
+ >>> flat_params = traverse_util.flatten_dict(params)
191
+ >>> mask = {
192
+ ... path: (path[-2] != ("LayerNorm", "bias") and path[-2:] != ("LayerNorm", "scale"))
193
+ ... for path in flat_params
194
+ ... }
195
+ >>> mask = traverse_util.unflatten_dict(mask)
196
+ >>> params = model.to_fp16(params, mask)
197
+ ```"""
198
+ return self._cast_floating_to(params, jnp.float16, mask)
199
+
200
+ def init_weights(self, rng: jax.Array) -> Dict:
201
+ raise NotImplementedError(f"init_weights method has to be implemented for {self}")
202
+
203
+ @classmethod
204
+ @validate_hf_hub_args
205
+ def from_pretrained(
206
+ cls,
207
+ pretrained_model_name_or_path: Union[str, os.PathLike],
208
+ dtype: jnp.dtype = jnp.float32,
209
+ *model_args,
210
+ **kwargs,
211
+ ):
212
+ r"""
213
+ Instantiate a pretrained Flax model from a pretrained model configuration.
214
+
215
+ Parameters:
216
+ pretrained_model_name_or_path (`str` or `os.PathLike`):
217
+ Can be either:
218
+
219
+ - A string, the *model id* (for example `runwayml/stable-diffusion-v1-5`) of a pretrained model
220
+ hosted on the Hub.
221
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
222
+ using [`~FlaxModelMixin.save_pretrained`].
223
+ dtype (`jax.numpy.dtype`, *optional*, defaults to `jax.numpy.float32`):
224
+ The data type of the computation. Can be one of `jax.numpy.float32`, `jax.numpy.float16` (on GPUs) and
225
+ `jax.numpy.bfloat16` (on TPUs).
226
+
227
+ This can be used to enable mixed-precision training or half-precision inference on GPUs or TPUs. If
228
+ specified, all the computation will be performed with the given `dtype`.
229
+
230
+ <Tip>
231
+
232
+ This only specifies the dtype of the *computation* and does not influence the dtype of model
233
+ parameters.
234
+
235
+ If you wish to change the dtype of the model parameters, see [`~FlaxModelMixin.to_fp16`] and
236
+ [`~FlaxModelMixin.to_bf16`].
237
+
238
+ </Tip>
239
+
240
+ model_args (sequence of positional arguments, *optional*):
241
+ All remaining positional arguments are passed to the underlying model's `__init__` method.
242
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
243
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
244
+ is not used.
245
+ force_download (`bool`, *optional*, defaults to `False`):
246
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
247
+ cached versions if they exist.
248
+
249
+ proxies (`Dict[str, str]`, *optional*):
250
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
251
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
252
+ local_files_only(`bool`, *optional*, defaults to `False`):
253
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
254
+ won't be downloaded from the Hub.
255
+ revision (`str`, *optional*, defaults to `"main"`):
256
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
257
+ allowed by Git.
258
+ from_pt (`bool`, *optional*, defaults to `False`):
259
+ Load the model weights from a PyTorch checkpoint save file.
260
+ kwargs (remaining dictionary of keyword arguments, *optional*):
261
+ Can be used to update the configuration object (after it is loaded) and initiate the model (for
262
+ example, `output_attentions=True`). Behaves differently depending on whether a `config` is provided or
263
+ automatically loaded:
264
+
265
+ - If a configuration is provided with `config`, `kwargs` are directly passed to the underlying
266
+ model's `__init__` method (we assume all relevant updates to the configuration have already been
267
+ done).
268
+ - If a configuration is not provided, `kwargs` are first passed to the configuration class
269
+ initialization function [`~ConfigMixin.from_config`]. Each key of the `kwargs` that corresponds
270
+ to a configuration attribute is used to override said attribute with the supplied `kwargs` value.
271
+ Remaining keys that do not correspond to any configuration attribute are passed to the underlying
272
+ model's `__init__` function.
273
+
274
+ Examples:
275
+
276
+ ```python
277
+ >>> from diffusers import FlaxUNet2DConditionModel
278
+
279
+ >>> # Download model and configuration from huggingface.co and cache.
280
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5")
281
+ >>> # Model was saved using *save_pretrained('./test/saved_model/')* (for example purposes, not runnable).
282
+ >>> model, params = FlaxUNet2DConditionModel.from_pretrained("./test/saved_model/")
283
+ ```
284
+
285
+ If you get the error message below, you need to finetune the weights for your downstream task:
286
+
287
+ ```bash
288
+ Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
289
+ - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
290
+ You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
291
+ ```
292
+ """
293
+ config = kwargs.pop("config", None)
294
+ cache_dir = kwargs.pop("cache_dir", None)
295
+ force_download = kwargs.pop("force_download", False)
296
+ from_pt = kwargs.pop("from_pt", False)
297
+ proxies = kwargs.pop("proxies", None)
298
+ local_files_only = kwargs.pop("local_files_only", False)
299
+ token = kwargs.pop("token", None)
300
+ revision = kwargs.pop("revision", None)
301
+ subfolder = kwargs.pop("subfolder", None)
302
+
303
+ user_agent = {
304
+ "diffusers": __version__,
305
+ "file_type": "model",
306
+ "framework": "flax",
307
+ }
308
+
309
+ # Load config if we don't provide one
310
+ if config is None:
311
+ config, unused_kwargs = cls.load_config(
312
+ pretrained_model_name_or_path,
313
+ cache_dir=cache_dir,
314
+ return_unused_kwargs=True,
315
+ force_download=force_download,
316
+ proxies=proxies,
317
+ local_files_only=local_files_only,
318
+ token=token,
319
+ revision=revision,
320
+ subfolder=subfolder,
321
+ **kwargs,
322
+ )
323
+
324
+ model, model_kwargs = cls.from_config(config, dtype=dtype, return_unused_kwargs=True, **unused_kwargs)
325
+
326
+ # Load model
327
+ pretrained_path_with_subfolder = (
328
+ pretrained_model_name_or_path
329
+ if subfolder is None
330
+ else os.path.join(pretrained_model_name_or_path, subfolder)
331
+ )
332
+ if os.path.isdir(pretrained_path_with_subfolder):
333
+ if from_pt:
334
+ if not os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
335
+ raise EnvironmentError(
336
+ f"Error no file named {WEIGHTS_NAME} found in directory {pretrained_path_with_subfolder} "
337
+ )
338
+ model_file = os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)
339
+ elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)):
340
+ # Load from a Flax checkpoint
341
+ model_file = os.path.join(pretrained_path_with_subfolder, FLAX_WEIGHTS_NAME)
342
+ # Check if pytorch weights exist instead
343
+ elif os.path.isfile(os.path.join(pretrained_path_with_subfolder, WEIGHTS_NAME)):
344
+ raise EnvironmentError(
345
+ f"{WEIGHTS_NAME} file found in directory {pretrained_path_with_subfolder}. Please load the model"
346
+ " using `from_pt=True`."
347
+ )
348
+ else:
349
+ raise EnvironmentError(
350
+ f"Error no file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME} found in directory "
351
+ f"{pretrained_path_with_subfolder}."
352
+ )
353
+ else:
354
+ try:
355
+ model_file = hf_hub_download(
356
+ pretrained_model_name_or_path,
357
+ filename=FLAX_WEIGHTS_NAME if not from_pt else WEIGHTS_NAME,
358
+ cache_dir=cache_dir,
359
+ force_download=force_download,
360
+ proxies=proxies,
361
+ local_files_only=local_files_only,
362
+ token=token,
363
+ user_agent=user_agent,
364
+ subfolder=subfolder,
365
+ revision=revision,
366
+ )
367
+
368
+ except RepositoryNotFoundError:
369
+ raise EnvironmentError(
370
+ f"{pretrained_model_name_or_path} is not a local folder and is not a valid model identifier "
371
+ "listed on 'https://huggingface.co/models'\nIf this is a private repository, make sure to pass a "
372
+ "token having permission to this repo with `token` or log in with `huggingface-cli "
373
+ "login`."
374
+ )
375
+ except RevisionNotFoundError:
376
+ raise EnvironmentError(
377
+ f"{revision} is not a valid git identifier (branch name, tag name or commit id) that exists for "
378
+ "this model name. Check the model page at "
379
+ f"'https://huggingface.co/{pretrained_model_name_or_path}' for available revisions."
380
+ )
381
+ except EntryNotFoundError:
382
+ raise EnvironmentError(
383
+ f"{pretrained_model_name_or_path} does not appear to have a file named {FLAX_WEIGHTS_NAME}."
384
+ )
385
+ except HTTPError as err:
386
+ raise EnvironmentError(
387
+ f"There was a specific connection error when trying to load {pretrained_model_name_or_path}:\n"
388
+ f"{err}"
389
+ )
390
+ except ValueError:
391
+ raise EnvironmentError(
392
+ f"We couldn't connect to '{HUGGINGFACE_CO_RESOLVE_ENDPOINT}' to load this model, couldn't find it"
393
+ f" in the cached files and it looks like {pretrained_model_name_or_path} is not the path to a"
394
+ f" directory containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}.\nCheckout your"
395
+ " internet connection or see how to run the library in offline mode at"
396
+ " 'https://huggingface.co/docs/transformers/installation#offline-mode'."
397
+ )
398
+ except EnvironmentError:
399
+ raise EnvironmentError(
400
+ f"Can't load the model for '{pretrained_model_name_or_path}'. If you were trying to load it from "
401
+ "'https://huggingface.co/models', make sure you don't have a local directory with the same name. "
402
+ f"Otherwise, make sure '{pretrained_model_name_or_path}' is the correct path to a directory "
403
+ f"containing a file named {FLAX_WEIGHTS_NAME} or {WEIGHTS_NAME}."
404
+ )
405
+
406
+ if from_pt:
407
+ if is_torch_available():
408
+ from .modeling_utils import load_state_dict
409
+ else:
410
+ raise EnvironmentError(
411
+ "Can't load the model in PyTorch format because PyTorch is not installed. "
412
+ "Please, install PyTorch or use native Flax weights."
413
+ )
414
+
415
+ # Step 1: Get the pytorch file
416
+ pytorch_model_file = load_state_dict(model_file)
417
+
418
+ # Step 2: Convert the weights
419
+ state = convert_pytorch_state_dict_to_flax(pytorch_model_file, model)
420
+ else:
421
+ try:
422
+ with open(model_file, "rb") as state_f:
423
+ state = from_bytes(cls, state_f.read())
424
+ except (UnpicklingError, msgpack.exceptions.ExtraData) as e:
425
+ try:
426
+ with open(model_file) as f:
427
+ if f.read().startswith("version"):
428
+ raise OSError(
429
+ "You seem to have cloned a repository without having git-lfs installed. Please"
430
+ " install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
431
+ " folder you cloned."
432
+ )
433
+ else:
434
+ raise ValueError from e
435
+ except (UnicodeDecodeError, ValueError):
436
+ raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. ")
437
+ # make sure all arrays are stored as jnp.ndarray
438
+ # NOTE: This is to prevent a bug this will be fixed in Flax >= v0.3.4:
439
+ # https://github.com/google/flax/issues/1261
440
+ state = jax.tree_util.tree_map(lambda x: jax.device_put(x, jax.local_devices(backend="cpu")[0]), state)
441
+
442
+ # flatten dicts
443
+ state = flatten_dict(state)
444
+
445
+ params_shape_tree = jax.eval_shape(model.init_weights, rng=jax.random.PRNGKey(0))
446
+ required_params = set(flatten_dict(unfreeze(params_shape_tree)).keys())
447
+
448
+ shape_state = flatten_dict(unfreeze(params_shape_tree))
449
+
450
+ missing_keys = required_params - set(state.keys())
451
+ unexpected_keys = set(state.keys()) - required_params
452
+
453
+ if missing_keys:
454
+ logger.warning(
455
+ f"The checkpoint {pretrained_model_name_or_path} is missing required keys: {missing_keys}. "
456
+ "Make sure to call model.init_weights to initialize the missing weights."
457
+ )
458
+ cls._missing_keys = missing_keys
459
+
460
+ for key in state.keys():
461
+ if key in shape_state and state[key].shape != shape_state[key].shape:
462
+ raise ValueError(
463
+ f"Trying to load the pretrained weight for {key} failed: checkpoint has shape "
464
+ f"{state[key].shape} which is incompatible with the model shape {shape_state[key].shape}. "
465
+ )
466
+
467
+ # remove unexpected keys to not be saved again
468
+ for unexpected_key in unexpected_keys:
469
+ del state[unexpected_key]
470
+
471
+ if len(unexpected_keys) > 0:
472
+ logger.warning(
473
+ f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when"
474
+ f" initializing {model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are"
475
+ f" initializing {model.__class__.__name__} from the checkpoint of a model trained on another task or"
476
+ " with another architecture."
477
+ )
478
+ else:
479
+ logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
480
+
481
+ if len(missing_keys) > 0:
482
+ logger.warning(
483
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
484
+ f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
485
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
486
+ )
487
+ else:
488
+ logger.info(
489
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
490
+ f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the checkpoint"
491
+ f" was trained on, you can already use {model.__class__.__name__} for predictions without further"
492
+ " training."
493
+ )
494
+
495
+ return model, unflatten_dict(state)
496
+
497
+ def save_pretrained(
498
+ self,
499
+ save_directory: Union[str, os.PathLike],
500
+ params: Union[Dict, FrozenDict],
501
+ is_main_process: bool = True,
502
+ push_to_hub: bool = False,
503
+ **kwargs,
504
+ ):
505
+ """
506
+ Save a model and its configuration file to a directory so that it can be reloaded using the
507
+ [`~FlaxModelMixin.from_pretrained`] class method.
508
+
509
+ Arguments:
510
+ save_directory (`str` or `os.PathLike`):
511
+ Directory to save a model and its configuration file to. Will be created if it doesn't exist.
512
+ params (`Union[Dict, FrozenDict]`):
513
+ A `PyTree` of model parameters.
514
+ is_main_process (`bool`, *optional*, defaults to `True`):
515
+ Whether the process calling this is the main process or not. Useful during distributed training and you
516
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
517
+ process to avoid race conditions.
518
+ push_to_hub (`bool`, *optional*, defaults to `False`):
519
+ Whether or not to push your model to the Hugging Face model hub after saving it. You can specify the
520
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
521
+ namespace).
522
+ kwargs (`Dict[str, Any]`, *optional*):
523
+ Additional key word arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
524
+ """
525
+ if os.path.isfile(save_directory):
526
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
527
+ return
528
+
529
+ os.makedirs(save_directory, exist_ok=True)
530
+
531
+ if push_to_hub:
532
+ commit_message = kwargs.pop("commit_message", None)
533
+ private = kwargs.pop("private", None)
534
+ create_pr = kwargs.pop("create_pr", False)
535
+ token = kwargs.pop("token", None)
536
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
537
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
538
+
539
+ model_to_save = self
540
+
541
+ # Attach architecture to the config
542
+ # Save the config
543
+ if is_main_process:
544
+ model_to_save.save_config(save_directory)
545
+
546
+ # save model
547
+ output_model_file = os.path.join(save_directory, FLAX_WEIGHTS_NAME)
548
+ with open(output_model_file, "wb") as f:
549
+ model_bytes = to_bytes(params)
550
+ f.write(model_bytes)
551
+
552
+ logger.info(f"Model weights saved in {output_model_file}")
553
+
554
+ if push_to_hub:
555
+ self._upload_folder(
556
+ save_directory,
557
+ repo_id,
558
+ token=token,
559
+ commit_message=commit_message,
560
+ create_pr=create_pr,
561
+ )
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_outputs.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ from ..utils import BaseOutput
4
+
5
+
6
+ @dataclass
7
+ class AutoencoderKLOutput(BaseOutput):
8
+ """
9
+ Output of AutoencoderKL encoding method.
10
+
11
+ Args:
12
+ latent_dist (`DiagonalGaussianDistribution`):
13
+ Encoded outputs of `Encoder` represented as the mean and logvar of `DiagonalGaussianDistribution`.
14
+ `DiagonalGaussianDistribution` allows for sampling latents from the distribution.
15
+ """
16
+
17
+ latent_dist: "DiagonalGaussianDistribution" # noqa: F821
18
+
19
+
20
+ @dataclass
21
+ class Transformer2DModelOutput(BaseOutput):
22
+ """
23
+ The output of [`Transformer2DModel`].
24
+
25
+ Args:
26
+ sample (`torch.Tensor` of shape `(batch_size, num_channels, height, width)` or `(batch size, num_vector_embeds - 1, num_latent_pixels)` if [`Transformer2DModel`] is discrete):
27
+ The hidden states output conditioned on the `encoder_hidden_states` input. If discrete, returns probability
28
+ distributions for the unnoised latent pixels.
29
+ """
30
+
31
+ sample: "torch.Tensor" # noqa: F821
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_pytorch_flax_utils.py ADDED
@@ -0,0 +1,161 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ """PyTorch - Flax general utilities."""
16
+
17
+ from pickle import UnpicklingError
18
+
19
+ import jax
20
+ import jax.numpy as jnp
21
+ import numpy as np
22
+ from flax.serialization import from_bytes
23
+ from flax.traverse_util import flatten_dict
24
+
25
+ from ..utils import logging
26
+
27
+
28
+ logger = logging.get_logger(__name__)
29
+
30
+
31
+ #####################
32
+ # Flax => PyTorch #
33
+ #####################
34
+
35
+
36
+ # from https://github.com/huggingface/transformers/blob/main/src/transformers/modeling_flax_pytorch_utils.py#L224-L352
37
+ def load_flax_checkpoint_in_pytorch_model(pt_model, model_file):
38
+ try:
39
+ with open(model_file, "rb") as flax_state_f:
40
+ flax_state = from_bytes(None, flax_state_f.read())
41
+ except UnpicklingError as e:
42
+ try:
43
+ with open(model_file) as f:
44
+ if f.read().startswith("version"):
45
+ raise OSError(
46
+ "You seem to have cloned a repository without having git-lfs installed. Please"
47
+ " install git-lfs and run `git lfs install` followed by `git lfs pull` in the"
48
+ " folder you cloned."
49
+ )
50
+ else:
51
+ raise ValueError from e
52
+ except (UnicodeDecodeError, ValueError):
53
+ raise EnvironmentError(f"Unable to convert {model_file} to Flax deserializable object. ")
54
+
55
+ return load_flax_weights_in_pytorch_model(pt_model, flax_state)
56
+
57
+
58
+ def load_flax_weights_in_pytorch_model(pt_model, flax_state):
59
+ """Load flax checkpoints in a PyTorch model"""
60
+
61
+ try:
62
+ import torch # noqa: F401
63
+ except ImportError:
64
+ logger.error(
65
+ "Loading Flax weights in PyTorch requires both PyTorch and Flax to be installed. Please see"
66
+ " https://pytorch.org/ and https://flax.readthedocs.io/en/latest/installation.html for installation"
67
+ " instructions."
68
+ )
69
+ raise
70
+
71
+ # check if we have bf16 weights
72
+ is_type_bf16 = flatten_dict(jax.tree_util.tree_map(lambda x: x.dtype == jnp.bfloat16, flax_state)).values()
73
+ if any(is_type_bf16):
74
+ # convert all weights to fp32 if they are bf16 since torch.from_numpy can-not handle bf16
75
+
76
+ # and bf16 is not fully supported in PT yet.
77
+ logger.warning(
78
+ "Found ``bfloat16`` weights in Flax model. Casting all ``bfloat16`` weights to ``float32`` "
79
+ "before loading those in PyTorch model."
80
+ )
81
+ flax_state = jax.tree_util.tree_map(
82
+ lambda params: params.astype(np.float32) if params.dtype == jnp.bfloat16 else params, flax_state
83
+ )
84
+
85
+ pt_model.base_model_prefix = ""
86
+
87
+ flax_state_dict = flatten_dict(flax_state, sep=".")
88
+ pt_model_dict = pt_model.state_dict()
89
+
90
+ # keep track of unexpected & missing keys
91
+ unexpected_keys = []
92
+ missing_keys = set(pt_model_dict.keys())
93
+
94
+ for flax_key_tuple, flax_tensor in flax_state_dict.items():
95
+ flax_key_tuple_array = flax_key_tuple.split(".")
96
+
97
+ if flax_key_tuple_array[-1] == "kernel" and flax_tensor.ndim == 4:
98
+ flax_key_tuple_array = flax_key_tuple_array[:-1] + ["weight"]
99
+ flax_tensor = jnp.transpose(flax_tensor, (3, 2, 0, 1))
100
+ elif flax_key_tuple_array[-1] == "kernel":
101
+ flax_key_tuple_array = flax_key_tuple_array[:-1] + ["weight"]
102
+ flax_tensor = flax_tensor.T
103
+ elif flax_key_tuple_array[-1] == "scale":
104
+ flax_key_tuple_array = flax_key_tuple_array[:-1] + ["weight"]
105
+
106
+ if "time_embedding" not in flax_key_tuple_array:
107
+ for i, flax_key_tuple_string in enumerate(flax_key_tuple_array):
108
+ flax_key_tuple_array[i] = (
109
+ flax_key_tuple_string.replace("_0", ".0")
110
+ .replace("_1", ".1")
111
+ .replace("_2", ".2")
112
+ .replace("_3", ".3")
113
+ .replace("_4", ".4")
114
+ .replace("_5", ".5")
115
+ .replace("_6", ".6")
116
+ .replace("_7", ".7")
117
+ .replace("_8", ".8")
118
+ .replace("_9", ".9")
119
+ )
120
+
121
+ flax_key = ".".join(flax_key_tuple_array)
122
+
123
+ if flax_key in pt_model_dict:
124
+ if flax_tensor.shape != pt_model_dict[flax_key].shape:
125
+ raise ValueError(
126
+ f"Flax checkpoint seems to be incorrect. Weight {flax_key_tuple} was expected "
127
+ f"to be of shape {pt_model_dict[flax_key].shape}, but is {flax_tensor.shape}."
128
+ )
129
+ else:
130
+ # add weight to pytorch dict
131
+ flax_tensor = np.asarray(flax_tensor) if not isinstance(flax_tensor, np.ndarray) else flax_tensor
132
+ pt_model_dict[flax_key] = torch.from_numpy(flax_tensor)
133
+ # remove from missing keys
134
+ missing_keys.remove(flax_key)
135
+ else:
136
+ # weight is not expected by PyTorch model
137
+ unexpected_keys.append(flax_key)
138
+
139
+ pt_model.load_state_dict(pt_model_dict)
140
+
141
+ # re-transform missing_keys to list
142
+ missing_keys = list(missing_keys)
143
+
144
+ if len(unexpected_keys) > 0:
145
+ logger.warning(
146
+ "Some weights of the Flax model were not used when initializing the PyTorch model"
147
+ f" {pt_model.__class__.__name__}: {unexpected_keys}\n- This IS expected if you are initializing"
148
+ f" {pt_model.__class__.__name__} from a Flax model trained on another task or with another architecture"
149
+ " (e.g. initializing a BertForSequenceClassification model from a FlaxBertForPreTraining model).\n- This"
150
+ f" IS NOT expected if you are initializing {pt_model.__class__.__name__} from a Flax model that you expect"
151
+ " to be exactly identical (e.g. initializing a BertForSequenceClassification model from a"
152
+ " FlaxBertForSequenceClassification model)."
153
+ )
154
+ if len(missing_keys) > 0:
155
+ logger.warning(
156
+ f"Some weights of {pt_model.__class__.__name__} were not initialized from the Flax model and are newly"
157
+ f" initialized: {missing_keys}\nYou should probably TRAIN this model on a down-stream task to be able to"
158
+ " use it for predictions and inference."
159
+ )
160
+
161
+ return pt_model
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/modeling_utils.py ADDED
@@ -0,0 +1,1831 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2025 The HuggingFace Inc. team.
3
+ # Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved.
4
+ #
5
+ # Licensed under the Apache License, Version 2.0 (the "License");
6
+ # you may not use this file except in compliance with the License.
7
+ # You may obtain a copy of the License at
8
+ #
9
+ # http://www.apache.org/licenses/LICENSE-2.0
10
+ #
11
+ # Unless required by applicable law or agreed to in writing, software
12
+ # distributed under the License is distributed on an "AS IS" BASIS,
13
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ # See the License for the specific language governing permissions and
15
+ # limitations under the License.
16
+
17
+ import copy
18
+ import inspect
19
+ import itertools
20
+ import json
21
+ import os
22
+ import re
23
+ import shutil
24
+ import tempfile
25
+ from collections import OrderedDict
26
+ from contextlib import ExitStack, contextmanager
27
+ from functools import wraps
28
+ from pathlib import Path
29
+ from typing import Any, Callable, ContextManager, Dict, List, Optional, Tuple, Type, Union
30
+
31
+ import safetensors
32
+ import torch
33
+ import torch.utils.checkpoint
34
+ from huggingface_hub import DDUFEntry, create_repo, split_torch_state_dict_into_shards
35
+ from huggingface_hub.utils import validate_hf_hub_args
36
+ from torch import Tensor, nn
37
+ from typing_extensions import Self
38
+
39
+ from .. import __version__
40
+ from ..quantizers import DiffusersAutoQuantizer, DiffusersQuantizer
41
+ from ..quantizers.quantization_config import QuantizationMethod
42
+ from ..utils import (
43
+ CONFIG_NAME,
44
+ FLAX_WEIGHTS_NAME,
45
+ SAFE_WEIGHTS_INDEX_NAME,
46
+ SAFETENSORS_WEIGHTS_NAME,
47
+ WEIGHTS_INDEX_NAME,
48
+ WEIGHTS_NAME,
49
+ _add_variant,
50
+ _get_checkpoint_shard_files,
51
+ _get_model_file,
52
+ deprecate,
53
+ is_accelerate_available,
54
+ is_bitsandbytes_available,
55
+ is_bitsandbytes_version,
56
+ is_peft_available,
57
+ is_torch_version,
58
+ logging,
59
+ )
60
+ from ..utils.hub_utils import (
61
+ PushToHubMixin,
62
+ load_or_create_model_card,
63
+ populate_model_card,
64
+ )
65
+ from .model_loading_utils import (
66
+ _determine_device_map,
67
+ _fetch_index_file,
68
+ _fetch_index_file_legacy,
69
+ _load_state_dict_into_model,
70
+ load_model_dict_into_meta,
71
+ load_state_dict,
72
+ )
73
+
74
+
75
+ class ContextManagers:
76
+ """
77
+ Wrapper for `contextlib.ExitStack` which enters a collection of context managers. Adaptation of `ContextManagers`
78
+ in the `fastcore` library.
79
+ """
80
+
81
+ def __init__(self, context_managers: List[ContextManager]):
82
+ self.context_managers = context_managers
83
+ self.stack = ExitStack()
84
+
85
+ def __enter__(self):
86
+ for context_manager in self.context_managers:
87
+ self.stack.enter_context(context_manager)
88
+
89
+ def __exit__(self, *args, **kwargs):
90
+ self.stack.__exit__(*args, **kwargs)
91
+
92
+
93
+ logger = logging.get_logger(__name__)
94
+
95
+ _REGEX_SHARD = re.compile(r"(.*?)-\d{5}-of-\d{5}")
96
+
97
+ TORCH_INIT_FUNCTIONS = {
98
+ "uniform_": nn.init.uniform_,
99
+ "normal_": nn.init.normal_,
100
+ "trunc_normal_": nn.init.trunc_normal_,
101
+ "constant_": nn.init.constant_,
102
+ "xavier_uniform_": nn.init.xavier_uniform_,
103
+ "xavier_normal_": nn.init.xavier_normal_,
104
+ "kaiming_uniform_": nn.init.kaiming_uniform_,
105
+ "kaiming_normal_": nn.init.kaiming_normal_,
106
+ "uniform": nn.init.uniform,
107
+ "normal": nn.init.normal,
108
+ "xavier_uniform": nn.init.xavier_uniform,
109
+ "xavier_normal": nn.init.xavier_normal,
110
+ "kaiming_uniform": nn.init.kaiming_uniform,
111
+ "kaiming_normal": nn.init.kaiming_normal,
112
+ }
113
+
114
+ if is_torch_version(">=", "1.9.0"):
115
+ _LOW_CPU_MEM_USAGE_DEFAULT = True
116
+ else:
117
+ _LOW_CPU_MEM_USAGE_DEFAULT = False
118
+
119
+
120
+ if is_accelerate_available():
121
+ import accelerate
122
+ from accelerate import dispatch_model
123
+ from accelerate.utils import load_offloaded_weights, save_offload_index
124
+
125
+
126
+ def get_parameter_device(parameter: torch.nn.Module) -> torch.device:
127
+ from ..hooks.group_offloading import _get_group_onload_device
128
+
129
+ try:
130
+ # Try to get the onload device from the group offloading hook
131
+ return _get_group_onload_device(parameter)
132
+ except ValueError:
133
+ pass
134
+
135
+ try:
136
+ # If the onload device is not available due to no group offloading hooks, try to get the device
137
+ # from the first parameter or buffer
138
+ parameters_and_buffers = itertools.chain(parameter.parameters(), parameter.buffers())
139
+ return next(parameters_and_buffers).device
140
+ except StopIteration:
141
+ # For torch.nn.DataParallel compatibility in PyTorch 1.5
142
+
143
+ def find_tensor_attributes(module: torch.nn.Module) -> List[Tuple[str, Tensor]]:
144
+ tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
145
+ return tuples
146
+
147
+ gen = parameter._named_members(get_members_fn=find_tensor_attributes)
148
+ first_tuple = next(gen)
149
+ return first_tuple[1].device
150
+
151
+
152
+ def get_parameter_dtype(parameter: torch.nn.Module) -> torch.dtype:
153
+ """
154
+ Returns the first found floating dtype in parameters if there is one, otherwise returns the last dtype it found.
155
+ """
156
+ # 1. Check if we have attached any dtype modifying hooks (eg. layerwise casting)
157
+ if isinstance(parameter, nn.Module):
158
+ for name, submodule in parameter.named_modules():
159
+ if not hasattr(submodule, "_diffusers_hook"):
160
+ continue
161
+ registry = submodule._diffusers_hook
162
+ hook = registry.get_hook("layerwise_casting")
163
+ if hook is not None:
164
+ return hook.compute_dtype
165
+
166
+ # 2. If no dtype modifying hooks are attached, return the dtype of the first floating point parameter/buffer
167
+ last_dtype = None
168
+
169
+ for name, param in parameter.named_parameters():
170
+ last_dtype = param.dtype
171
+ if parameter._keep_in_fp32_modules and any(m in name for m in parameter._keep_in_fp32_modules):
172
+ continue
173
+
174
+ if param.is_floating_point():
175
+ return param.dtype
176
+
177
+ for buffer in parameter.buffers():
178
+ last_dtype = buffer.dtype
179
+ if buffer.is_floating_point():
180
+ return buffer.dtype
181
+
182
+ if last_dtype is not None:
183
+ # if no floating dtype was found return whatever the first dtype is
184
+ return last_dtype
185
+
186
+ # For nn.DataParallel compatibility in PyTorch > 1.5
187
+ def find_tensor_attributes(module: nn.Module) -> List[Tuple[str, Tensor]]:
188
+ tuples = [(k, v) for k, v in module.__dict__.items() if torch.is_tensor(v)]
189
+ return tuples
190
+
191
+ gen = parameter._named_members(get_members_fn=find_tensor_attributes)
192
+ last_tuple = None
193
+ for tuple in gen:
194
+ last_tuple = tuple
195
+ if tuple[1].is_floating_point():
196
+ return tuple[1].dtype
197
+
198
+ if last_tuple is not None:
199
+ # fallback to the last dtype
200
+ return last_tuple[1].dtype
201
+
202
+
203
+ def check_support_param_buffer_assignment(model_to_load, state_dict, start_prefix=""):
204
+ """
205
+ Checks if `model_to_load` supports param buffer assignment (such as when loading in empty weights) by first
206
+ checking if the model explicitly disables it, then by ensuring that the state dict keys are a subset of the model's
207
+ parameters.
208
+
209
+ """
210
+ if model_to_load.device.type == "meta":
211
+ return False
212
+
213
+ if len([key for key in state_dict if key.startswith(start_prefix)]) == 0:
214
+ return False
215
+
216
+ # Some models explicitly do not support param buffer assignment
217
+ if not getattr(model_to_load, "_supports_param_buffer_assignment", True):
218
+ logger.debug(
219
+ f"{model_to_load.__class__.__name__} does not support param buffer assignment, loading will be slower"
220
+ )
221
+ return False
222
+
223
+ # If the model does, the incoming `state_dict` and the `model_to_load` must be the same dtype
224
+ first_key = next(iter(model_to_load.state_dict().keys()))
225
+ if start_prefix + first_key in state_dict:
226
+ return state_dict[start_prefix + first_key].dtype == model_to_load.state_dict()[first_key].dtype
227
+
228
+ return False
229
+
230
+
231
+ @contextmanager
232
+ def no_init_weights():
233
+ """
234
+ Context manager to globally disable weight initialization to speed up loading large models. To do that, all the
235
+ torch.nn.init function are all replaced with skip.
236
+ """
237
+
238
+ def _skip_init(*args, **kwargs):
239
+ pass
240
+
241
+ for name, init_func in TORCH_INIT_FUNCTIONS.items():
242
+ setattr(torch.nn.init, name, _skip_init)
243
+ try:
244
+ yield
245
+ finally:
246
+ # Restore the original initialization functions
247
+ for name, init_func in TORCH_INIT_FUNCTIONS.items():
248
+ setattr(torch.nn.init, name, init_func)
249
+
250
+
251
+ class ModelMixin(torch.nn.Module, PushToHubMixin):
252
+ r"""
253
+ Base class for all models.
254
+
255
+ [`ModelMixin`] takes care of storing the model configuration and provides methods for loading, downloading and
256
+ saving models.
257
+
258
+ - **config_name** ([`str`]) -- Filename to save a model to when calling [`~models.ModelMixin.save_pretrained`].
259
+ """
260
+
261
+ config_name = CONFIG_NAME
262
+ _automatically_saved_args = ["_diffusers_version", "_class_name", "_name_or_path"]
263
+ _supports_gradient_checkpointing = False
264
+ _keys_to_ignore_on_load_unexpected = None
265
+ _no_split_modules = None
266
+ _keep_in_fp32_modules = None
267
+ _skip_layerwise_casting_patterns = None
268
+ _supports_group_offloading = True
269
+
270
+ def __init__(self):
271
+ super().__init__()
272
+
273
+ self._gradient_checkpointing_func = None
274
+
275
+ def __getattr__(self, name: str) -> Any:
276
+ """The only reason we overwrite `getattr` here is to gracefully deprecate accessing
277
+ config attributes directly. See https://github.com/huggingface/diffusers/pull/3129 We need to overwrite
278
+ __getattr__ here in addition so that we don't trigger `torch.nn.Module`'s __getattr__':
279
+ https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
280
+ """
281
+
282
+ is_in_config = "_internal_dict" in self.__dict__ and hasattr(self.__dict__["_internal_dict"], name)
283
+ is_attribute = name in self.__dict__
284
+
285
+ if is_in_config and not is_attribute:
286
+ deprecation_message = f"Accessing config attribute `{name}` directly via '{type(self).__name__}' object attribute is deprecated. Please access '{name}' over '{type(self).__name__}'s config object instead, e.g. 'unet.config.{name}'."
287
+ deprecate("direct config name access", "1.0.0", deprecation_message, standard_warn=False, stacklevel=3)
288
+ return self._internal_dict[name]
289
+
290
+ # call PyTorch's https://pytorch.org/docs/stable/_modules/torch/nn/modules/module.html#Module
291
+ return super().__getattr__(name)
292
+
293
+ @property
294
+ def is_gradient_checkpointing(self) -> bool:
295
+ """
296
+ Whether gradient checkpointing is activated for this model or not.
297
+ """
298
+ return any(hasattr(m, "gradient_checkpointing") and m.gradient_checkpointing for m in self.modules())
299
+
300
+ def enable_gradient_checkpointing(self, gradient_checkpointing_func: Optional[Callable] = None) -> None:
301
+ """
302
+ Activates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
303
+ *checkpoint activations* in other frameworks).
304
+
305
+ Args:
306
+ gradient_checkpointing_func (`Callable`, *optional*):
307
+ The function to use for gradient checkpointing. If `None`, the default PyTorch checkpointing function
308
+ is used (`torch.utils.checkpoint.checkpoint`).
309
+ """
310
+ if not self._supports_gradient_checkpointing:
311
+ raise ValueError(
312
+ f"{self.__class__.__name__} does not support gradient checkpointing. Please make sure to set the boolean attribute "
313
+ f"`_supports_gradient_checkpointing` to `True` in the class definition."
314
+ )
315
+
316
+ if gradient_checkpointing_func is None:
317
+
318
+ def _gradient_checkpointing_func(module, *args):
319
+ ckpt_kwargs = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
320
+ return torch.utils.checkpoint.checkpoint(
321
+ module.__call__,
322
+ *args,
323
+ **ckpt_kwargs,
324
+ )
325
+
326
+ gradient_checkpointing_func = _gradient_checkpointing_func
327
+
328
+ self._set_gradient_checkpointing(enable=True, gradient_checkpointing_func=gradient_checkpointing_func)
329
+
330
+ def disable_gradient_checkpointing(self) -> None:
331
+ """
332
+ Deactivates gradient checkpointing for the current model (may be referred to as *activation checkpointing* or
333
+ *checkpoint activations* in other frameworks).
334
+ """
335
+ if self._supports_gradient_checkpointing:
336
+ self._set_gradient_checkpointing(enable=False)
337
+
338
+ def set_use_npu_flash_attention(self, valid: bool) -> None:
339
+ r"""
340
+ Set the switch for the npu flash attention.
341
+ """
342
+
343
+ def fn_recursive_set_npu_flash_attention(module: torch.nn.Module):
344
+ if hasattr(module, "set_use_npu_flash_attention"):
345
+ module.set_use_npu_flash_attention(valid)
346
+
347
+ for child in module.children():
348
+ fn_recursive_set_npu_flash_attention(child)
349
+
350
+ for module in self.children():
351
+ if isinstance(module, torch.nn.Module):
352
+ fn_recursive_set_npu_flash_attention(module)
353
+
354
+ def enable_npu_flash_attention(self) -> None:
355
+ r"""
356
+ Enable npu flash attention from torch_npu
357
+
358
+ """
359
+ self.set_use_npu_flash_attention(True)
360
+
361
+ def disable_npu_flash_attention(self) -> None:
362
+ r"""
363
+ disable npu flash attention from torch_npu
364
+
365
+ """
366
+ self.set_use_npu_flash_attention(False)
367
+
368
+ def set_use_xla_flash_attention(
369
+ self, use_xla_flash_attention: bool, partition_spec: Optional[Callable] = None, **kwargs
370
+ ) -> None:
371
+ # Recursively walk through all the children.
372
+ # Any children which exposes the set_use_xla_flash_attention method
373
+ # gets the message
374
+ def fn_recursive_set_flash_attention(module: torch.nn.Module):
375
+ if hasattr(module, "set_use_xla_flash_attention"):
376
+ module.set_use_xla_flash_attention(use_xla_flash_attention, partition_spec, **kwargs)
377
+
378
+ for child in module.children():
379
+ fn_recursive_set_flash_attention(child)
380
+
381
+ for module in self.children():
382
+ if isinstance(module, torch.nn.Module):
383
+ fn_recursive_set_flash_attention(module)
384
+
385
+ def enable_xla_flash_attention(self, partition_spec: Optional[Callable] = None, **kwargs):
386
+ r"""
387
+ Enable the flash attention pallals kernel for torch_xla.
388
+ """
389
+ self.set_use_xla_flash_attention(True, partition_spec, **kwargs)
390
+
391
+ def disable_xla_flash_attention(self):
392
+ r"""
393
+ Disable the flash attention pallals kernel for torch_xla.
394
+ """
395
+ self.set_use_xla_flash_attention(False)
396
+
397
+ def set_use_memory_efficient_attention_xformers(
398
+ self, valid: bool, attention_op: Optional[Callable] = None
399
+ ) -> None:
400
+ # Recursively walk through all the children.
401
+ # Any children which exposes the set_use_memory_efficient_attention_xformers method
402
+ # gets the message
403
+ def fn_recursive_set_mem_eff(module: torch.nn.Module):
404
+ if hasattr(module, "set_use_memory_efficient_attention_xformers"):
405
+ module.set_use_memory_efficient_attention_xformers(valid, attention_op)
406
+
407
+ for child in module.children():
408
+ fn_recursive_set_mem_eff(child)
409
+
410
+ for module in self.children():
411
+ if isinstance(module, torch.nn.Module):
412
+ fn_recursive_set_mem_eff(module)
413
+
414
+ def enable_xformers_memory_efficient_attention(self, attention_op: Optional[Callable] = None) -> None:
415
+ r"""
416
+ Enable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
417
+
418
+ When this option is enabled, you should observe lower GPU memory usage and a potential speed up during
419
+ inference. Speed up during training is not guaranteed.
420
+
421
+ <Tip warning={true}>
422
+
423
+ ⚠️ When memory efficient attention and sliced attention are both enabled, memory efficient attention takes
424
+ precedent.
425
+
426
+ </Tip>
427
+
428
+ Parameters:
429
+ attention_op (`Callable`, *optional*):
430
+ Override the default `None` operator for use as `op` argument to the
431
+ [`memory_efficient_attention()`](https://facebookresearch.github.io/xformers/components/ops.html#xformers.ops.memory_efficient_attention)
432
+ function of xFormers.
433
+
434
+ Examples:
435
+
436
+ ```py
437
+ >>> import torch
438
+ >>> from diffusers import UNet2DConditionModel
439
+ >>> from xformers.ops import MemoryEfficientAttentionFlashAttentionOp
440
+
441
+ >>> model = UNet2DConditionModel.from_pretrained(
442
+ ... "stabilityai/stable-diffusion-2-1", subfolder="unet", torch_dtype=torch.float16
443
+ ... )
444
+ >>> model = model.to("cuda")
445
+ >>> model.enable_xformers_memory_efficient_attention(attention_op=MemoryEfficientAttentionFlashAttentionOp)
446
+ ```
447
+ """
448
+ self.set_use_memory_efficient_attention_xformers(True, attention_op)
449
+
450
+ def disable_xformers_memory_efficient_attention(self) -> None:
451
+ r"""
452
+ Disable memory efficient attention from [xFormers](https://facebookresearch.github.io/xformers/).
453
+ """
454
+ self.set_use_memory_efficient_attention_xformers(False)
455
+
456
+ def enable_layerwise_casting(
457
+ self,
458
+ storage_dtype: torch.dtype = torch.float8_e4m3fn,
459
+ compute_dtype: Optional[torch.dtype] = None,
460
+ skip_modules_pattern: Optional[Tuple[str, ...]] = None,
461
+ skip_modules_classes: Optional[Tuple[Type[torch.nn.Module], ...]] = None,
462
+ non_blocking: bool = False,
463
+ ) -> None:
464
+ r"""
465
+ Activates layerwise casting for the current model.
466
+
467
+ Layerwise casting is a technique that casts the model weights to a lower precision dtype for storage but
468
+ upcasts them on-the-fly to a higher precision dtype for computation. This process can significantly reduce the
469
+ memory footprint from model weights, but may lead to some quality degradation in the outputs. Most degradations
470
+ are negligible, mostly stemming from weight casting in normalization and modulation layers.
471
+
472
+ By default, most models in diffusers set the `_skip_layerwise_casting_patterns` attribute to ignore patch
473
+ embedding, positional embedding and normalization layers. This is because these layers are most likely
474
+ precision-critical for quality. If you wish to change this behavior, you can set the
475
+ `_skip_layerwise_casting_patterns` attribute to `None`, or call
476
+ [`~hooks.layerwise_casting.apply_layerwise_casting`] with custom arguments.
477
+
478
+ Example:
479
+ Using [`~models.ModelMixin.enable_layerwise_casting`]:
480
+
481
+ ```python
482
+ >>> from diffusers import CogVideoXTransformer3DModel
483
+
484
+ >>> transformer = CogVideoXTransformer3DModel.from_pretrained(
485
+ ... "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
486
+ ... )
487
+
488
+ >>> # Enable layerwise casting via the model, which ignores certain modules by default
489
+ >>> transformer.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)
490
+ ```
491
+
492
+ Args:
493
+ storage_dtype (`torch.dtype`):
494
+ The dtype to which the model should be cast for storage.
495
+ compute_dtype (`torch.dtype`):
496
+ The dtype to which the model weights should be cast during the forward pass.
497
+ skip_modules_pattern (`Tuple[str, ...]`, *optional*):
498
+ A list of patterns to match the names of the modules to skip during the layerwise casting process. If
499
+ set to `None`, default skip patterns are used to ignore certain internal layers of modules and PEFT
500
+ layers.
501
+ skip_modules_classes (`Tuple[Type[torch.nn.Module], ...]`, *optional*):
502
+ A list of module classes to skip during the layerwise casting process.
503
+ non_blocking (`bool`, *optional*, defaults to `False`):
504
+ If `True`, the weight casting operations are non-blocking.
505
+ """
506
+ from ..hooks import apply_layerwise_casting
507
+
508
+ user_provided_patterns = True
509
+ if skip_modules_pattern is None:
510
+ from ..hooks.layerwise_casting import DEFAULT_SKIP_MODULES_PATTERN
511
+
512
+ skip_modules_pattern = DEFAULT_SKIP_MODULES_PATTERN
513
+ user_provided_patterns = False
514
+ if self._keep_in_fp32_modules is not None:
515
+ skip_modules_pattern += tuple(self._keep_in_fp32_modules)
516
+ if self._skip_layerwise_casting_patterns is not None:
517
+ skip_modules_pattern += tuple(self._skip_layerwise_casting_patterns)
518
+ skip_modules_pattern = tuple(set(skip_modules_pattern))
519
+
520
+ if is_peft_available() and not user_provided_patterns:
521
+ # By default, we want to skip all peft layers because they have a very low memory footprint.
522
+ # If users want to apply layerwise casting on peft layers as well, they can utilize the
523
+ # `~diffusers.hooks.layerwise_casting.apply_layerwise_casting` function which provides
524
+ # them with more flexibility and control.
525
+
526
+ from peft.tuners.loha.layer import LoHaLayer
527
+ from peft.tuners.lokr.layer import LoKrLayer
528
+ from peft.tuners.lora.layer import LoraLayer
529
+
530
+ for layer in (LoHaLayer, LoKrLayer, LoraLayer):
531
+ skip_modules_pattern += tuple(layer.adapter_layer_names)
532
+
533
+ if compute_dtype is None:
534
+ logger.info("`compute_dtype` not provided when enabling layerwise casting. Using dtype of the model.")
535
+ compute_dtype = self.dtype
536
+
537
+ apply_layerwise_casting(
538
+ self, storage_dtype, compute_dtype, skip_modules_pattern, skip_modules_classes, non_blocking
539
+ )
540
+
541
+ def enable_group_offload(
542
+ self,
543
+ onload_device: torch.device,
544
+ offload_device: torch.device = torch.device("cpu"),
545
+ offload_type: str = "block_level",
546
+ num_blocks_per_group: Optional[int] = None,
547
+ non_blocking: bool = False,
548
+ use_stream: bool = False,
549
+ record_stream: bool = False,
550
+ low_cpu_mem_usage=False,
551
+ ) -> None:
552
+ r"""
553
+ Activates group offloading for the current model.
554
+
555
+ See [`~hooks.group_offloading.apply_group_offloading`] for more information.
556
+
557
+ Example:
558
+
559
+ ```python
560
+ >>> from diffusers import CogVideoXTransformer3DModel
561
+
562
+ >>> transformer = CogVideoXTransformer3DModel.from_pretrained(
563
+ ... "THUDM/CogVideoX-5b", subfolder="transformer", torch_dtype=torch.bfloat16
564
+ ... )
565
+
566
+ >>> transformer.enable_group_offload(
567
+ ... onload_device=torch.device("cuda"),
568
+ ... offload_device=torch.device("cpu"),
569
+ ... offload_type="leaf_level",
570
+ ... use_stream=True,
571
+ ... )
572
+ ```
573
+ """
574
+ from ..hooks import apply_group_offloading
575
+
576
+ if getattr(self, "enable_tiling", None) is not None and getattr(self, "use_tiling", False) and use_stream:
577
+ msg = (
578
+ "Applying group offloading on autoencoders, with CUDA streams, may not work as expected if the first "
579
+ "forward pass is executed with tiling enabled. Please make sure to either:\n"
580
+ "1. Run a forward pass with small input shapes.\n"
581
+ "2. Or, run a forward pass with tiling disabled (can still use small dummy inputs)."
582
+ )
583
+ logger.warning(msg)
584
+ if not self._supports_group_offloading:
585
+ raise ValueError(
586
+ f"{self.__class__.__name__} does not support group offloading. Please make sure to set the boolean attribute "
587
+ f"`_supports_group_offloading` to `True` in the class definition. If you believe this is a mistake, please "
588
+ f"open an issue at https://github.com/huggingface/diffusers/issues."
589
+ )
590
+ apply_group_offloading(
591
+ self,
592
+ onload_device,
593
+ offload_device,
594
+ offload_type,
595
+ num_blocks_per_group,
596
+ non_blocking,
597
+ use_stream,
598
+ record_stream,
599
+ low_cpu_mem_usage=low_cpu_mem_usage,
600
+ )
601
+
602
+ def save_pretrained(
603
+ self,
604
+ save_directory: Union[str, os.PathLike],
605
+ is_main_process: bool = True,
606
+ save_function: Optional[Callable] = None,
607
+ safe_serialization: bool = True,
608
+ variant: Optional[str] = None,
609
+ max_shard_size: Union[int, str] = "10GB",
610
+ push_to_hub: bool = False,
611
+ **kwargs,
612
+ ):
613
+ """
614
+ Save a model and its configuration file to a directory so that it can be reloaded using the
615
+ [`~models.ModelMixin.from_pretrained`] class method.
616
+
617
+ Arguments:
618
+ save_directory (`str` or `os.PathLike`):
619
+ Directory to save a model and its configuration file to. Will be created if it doesn't exist.
620
+ is_main_process (`bool`, *optional*, defaults to `True`):
621
+ Whether the process calling this is the main process or not. Useful during distributed training and you
622
+ need to call this function on all processes. In this case, set `is_main_process=True` only on the main
623
+ process to avoid race conditions.
624
+ save_function (`Callable`):
625
+ The function to use to save the state dictionary. Useful during distributed training when you need to
626
+ replace `torch.save` with another method. Can be configured with the environment variable
627
+ `DIFFUSERS_SAVE_MODE`.
628
+ safe_serialization (`bool`, *optional*, defaults to `True`):
629
+ Whether to save the model using `safetensors` or the traditional PyTorch way with `pickle`.
630
+ variant (`str`, *optional*):
631
+ If specified, weights are saved in the format `pytorch_model.<variant>.bin`.
632
+ max_shard_size (`int` or `str`, defaults to `"10GB"`):
633
+ The maximum size for a checkpoint before being sharded. Checkpoints shard will then be each of size
634
+ lower than this size. If expressed as a string, needs to be digits followed by a unit (like `"5GB"`).
635
+ If expressed as an integer, the unit is bytes. Note that this limit will be decreased after a certain
636
+ period of time (starting from Oct 2024) to allow users to upgrade to the latest version of `diffusers`.
637
+ This is to establish a common default size for this argument across different libraries in the Hugging
638
+ Face ecosystem (`transformers`, and `accelerate`, for example).
639
+ push_to_hub (`bool`, *optional*, defaults to `False`):
640
+ Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
641
+ repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
642
+ namespace).
643
+ kwargs (`Dict[str, Any]`, *optional*):
644
+ Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
645
+ """
646
+ if os.path.isfile(save_directory):
647
+ logger.error(f"Provided path ({save_directory}) should be a directory, not a file")
648
+ return
649
+
650
+ hf_quantizer = getattr(self, "hf_quantizer", None)
651
+ if hf_quantizer is not None:
652
+ quantization_serializable = (
653
+ hf_quantizer is not None
654
+ and isinstance(hf_quantizer, DiffusersQuantizer)
655
+ and hf_quantizer.is_serializable
656
+ )
657
+ if not quantization_serializable:
658
+ raise ValueError(
659
+ f"The model is quantized with {hf_quantizer.quantization_config.quant_method} and is not serializable - check out the warnings from"
660
+ " the logger on the traceback to understand the reason why the quantized model is not serializable."
661
+ )
662
+
663
+ weights_name = SAFETENSORS_WEIGHTS_NAME if safe_serialization else WEIGHTS_NAME
664
+ weights_name = _add_variant(weights_name, variant)
665
+ weights_name_pattern = weights_name.replace(".bin", "{suffix}.bin").replace(
666
+ ".safetensors", "{suffix}.safetensors"
667
+ )
668
+
669
+ os.makedirs(save_directory, exist_ok=True)
670
+
671
+ if push_to_hub:
672
+ commit_message = kwargs.pop("commit_message", None)
673
+ private = kwargs.pop("private", None)
674
+ create_pr = kwargs.pop("create_pr", False)
675
+ token = kwargs.pop("token", None)
676
+ repo_id = kwargs.pop("repo_id", save_directory.split(os.path.sep)[-1])
677
+ repo_id = create_repo(repo_id, exist_ok=True, private=private, token=token).repo_id
678
+
679
+ # Only save the model itself if we are using distributed training
680
+ model_to_save = self
681
+
682
+ # Attach architecture to the config
683
+ # Save the config
684
+ if is_main_process:
685
+ model_to_save.save_config(save_directory)
686
+
687
+ # Save the model
688
+ state_dict = model_to_save.state_dict()
689
+
690
+ # Save the model
691
+ state_dict_split = split_torch_state_dict_into_shards(
692
+ state_dict, max_shard_size=max_shard_size, filename_pattern=weights_name_pattern
693
+ )
694
+
695
+ # Clean the folder from a previous save
696
+ if is_main_process:
697
+ for filename in os.listdir(save_directory):
698
+ if filename in state_dict_split.filename_to_tensors.keys():
699
+ continue
700
+ full_filename = os.path.join(save_directory, filename)
701
+ if not os.path.isfile(full_filename):
702
+ continue
703
+ weights_without_ext = weights_name_pattern.replace(".bin", "").replace(".safetensors", "")
704
+ weights_without_ext = weights_without_ext.replace("{suffix}", "")
705
+ filename_without_ext = filename.replace(".bin", "").replace(".safetensors", "")
706
+ # make sure that file to be deleted matches format of sharded file, e.g. pytorch_model-00001-of-00005
707
+ if (
708
+ filename.startswith(weights_without_ext)
709
+ and _REGEX_SHARD.fullmatch(filename_without_ext) is not None
710
+ ):
711
+ os.remove(full_filename)
712
+
713
+ for filename, tensors in state_dict_split.filename_to_tensors.items():
714
+ shard = {tensor: state_dict[tensor].contiguous() for tensor in tensors}
715
+ filepath = os.path.join(save_directory, filename)
716
+ if safe_serialization:
717
+ # At some point we will need to deal better with save_function (used for TPU and other distributed
718
+ # joyfulness), but for now this enough.
719
+ safetensors.torch.save_file(shard, filepath, metadata={"format": "pt"})
720
+ else:
721
+ torch.save(shard, filepath)
722
+
723
+ if state_dict_split.is_sharded:
724
+ index = {
725
+ "metadata": state_dict_split.metadata,
726
+ "weight_map": state_dict_split.tensor_to_filename,
727
+ }
728
+ save_index_file = SAFE_WEIGHTS_INDEX_NAME if safe_serialization else WEIGHTS_INDEX_NAME
729
+ save_index_file = os.path.join(save_directory, _add_variant(save_index_file, variant))
730
+ # Save the index as well
731
+ with open(save_index_file, "w", encoding="utf-8") as f:
732
+ content = json.dumps(index, indent=2, sort_keys=True) + "\n"
733
+ f.write(content)
734
+ logger.info(
735
+ f"The model is bigger than the maximum size per checkpoint ({max_shard_size}) and is going to be "
736
+ f"split in {len(state_dict_split.filename_to_tensors)} checkpoint shards. You can find where each parameters has been saved in the "
737
+ f"index located at {save_index_file}."
738
+ )
739
+ else:
740
+ path_to_weights = os.path.join(save_directory, weights_name)
741
+ logger.info(f"Model weights saved in {path_to_weights}")
742
+
743
+ if push_to_hub:
744
+ # Create a new empty model card and eventually tag it
745
+ model_card = load_or_create_model_card(repo_id, token=token)
746
+ model_card = populate_model_card(model_card)
747
+ model_card.save(Path(save_directory, "README.md").as_posix())
748
+
749
+ self._upload_folder(
750
+ save_directory,
751
+ repo_id,
752
+ token=token,
753
+ commit_message=commit_message,
754
+ create_pr=create_pr,
755
+ )
756
+
757
+ def dequantize(self):
758
+ """
759
+ Potentially dequantize the model in case it has been quantized by a quantization method that support
760
+ dequantization.
761
+ """
762
+ hf_quantizer = getattr(self, "hf_quantizer", None)
763
+
764
+ if hf_quantizer is None:
765
+ raise ValueError("You need to first quantize your model in order to dequantize it")
766
+
767
+ return hf_quantizer.dequantize(self)
768
+
769
+ @classmethod
770
+ @validate_hf_hub_args
771
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs) -> Self:
772
+ r"""
773
+ Instantiate a pretrained PyTorch model from a pretrained model configuration.
774
+
775
+ The model is set in evaluation mode - `model.eval()` - by default, and dropout modules are deactivated. To
776
+ train the model, set it back in training mode with `model.train()`.
777
+
778
+ Parameters:
779
+ pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
780
+ Can be either:
781
+
782
+ - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
783
+ the Hub.
784
+ - A path to a *directory* (for example `./my_model_directory`) containing the model weights saved
785
+ with [`~ModelMixin.save_pretrained`].
786
+
787
+ cache_dir (`Union[str, os.PathLike]`, *optional*):
788
+ Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
789
+ is not used.
790
+ torch_dtype (`str` or `torch.dtype`, *optional*):
791
+ Override the default `torch.dtype` and load the model with another dtype. If `"auto"` is passed, the
792
+ dtype is automatically derived from the model's weights.
793
+ force_download (`bool`, *optional*, defaults to `False`):
794
+ Whether or not to force the (re-)download of the model weights and configuration files, overriding the
795
+ cached versions if they exist.
796
+ proxies (`Dict[str, str]`, *optional*):
797
+ A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
798
+ 'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
799
+ output_loading_info (`bool`, *optional*, defaults to `False`):
800
+ Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
801
+ local_files_only(`bool`, *optional*, defaults to `False`):
802
+ Whether to only load local model weights and configuration files or not. If set to `True`, the model
803
+ won't be downloaded from the Hub.
804
+ token (`str` or *bool*, *optional*):
805
+ The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
806
+ `diffusers-cli login` (stored in `~/.huggingface`) is used.
807
+ revision (`str`, *optional*, defaults to `"main"`):
808
+ The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
809
+ allowed by Git.
810
+ from_flax (`bool`, *optional*, defaults to `False`):
811
+ Load the model weights from a Flax checkpoint save file.
812
+ subfolder (`str`, *optional*, defaults to `""`):
813
+ The subfolder location of a model file within a larger model repository on the Hub or locally.
814
+ mirror (`str`, *optional*):
815
+ Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
816
+ guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
817
+ information.
818
+ device_map (`str` or `Dict[str, Union[int, str, torch.device]]`, *optional*):
819
+ A map that specifies where each submodule should go. It doesn't need to be defined for each
820
+ parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
821
+ same device. Defaults to `None`, meaning that the model will be loaded on CPU.
822
+
823
+ Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
824
+ more information about each option see [designing a device
825
+ map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
826
+ max_memory (`Dict`, *optional*):
827
+ A dictionary device identifier for the maximum memory. Will default to the maximum memory available for
828
+ each GPU and the available CPU RAM if unset.
829
+ offload_folder (`str` or `os.PathLike`, *optional*):
830
+ The path to offload weights if `device_map` contains the value `"disk"`.
831
+ offload_state_dict (`bool`, *optional*):
832
+ If `True`, temporarily offloads the CPU state dict to the hard drive to avoid running out of CPU RAM if
833
+ the weight of the CPU state dict + the biggest shard of the checkpoint does not fit. Defaults to `True`
834
+ when there is some disk offload.
835
+ low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
836
+ Speed up model loading only loading the pretrained weights and not initializing the weights. This also
837
+ tries to not use more than 1x model size in CPU memory (including peak memory) while loading the model.
838
+ Only supported for PyTorch >= 1.9.0. If you are using an older version of PyTorch, setting this
839
+ argument to `True` will raise an error.
840
+ variant (`str`, *optional*):
841
+ Load weights from a specified `variant` filename such as `"fp16"` or `"ema"`. This is ignored when
842
+ loading `from_flax`.
843
+ use_safetensors (`bool`, *optional*, defaults to `None`):
844
+ If set to `None`, the `safetensors` weights are downloaded if they're available **and** if the
845
+ `safetensors` library is installed. If set to `True`, the model is forcibly loaded from `safetensors`
846
+ weights. If set to `False`, `safetensors` weights are not loaded.
847
+ disable_mmap ('bool', *optional*, defaults to 'False'):
848
+ Whether to disable mmap when loading a Safetensors model. This option can perform better when the model
849
+ is on a network mount or hard drive, which may not handle the seeky-ness of mmap very well.
850
+
851
+ <Tip>
852
+
853
+ To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in with
854
+ `huggingface-cli login`. You can also activate the special
855
+ ["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a
856
+ firewalled environment.
857
+
858
+ </Tip>
859
+
860
+ Example:
861
+
862
+ ```py
863
+ from diffusers import UNet2DConditionModel
864
+
865
+ unet = UNet2DConditionModel.from_pretrained("runwayml/stable-diffusion-v1-5", subfolder="unet")
866
+ ```
867
+
868
+ If you get the error message below, you need to finetune the weights for your downstream task:
869
+
870
+ ```bash
871
+ Some weights of UNet2DConditionModel were not initialized from the model checkpoint at runwayml/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
872
+ - conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in the model instantiated
873
+ You should probably TRAIN this model on a down-stream task to be able to use it for predictions and inference.
874
+ ```
875
+ """
876
+ cache_dir = kwargs.pop("cache_dir", None)
877
+ ignore_mismatched_sizes = kwargs.pop("ignore_mismatched_sizes", False)
878
+ force_download = kwargs.pop("force_download", False)
879
+ from_flax = kwargs.pop("from_flax", False)
880
+ proxies = kwargs.pop("proxies", None)
881
+ output_loading_info = kwargs.pop("output_loading_info", False)
882
+ local_files_only = kwargs.pop("local_files_only", None)
883
+ token = kwargs.pop("token", None)
884
+ revision = kwargs.pop("revision", None)
885
+ torch_dtype = kwargs.pop("torch_dtype", None)
886
+ subfolder = kwargs.pop("subfolder", None)
887
+ device_map = kwargs.pop("device_map", None)
888
+ max_memory = kwargs.pop("max_memory", None)
889
+ offload_folder = kwargs.pop("offload_folder", None)
890
+ offload_state_dict = kwargs.pop("offload_state_dict", None)
891
+ low_cpu_mem_usage = kwargs.pop("low_cpu_mem_usage", _LOW_CPU_MEM_USAGE_DEFAULT)
892
+ variant = kwargs.pop("variant", None)
893
+ use_safetensors = kwargs.pop("use_safetensors", None)
894
+ quantization_config = kwargs.pop("quantization_config", None)
895
+ dduf_entries: Optional[Dict[str, DDUFEntry]] = kwargs.pop("dduf_entries", None)
896
+ disable_mmap = kwargs.pop("disable_mmap", False)
897
+
898
+ if torch_dtype is not None and not isinstance(torch_dtype, torch.dtype):
899
+ torch_dtype = torch.float32
900
+ logger.warning(
901
+ f"Passed `torch_dtype` {torch_dtype} is not a `torch.dtype`. Defaulting to `torch.float32`."
902
+ )
903
+
904
+ allow_pickle = False
905
+ if use_safetensors is None:
906
+ use_safetensors = True
907
+ allow_pickle = True
908
+
909
+ if low_cpu_mem_usage and not is_accelerate_available():
910
+ low_cpu_mem_usage = False
911
+ logger.warning(
912
+ "Cannot initialize model with low cpu memory usage because `accelerate` was not found in the"
913
+ " environment. Defaulting to `low_cpu_mem_usage=False`. It is strongly recommended to install"
914
+ " `accelerate` for faster and less memory-intense model loading. You can do so with: \n```\npip"
915
+ " install accelerate\n```\n."
916
+ )
917
+
918
+ if device_map is not None and not is_accelerate_available():
919
+ raise NotImplementedError(
920
+ "Loading and dispatching requires `accelerate`. Please make sure to install accelerate or set"
921
+ " `device_map=None`. You can install accelerate with `pip install accelerate`."
922
+ )
923
+
924
+ # Check if we can handle device_map and dispatching the weights
925
+ if device_map is not None and not is_torch_version(">=", "1.9.0"):
926
+ raise NotImplementedError(
927
+ "Loading and dispatching requires torch >= 1.9.0. Please either update your PyTorch version or set"
928
+ " `device_map=None`."
929
+ )
930
+
931
+ if low_cpu_mem_usage is True and not is_torch_version(">=", "1.9.0"):
932
+ raise NotImplementedError(
933
+ "Low memory initialization requires torch >= 1.9.0. Please either update your PyTorch version or set"
934
+ " `low_cpu_mem_usage=False`."
935
+ )
936
+
937
+ if low_cpu_mem_usage is False and device_map is not None:
938
+ raise ValueError(
939
+ f"You cannot set `low_cpu_mem_usage` to `False` while using device_map={device_map} for loading and"
940
+ " dispatching. Please make sure to set `low_cpu_mem_usage=True`."
941
+ )
942
+
943
+ # change device_map into a map if we passed an int, a str or a torch.device
944
+ if isinstance(device_map, torch.device):
945
+ device_map = {"": device_map}
946
+ elif isinstance(device_map, str) and device_map not in ["auto", "balanced", "balanced_low_0", "sequential"]:
947
+ try:
948
+ device_map = {"": torch.device(device_map)}
949
+ except RuntimeError:
950
+ raise ValueError(
951
+ "When passing device_map as a string, the value needs to be a device name (e.g. cpu, cuda:0) or "
952
+ f"'auto', 'balanced', 'balanced_low_0', 'sequential' but found {device_map}."
953
+ )
954
+ elif isinstance(device_map, int):
955
+ if device_map < 0:
956
+ raise ValueError(
957
+ "You can't pass device_map as a negative int. If you want to put the model on the cpu, pass device_map = 'cpu' "
958
+ )
959
+ else:
960
+ device_map = {"": device_map}
961
+
962
+ if device_map is not None:
963
+ if low_cpu_mem_usage is None:
964
+ low_cpu_mem_usage = True
965
+ elif not low_cpu_mem_usage:
966
+ raise ValueError("Passing along a `device_map` requires `low_cpu_mem_usage=True`")
967
+
968
+ if low_cpu_mem_usage:
969
+ if device_map is not None and not is_torch_version(">=", "1.10"):
970
+ # The max memory utils require PyTorch >= 1.10 to have torch.cuda.mem_get_info.
971
+ raise ValueError("`low_cpu_mem_usage` and `device_map` require PyTorch >= 1.10.")
972
+
973
+ user_agent = {
974
+ "diffusers": __version__,
975
+ "file_type": "model",
976
+ "framework": "pytorch",
977
+ }
978
+ unused_kwargs = {}
979
+
980
+ # Load config if we don't provide a configuration
981
+ config_path = pretrained_model_name_or_path
982
+
983
+ # load config
984
+ config, unused_kwargs, commit_hash = cls.load_config(
985
+ config_path,
986
+ cache_dir=cache_dir,
987
+ return_unused_kwargs=True,
988
+ return_commit_hash=True,
989
+ force_download=force_download,
990
+ proxies=proxies,
991
+ local_files_only=local_files_only,
992
+ token=token,
993
+ revision=revision,
994
+ subfolder=subfolder,
995
+ user_agent=user_agent,
996
+ dduf_entries=dduf_entries,
997
+ **kwargs,
998
+ )
999
+ # no in-place modification of the original config.
1000
+ config = copy.deepcopy(config)
1001
+
1002
+ # determine initial quantization config.
1003
+ #######################################
1004
+ pre_quantized = "quantization_config" in config and config["quantization_config"] is not None
1005
+ if pre_quantized or quantization_config is not None:
1006
+ if pre_quantized:
1007
+ config["quantization_config"] = DiffusersAutoQuantizer.merge_quantization_configs(
1008
+ config["quantization_config"], quantization_config
1009
+ )
1010
+ else:
1011
+ config["quantization_config"] = quantization_config
1012
+ hf_quantizer = DiffusersAutoQuantizer.from_config(
1013
+ config["quantization_config"], pre_quantized=pre_quantized
1014
+ )
1015
+ else:
1016
+ hf_quantizer = None
1017
+
1018
+ if hf_quantizer is not None:
1019
+ hf_quantizer.validate_environment(torch_dtype=torch_dtype, from_flax=from_flax, device_map=device_map)
1020
+ torch_dtype = hf_quantizer.update_torch_dtype(torch_dtype)
1021
+ device_map = hf_quantizer.update_device_map(device_map)
1022
+
1023
+ # In order to ensure popular quantization methods are supported. Can be disable with `disable_telemetry`
1024
+ user_agent["quant"] = hf_quantizer.quantization_config.quant_method.value
1025
+
1026
+ # Force-set to `True` for more mem efficiency
1027
+ if low_cpu_mem_usage is None:
1028
+ low_cpu_mem_usage = True
1029
+ logger.info("Set `low_cpu_mem_usage` to True as `hf_quantizer` is not None.")
1030
+ elif not low_cpu_mem_usage:
1031
+ raise ValueError("`low_cpu_mem_usage` cannot be False or None when using quantization.")
1032
+
1033
+ # Check if `_keep_in_fp32_modules` is not None
1034
+ use_keep_in_fp32_modules = cls._keep_in_fp32_modules is not None and (
1035
+ hf_quantizer is None or getattr(hf_quantizer, "use_keep_in_fp32_modules", False)
1036
+ )
1037
+
1038
+ if use_keep_in_fp32_modules:
1039
+ keep_in_fp32_modules = cls._keep_in_fp32_modules
1040
+ if not isinstance(keep_in_fp32_modules, list):
1041
+ keep_in_fp32_modules = [keep_in_fp32_modules]
1042
+
1043
+ if low_cpu_mem_usage is None:
1044
+ low_cpu_mem_usage = True
1045
+ logger.info("Set `low_cpu_mem_usage` to True as `_keep_in_fp32_modules` is not None.")
1046
+ elif not low_cpu_mem_usage:
1047
+ raise ValueError("`low_cpu_mem_usage` cannot be False when `keep_in_fp32_modules` is True.")
1048
+ else:
1049
+ keep_in_fp32_modules = []
1050
+
1051
+ is_sharded = False
1052
+ resolved_model_file = None
1053
+
1054
+ # Determine if we're loading from a directory of sharded checkpoints.
1055
+ sharded_metadata = None
1056
+ index_file = None
1057
+ is_local = os.path.isdir(pretrained_model_name_or_path)
1058
+ index_file_kwargs = {
1059
+ "is_local": is_local,
1060
+ "pretrained_model_name_or_path": pretrained_model_name_or_path,
1061
+ "subfolder": subfolder or "",
1062
+ "use_safetensors": use_safetensors,
1063
+ "cache_dir": cache_dir,
1064
+ "variant": variant,
1065
+ "force_download": force_download,
1066
+ "proxies": proxies,
1067
+ "local_files_only": local_files_only,
1068
+ "token": token,
1069
+ "revision": revision,
1070
+ "user_agent": user_agent,
1071
+ "commit_hash": commit_hash,
1072
+ "dduf_entries": dduf_entries,
1073
+ }
1074
+ index_file = _fetch_index_file(**index_file_kwargs)
1075
+ # In case the index file was not found we still have to consider the legacy format.
1076
+ # this becomes applicable when the variant is not None.
1077
+ if variant is not None and (index_file is None or not os.path.exists(index_file)):
1078
+ index_file = _fetch_index_file_legacy(**index_file_kwargs)
1079
+ if index_file is not None and (dduf_entries or index_file.is_file()):
1080
+ is_sharded = True
1081
+
1082
+ if is_sharded and from_flax:
1083
+ raise ValueError("Loading of sharded checkpoints is not supported when `from_flax=True`.")
1084
+
1085
+ # load model
1086
+ if from_flax:
1087
+ resolved_model_file = _get_model_file(
1088
+ pretrained_model_name_or_path,
1089
+ weights_name=FLAX_WEIGHTS_NAME,
1090
+ cache_dir=cache_dir,
1091
+ force_download=force_download,
1092
+ proxies=proxies,
1093
+ local_files_only=local_files_only,
1094
+ token=token,
1095
+ revision=revision,
1096
+ subfolder=subfolder,
1097
+ user_agent=user_agent,
1098
+ commit_hash=commit_hash,
1099
+ )
1100
+ model = cls.from_config(config, **unused_kwargs)
1101
+
1102
+ # Convert the weights
1103
+ from .modeling_pytorch_flax_utils import load_flax_checkpoint_in_pytorch_model
1104
+
1105
+ model = load_flax_checkpoint_in_pytorch_model(model, resolved_model_file)
1106
+ else:
1107
+ # in the case it is sharded, we have already the index
1108
+ if is_sharded:
1109
+ resolved_model_file, sharded_metadata = _get_checkpoint_shard_files(
1110
+ pretrained_model_name_or_path,
1111
+ index_file,
1112
+ cache_dir=cache_dir,
1113
+ proxies=proxies,
1114
+ local_files_only=local_files_only,
1115
+ token=token,
1116
+ user_agent=user_agent,
1117
+ revision=revision,
1118
+ subfolder=subfolder or "",
1119
+ dduf_entries=dduf_entries,
1120
+ )
1121
+ elif use_safetensors:
1122
+ try:
1123
+ resolved_model_file = _get_model_file(
1124
+ pretrained_model_name_or_path,
1125
+ weights_name=_add_variant(SAFETENSORS_WEIGHTS_NAME, variant),
1126
+ cache_dir=cache_dir,
1127
+ force_download=force_download,
1128
+ proxies=proxies,
1129
+ local_files_only=local_files_only,
1130
+ token=token,
1131
+ revision=revision,
1132
+ subfolder=subfolder,
1133
+ user_agent=user_agent,
1134
+ commit_hash=commit_hash,
1135
+ dduf_entries=dduf_entries,
1136
+ )
1137
+
1138
+ except IOError as e:
1139
+ logger.error(f"An error occurred while trying to fetch {pretrained_model_name_or_path}: {e}")
1140
+ if not allow_pickle:
1141
+ raise
1142
+ logger.warning(
1143
+ "Defaulting to unsafe serialization. Pass `allow_pickle=False` to raise an error instead."
1144
+ )
1145
+
1146
+ if resolved_model_file is None and not is_sharded:
1147
+ resolved_model_file = _get_model_file(
1148
+ pretrained_model_name_or_path,
1149
+ weights_name=_add_variant(WEIGHTS_NAME, variant),
1150
+ cache_dir=cache_dir,
1151
+ force_download=force_download,
1152
+ proxies=proxies,
1153
+ local_files_only=local_files_only,
1154
+ token=token,
1155
+ revision=revision,
1156
+ subfolder=subfolder,
1157
+ user_agent=user_agent,
1158
+ commit_hash=commit_hash,
1159
+ dduf_entries=dduf_entries,
1160
+ )
1161
+
1162
+ if not isinstance(resolved_model_file, list):
1163
+ resolved_model_file = [resolved_model_file]
1164
+
1165
+ # set dtype to instantiate the model under:
1166
+ # 1. If torch_dtype is not None, we use that dtype
1167
+ # 2. If torch_dtype is float8, we don't use _set_default_torch_dtype and we downcast after loading the model
1168
+ dtype_orig = None
1169
+ if torch_dtype is not None and not torch_dtype == getattr(torch, "float8_e4m3fn", None):
1170
+ if not isinstance(torch_dtype, torch.dtype):
1171
+ raise ValueError(
1172
+ f"{torch_dtype} needs to be of type `torch.dtype`, e.g. `torch.float16`, but is {type(torch_dtype)}."
1173
+ )
1174
+ dtype_orig = cls._set_default_torch_dtype(torch_dtype)
1175
+
1176
+ init_contexts = [no_init_weights()]
1177
+
1178
+ if low_cpu_mem_usage:
1179
+ init_contexts.append(accelerate.init_empty_weights())
1180
+
1181
+ with ContextManagers(init_contexts):
1182
+ model = cls.from_config(config, **unused_kwargs)
1183
+
1184
+ if dtype_orig is not None:
1185
+ torch.set_default_dtype(dtype_orig)
1186
+
1187
+ state_dict = None
1188
+ if not is_sharded:
1189
+ # Time to load the checkpoint
1190
+ state_dict = load_state_dict(resolved_model_file[0], disable_mmap=disable_mmap, dduf_entries=dduf_entries)
1191
+ # We only fix it for non sharded checkpoints as we don't need it yet for sharded one.
1192
+ model._fix_state_dict_keys_on_load(state_dict)
1193
+
1194
+ if is_sharded:
1195
+ loaded_keys = sharded_metadata["all_checkpoint_keys"]
1196
+ else:
1197
+ loaded_keys = list(state_dict.keys())
1198
+
1199
+ if hf_quantizer is not None:
1200
+ hf_quantizer.preprocess_model(
1201
+ model=model, device_map=device_map, keep_in_fp32_modules=keep_in_fp32_modules
1202
+ )
1203
+
1204
+ # Now that the model is loaded, we can determine the device_map
1205
+ device_map = _determine_device_map(
1206
+ model, device_map, max_memory, torch_dtype, keep_in_fp32_modules, hf_quantizer
1207
+ )
1208
+ if hf_quantizer is not None:
1209
+ hf_quantizer.validate_environment(device_map=device_map)
1210
+
1211
+ (
1212
+ model,
1213
+ missing_keys,
1214
+ unexpected_keys,
1215
+ mismatched_keys,
1216
+ offload_index,
1217
+ error_msgs,
1218
+ ) = cls._load_pretrained_model(
1219
+ model,
1220
+ state_dict,
1221
+ resolved_model_file,
1222
+ pretrained_model_name_or_path,
1223
+ loaded_keys,
1224
+ ignore_mismatched_sizes=ignore_mismatched_sizes,
1225
+ low_cpu_mem_usage=low_cpu_mem_usage,
1226
+ device_map=device_map,
1227
+ offload_folder=offload_folder,
1228
+ offload_state_dict=offload_state_dict,
1229
+ dtype=torch_dtype,
1230
+ hf_quantizer=hf_quantizer,
1231
+ keep_in_fp32_modules=keep_in_fp32_modules,
1232
+ dduf_entries=dduf_entries,
1233
+ )
1234
+ loading_info = {
1235
+ "missing_keys": missing_keys,
1236
+ "unexpected_keys": unexpected_keys,
1237
+ "mismatched_keys": mismatched_keys,
1238
+ "error_msgs": error_msgs,
1239
+ }
1240
+
1241
+ # Dispatch model with hooks on all devices if necessary
1242
+ if device_map is not None:
1243
+ device_map_kwargs = {
1244
+ "device_map": device_map,
1245
+ "offload_dir": offload_folder,
1246
+ "offload_index": offload_index,
1247
+ }
1248
+ dispatch_model(model, **device_map_kwargs)
1249
+
1250
+ if hf_quantizer is not None:
1251
+ hf_quantizer.postprocess_model(model)
1252
+ model.hf_quantizer = hf_quantizer
1253
+
1254
+ if (
1255
+ torch_dtype is not None
1256
+ and torch_dtype == getattr(torch, "float8_e4m3fn", None)
1257
+ and hf_quantizer is None
1258
+ and not use_keep_in_fp32_modules
1259
+ ):
1260
+ model = model.to(torch_dtype)
1261
+
1262
+ if hf_quantizer is not None:
1263
+ # We also make sure to purge `_pre_quantization_dtype` when we serialize
1264
+ # the model config because `_pre_quantization_dtype` is `torch.dtype`, not JSON serializable.
1265
+ model.register_to_config(_name_or_path=pretrained_model_name_or_path, _pre_quantization_dtype=torch_dtype)
1266
+ else:
1267
+ model.register_to_config(_name_or_path=pretrained_model_name_or_path)
1268
+
1269
+ # Set model in evaluation mode to deactivate DropOut modules by default
1270
+ model.eval()
1271
+
1272
+ if output_loading_info:
1273
+ return model, loading_info
1274
+
1275
+ return model
1276
+
1277
+ # Adapted from `transformers`.
1278
+ @wraps(torch.nn.Module.cuda)
1279
+ def cuda(self, *args, **kwargs):
1280
+ from ..hooks.group_offloading import _is_group_offload_enabled
1281
+
1282
+ # Checks if the model has been loaded in 4-bit or 8-bit with BNB
1283
+ if getattr(self, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES:
1284
+ if getattr(self, "is_loaded_in_8bit", False):
1285
+ raise ValueError(
1286
+ "Calling `cuda()` is not supported for `8-bit` quantized models. "
1287
+ " Please use the model as it is, since the model has already been set to the correct devices."
1288
+ )
1289
+ elif is_bitsandbytes_version("<", "0.43.2"):
1290
+ raise ValueError(
1291
+ "Calling `cuda()` is not supported for `4-bit` quantized models with the installed version of bitsandbytes. "
1292
+ f"The current device is `{self.device}`. If you intended to move the model, please install bitsandbytes >= 0.43.2."
1293
+ )
1294
+
1295
+ # Checks if group offloading is enabled
1296
+ if _is_group_offload_enabled(self):
1297
+ logger.warning(
1298
+ f"The module '{self.__class__.__name__}' is group offloaded and moving it using `.cuda()` is not supported."
1299
+ )
1300
+ return self
1301
+
1302
+ return super().cuda(*args, **kwargs)
1303
+
1304
+ # Adapted from `transformers`.
1305
+ @wraps(torch.nn.Module.to)
1306
+ def to(self, *args, **kwargs):
1307
+ from ..hooks.group_offloading import _is_group_offload_enabled
1308
+
1309
+ device_arg_or_kwarg_present = any(isinstance(arg, torch.device) for arg in args) or "device" in kwargs
1310
+ dtype_present_in_args = "dtype" in kwargs
1311
+
1312
+ # Try converting arguments to torch.device in case they are passed as strings
1313
+ for arg in args:
1314
+ if not isinstance(arg, str):
1315
+ continue
1316
+ try:
1317
+ torch.device(arg)
1318
+ device_arg_or_kwarg_present = True
1319
+ except RuntimeError:
1320
+ pass
1321
+
1322
+ if not dtype_present_in_args:
1323
+ for arg in args:
1324
+ if isinstance(arg, torch.dtype):
1325
+ dtype_present_in_args = True
1326
+ break
1327
+
1328
+ if getattr(self, "is_quantized", False):
1329
+ if dtype_present_in_args:
1330
+ raise ValueError(
1331
+ "Casting a quantized model to a new `dtype` is unsupported. To set the dtype of unquantized layers, please "
1332
+ "use the `torch_dtype` argument when loading the model using `from_pretrained` or `from_single_file`"
1333
+ )
1334
+
1335
+ if getattr(self, "quantization_method", None) == QuantizationMethod.BITS_AND_BYTES:
1336
+ if getattr(self, "is_loaded_in_8bit", False):
1337
+ raise ValueError(
1338
+ "`.to` is not supported for `8-bit` bitsandbytes models. Please use the model as it is, since the"
1339
+ " model has already been set to the correct devices and casted to the correct `dtype`."
1340
+ )
1341
+ elif is_bitsandbytes_version("<", "0.43.2"):
1342
+ raise ValueError(
1343
+ "Calling `to()` is not supported for `4-bit` quantized models with the installed version of bitsandbytes. "
1344
+ f"The current device is `{self.device}`. If you intended to move the model, please install bitsandbytes >= 0.43.2."
1345
+ )
1346
+
1347
+ if _is_group_offload_enabled(self) and device_arg_or_kwarg_present:
1348
+ logger.warning(
1349
+ f"The module '{self.__class__.__name__}' is group offloaded and moving it using `.to()` is not supported."
1350
+ )
1351
+ return self
1352
+
1353
+ return super().to(*args, **kwargs)
1354
+
1355
+ # Taken from `transformers`.
1356
+ def half(self, *args):
1357
+ # Checks if the model is quantized
1358
+ if getattr(self, "is_quantized", False):
1359
+ raise ValueError(
1360
+ "`.half()` is not supported for quantized model. Please use the model as it is, since the"
1361
+ " model has already been cast to the correct `dtype`."
1362
+ )
1363
+ else:
1364
+ return super().half(*args)
1365
+
1366
+ # Taken from `transformers`.
1367
+ def float(self, *args):
1368
+ # Checks if the model is quantized
1369
+ if getattr(self, "is_quantized", False):
1370
+ raise ValueError(
1371
+ "`.float()` is not supported for quantized model. Please use the model as it is, since the"
1372
+ " model has already been cast to the correct `dtype`."
1373
+ )
1374
+ else:
1375
+ return super().float(*args)
1376
+
1377
+ @classmethod
1378
+ def _load_pretrained_model(
1379
+ cls,
1380
+ model,
1381
+ state_dict: OrderedDict,
1382
+ resolved_model_file: List[str],
1383
+ pretrained_model_name_or_path: Union[str, os.PathLike],
1384
+ loaded_keys: List[str],
1385
+ ignore_mismatched_sizes: bool = False,
1386
+ assign_to_params_buffers: bool = False,
1387
+ hf_quantizer: Optional[DiffusersQuantizer] = None,
1388
+ low_cpu_mem_usage: bool = True,
1389
+ dtype: Optional[Union[str, torch.dtype]] = None,
1390
+ keep_in_fp32_modules: Optional[List[str]] = None,
1391
+ device_map: Dict[str, Union[int, str, torch.device]] = None,
1392
+ offload_state_dict: Optional[bool] = None,
1393
+ offload_folder: Optional[Union[str, os.PathLike]] = None,
1394
+ dduf_entries: Optional[Dict[str, DDUFEntry]] = None,
1395
+ ):
1396
+ model_state_dict = model.state_dict()
1397
+ expected_keys = list(model_state_dict.keys())
1398
+ missing_keys = list(set(expected_keys) - set(loaded_keys))
1399
+ if hf_quantizer is not None:
1400
+ missing_keys = hf_quantizer.update_missing_keys(model, missing_keys, prefix="")
1401
+ unexpected_keys = list(set(loaded_keys) - set(expected_keys))
1402
+ # Some models may have keys that are not in the state by design, removing them before needlessly warning
1403
+ # the user.
1404
+ if cls._keys_to_ignore_on_load_unexpected is not None:
1405
+ for pat in cls._keys_to_ignore_on_load_unexpected:
1406
+ unexpected_keys = [k for k in unexpected_keys if re.search(pat, k) is None]
1407
+
1408
+ mismatched_keys = []
1409
+
1410
+ assign_to_params_buffers = None
1411
+ error_msgs = []
1412
+
1413
+ # Deal with offload
1414
+ if device_map is not None and "disk" in device_map.values():
1415
+ if offload_folder is None:
1416
+ raise ValueError(
1417
+ "The current `device_map` had weights offloaded to the disk. Please provide an `offload_folder`"
1418
+ " for them. Alternatively, make sure you have `safetensors` installed if the model you are using"
1419
+ " offers the weights in this format."
1420
+ )
1421
+ if offload_folder is not None:
1422
+ os.makedirs(offload_folder, exist_ok=True)
1423
+ if offload_state_dict is None:
1424
+ offload_state_dict = True
1425
+
1426
+ offload_index = {} if device_map is not None and "disk" in device_map.values() else None
1427
+ if offload_state_dict:
1428
+ state_dict_folder = tempfile.mkdtemp()
1429
+ state_dict_index = {}
1430
+ else:
1431
+ state_dict_folder = None
1432
+ state_dict_index = None
1433
+
1434
+ if state_dict is not None:
1435
+ # load_state_dict will manage the case where we pass a dict instead of a file
1436
+ # if state dict is not None, it means that we don't need to read the files from resolved_model_file also
1437
+ resolved_model_file = [state_dict]
1438
+
1439
+ if len(resolved_model_file) > 1:
1440
+ resolved_model_file = logging.tqdm(resolved_model_file, desc="Loading checkpoint shards")
1441
+
1442
+ for shard_file in resolved_model_file:
1443
+ state_dict = load_state_dict(shard_file, dduf_entries=dduf_entries)
1444
+
1445
+ def _find_mismatched_keys(
1446
+ state_dict,
1447
+ model_state_dict,
1448
+ loaded_keys,
1449
+ ignore_mismatched_sizes,
1450
+ ):
1451
+ mismatched_keys = []
1452
+ if ignore_mismatched_sizes:
1453
+ for checkpoint_key in loaded_keys:
1454
+ model_key = checkpoint_key
1455
+ # If the checkpoint is sharded, we may not have the key here.
1456
+ if checkpoint_key not in state_dict:
1457
+ continue
1458
+
1459
+ if (
1460
+ model_key in model_state_dict
1461
+ and state_dict[checkpoint_key].shape != model_state_dict[model_key].shape
1462
+ ):
1463
+ mismatched_keys.append(
1464
+ (checkpoint_key, state_dict[checkpoint_key].shape, model_state_dict[model_key].shape)
1465
+ )
1466
+ del state_dict[checkpoint_key]
1467
+ return mismatched_keys
1468
+
1469
+ mismatched_keys += _find_mismatched_keys(
1470
+ state_dict,
1471
+ model_state_dict,
1472
+ loaded_keys,
1473
+ ignore_mismatched_sizes,
1474
+ )
1475
+
1476
+ if low_cpu_mem_usage:
1477
+ offload_index, state_dict_index = load_model_dict_into_meta(
1478
+ model,
1479
+ state_dict,
1480
+ device_map=device_map,
1481
+ dtype=dtype,
1482
+ hf_quantizer=hf_quantizer,
1483
+ keep_in_fp32_modules=keep_in_fp32_modules,
1484
+ unexpected_keys=unexpected_keys,
1485
+ offload_folder=offload_folder,
1486
+ offload_index=offload_index,
1487
+ state_dict_index=state_dict_index,
1488
+ state_dict_folder=state_dict_folder,
1489
+ )
1490
+ else:
1491
+ if assign_to_params_buffers is None:
1492
+ assign_to_params_buffers = check_support_param_buffer_assignment(model, state_dict)
1493
+
1494
+ error_msgs += _load_state_dict_into_model(model, state_dict, assign_to_params_buffers)
1495
+
1496
+ if offload_index is not None and len(offload_index) > 0:
1497
+ save_offload_index(offload_index, offload_folder)
1498
+ offload_index = None
1499
+
1500
+ if offload_state_dict:
1501
+ load_offloaded_weights(model, state_dict_index, state_dict_folder)
1502
+ shutil.rmtree(state_dict_folder)
1503
+
1504
+ if len(error_msgs) > 0:
1505
+ error_msg = "\n\t".join(error_msgs)
1506
+ if "size mismatch" in error_msg:
1507
+ error_msg += (
1508
+ "\n\tYou may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method."
1509
+ )
1510
+ raise RuntimeError(f"Error(s) in loading state_dict for {model.__class__.__name__}:\n\t{error_msg}")
1511
+
1512
+ if len(unexpected_keys) > 0:
1513
+ logger.warning(
1514
+ f"Some weights of the model checkpoint at {pretrained_model_name_or_path} were not used when initializing {cls.__name__}: \n {[', '.join(unexpected_keys)]}"
1515
+ )
1516
+ else:
1517
+ logger.info(f"All model checkpoint weights were used when initializing {model.__class__.__name__}.\n")
1518
+
1519
+ if len(missing_keys) > 0:
1520
+ logger.warning(
1521
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
1522
+ f" {pretrained_model_name_or_path} and are newly initialized: {missing_keys}\nYou should probably"
1523
+ " TRAIN this model on a down-stream task to be able to use it for predictions and inference."
1524
+ )
1525
+ elif len(mismatched_keys) == 0:
1526
+ logger.info(
1527
+ f"All the weights of {model.__class__.__name__} were initialized from the model checkpoint at"
1528
+ f" {pretrained_model_name_or_path}.\nIf your task is similar to the task the model of the"
1529
+ f" checkpoint was trained on, you can already use {model.__class__.__name__} for predictions"
1530
+ " without further training."
1531
+ )
1532
+ if len(mismatched_keys) > 0:
1533
+ mismatched_warning = "\n".join(
1534
+ [
1535
+ f"- {key}: found shape {shape1} in the checkpoint and {shape2} in the model instantiated"
1536
+ for key, shape1, shape2 in mismatched_keys
1537
+ ]
1538
+ )
1539
+ logger.warning(
1540
+ f"Some weights of {model.__class__.__name__} were not initialized from the model checkpoint at"
1541
+ f" {pretrained_model_name_or_path} and are newly initialized because the shapes did not"
1542
+ f" match:\n{mismatched_warning}\nYou should probably TRAIN this model on a down-stream task to be"
1543
+ " able to use it for predictions and inference."
1544
+ )
1545
+
1546
+ return model, missing_keys, unexpected_keys, mismatched_keys, offload_index, error_msgs
1547
+
1548
+ @classmethod
1549
+ def _get_signature_keys(cls, obj):
1550
+ parameters = inspect.signature(obj.__init__).parameters
1551
+ required_parameters = {k: v for k, v in parameters.items() if v.default == inspect._empty}
1552
+ optional_parameters = set({k for k, v in parameters.items() if v.default != inspect._empty})
1553
+ expected_modules = set(required_parameters.keys()) - {"self"}
1554
+
1555
+ return expected_modules, optional_parameters
1556
+
1557
+ # Adapted from `transformers` modeling_utils.py
1558
+ def _get_no_split_modules(self, device_map: str):
1559
+ """
1560
+ Get the modules of the model that should not be split when using device_map. We iterate through the modules to
1561
+ get the underlying `_no_split_modules`.
1562
+
1563
+ Args:
1564
+ device_map (`str`):
1565
+ The device map value. Options are ["auto", "balanced", "balanced_low_0", "sequential"]
1566
+
1567
+ Returns:
1568
+ `List[str]`: List of modules that should not be split
1569
+ """
1570
+ _no_split_modules = set()
1571
+ modules_to_check = [self]
1572
+ while len(modules_to_check) > 0:
1573
+ module = modules_to_check.pop(-1)
1574
+ # if the module does not appear in _no_split_modules, we also check the children
1575
+ if module.__class__.__name__ not in _no_split_modules:
1576
+ if isinstance(module, ModelMixin):
1577
+ if module._no_split_modules is None:
1578
+ raise ValueError(
1579
+ f"{module.__class__.__name__} does not support `device_map='{device_map}'`. To implement support, the model "
1580
+ "class needs to implement the `_no_split_modules` attribute."
1581
+ )
1582
+ else:
1583
+ _no_split_modules = _no_split_modules | set(module._no_split_modules)
1584
+ modules_to_check += list(module.children())
1585
+ return list(_no_split_modules)
1586
+
1587
+ @classmethod
1588
+ def _set_default_torch_dtype(cls, dtype: torch.dtype) -> torch.dtype:
1589
+ """
1590
+ Change the default dtype and return the previous one. This is needed when wanting to instantiate the model
1591
+ under specific dtype.
1592
+
1593
+ Args:
1594
+ dtype (`torch.dtype`):
1595
+ a floating dtype to set to.
1596
+
1597
+ Returns:
1598
+ `torch.dtype`: the original `dtype` that can be used to restore `torch.set_default_dtype(dtype)` if it was
1599
+ modified. If it wasn't, returns `None`.
1600
+
1601
+ Note `set_default_dtype` currently only works with floating-point types and asserts if for example,
1602
+ `torch.int64` is passed. So if a non-float `dtype` is passed this functions will throw an exception.
1603
+ """
1604
+ if not dtype.is_floating_point:
1605
+ raise ValueError(
1606
+ f"Can't instantiate {cls.__name__} model under dtype={dtype} since it is not a floating point dtype"
1607
+ )
1608
+
1609
+ logger.info(f"Instantiating {cls.__name__} model under default dtype {dtype}.")
1610
+ dtype_orig = torch.get_default_dtype()
1611
+ torch.set_default_dtype(dtype)
1612
+ return dtype_orig
1613
+
1614
+ @property
1615
+ def device(self) -> torch.device:
1616
+ """
1617
+ `torch.device`: The device on which the module is (assuming that all the module parameters are on the same
1618
+ device).
1619
+ """
1620
+ return get_parameter_device(self)
1621
+
1622
+ @property
1623
+ def dtype(self) -> torch.dtype:
1624
+ """
1625
+ `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
1626
+ """
1627
+ return get_parameter_dtype(self)
1628
+
1629
+ def num_parameters(self, only_trainable: bool = False, exclude_embeddings: bool = False) -> int:
1630
+ """
1631
+ Get number of (trainable or non-embedding) parameters in the module.
1632
+
1633
+ Args:
1634
+ only_trainable (`bool`, *optional*, defaults to `False`):
1635
+ Whether or not to return only the number of trainable parameters.
1636
+ exclude_embeddings (`bool`, *optional*, defaults to `False`):
1637
+ Whether or not to return only the number of non-embedding parameters.
1638
+
1639
+ Returns:
1640
+ `int`: The number of parameters.
1641
+
1642
+ Example:
1643
+
1644
+ ```py
1645
+ from diffusers import UNet2DConditionModel
1646
+
1647
+ model_id = "runwayml/stable-diffusion-v1-5"
1648
+ unet = UNet2DConditionModel.from_pretrained(model_id, subfolder="unet")
1649
+ unet.num_parameters(only_trainable=True)
1650
+ 859520964
1651
+ ```
1652
+ """
1653
+ is_loaded_in_4bit = getattr(self, "is_loaded_in_4bit", False)
1654
+
1655
+ if is_loaded_in_4bit:
1656
+ if is_bitsandbytes_available():
1657
+ import bitsandbytes as bnb
1658
+ else:
1659
+ raise ValueError(
1660
+ "bitsandbytes is not installed but it seems that the model has been loaded in 4bit precision, something went wrong"
1661
+ " make sure to install bitsandbytes with `pip install bitsandbytes`. You also need a GPU. "
1662
+ )
1663
+
1664
+ if exclude_embeddings:
1665
+ embedding_param_names = [
1666
+ f"{name}.weight" for name, module_type in self.named_modules() if isinstance(module_type, nn.Embedding)
1667
+ ]
1668
+ total_parameters = [
1669
+ parameter for name, parameter in self.named_parameters() if name not in embedding_param_names
1670
+ ]
1671
+ else:
1672
+ total_parameters = list(self.parameters())
1673
+
1674
+ total_numel = []
1675
+
1676
+ for param in total_parameters:
1677
+ if param.requires_grad or not only_trainable:
1678
+ # For 4bit models, we need to multiply the number of parameters by 2 as half of the parameters are
1679
+ # used for the 4bit quantization (uint8 tensors are stored)
1680
+ if is_loaded_in_4bit and isinstance(param, bnb.nn.Params4bit):
1681
+ if hasattr(param, "element_size"):
1682
+ num_bytes = param.element_size()
1683
+ elif hasattr(param, "quant_storage"):
1684
+ num_bytes = param.quant_storage.itemsize
1685
+ else:
1686
+ num_bytes = 1
1687
+ total_numel.append(param.numel() * 2 * num_bytes)
1688
+ else:
1689
+ total_numel.append(param.numel())
1690
+
1691
+ return sum(total_numel)
1692
+
1693
+ def get_memory_footprint(self, return_buffers=True):
1694
+ r"""
1695
+ Get the memory footprint of a model. This will return the memory footprint of the current model in bytes.
1696
+ Useful to benchmark the memory footprint of the current model and design some tests. Solution inspired from the
1697
+ PyTorch discussions: https://discuss.pytorch.org/t/gpu-memory-that-model-uses/56822/2
1698
+
1699
+ Arguments:
1700
+ return_buffers (`bool`, *optional*, defaults to `True`):
1701
+ Whether to return the size of the buffer tensors in the computation of the memory footprint. Buffers
1702
+ are tensors that do not require gradients and not registered as parameters. E.g. mean and std in batch
1703
+ norm layers. Please see: https://discuss.pytorch.org/t/what-pytorch-means-by-buffers/120266/2
1704
+ """
1705
+ mem = sum([param.nelement() * param.element_size() for param in self.parameters()])
1706
+ if return_buffers:
1707
+ mem_bufs = sum([buf.nelement() * buf.element_size() for buf in self.buffers()])
1708
+ mem = mem + mem_bufs
1709
+ return mem
1710
+
1711
+ def _set_gradient_checkpointing(
1712
+ self, enable: bool = True, gradient_checkpointing_func: Callable = torch.utils.checkpoint.checkpoint
1713
+ ) -> None:
1714
+ is_gradient_checkpointing_set = False
1715
+
1716
+ for name, module in self.named_modules():
1717
+ if hasattr(module, "gradient_checkpointing"):
1718
+ logger.debug(f"Setting `gradient_checkpointing={enable}` for '{name}'")
1719
+ module._gradient_checkpointing_func = gradient_checkpointing_func
1720
+ module.gradient_checkpointing = enable
1721
+ is_gradient_checkpointing_set = True
1722
+
1723
+ if not is_gradient_checkpointing_set:
1724
+ raise ValueError(
1725
+ f"The module {self.__class__.__name__} does not support gradient checkpointing. Please make sure to "
1726
+ f"use a module that supports gradient checkpointing by creating a boolean attribute `gradient_checkpointing`."
1727
+ )
1728
+
1729
+ def _fix_state_dict_keys_on_load(self, state_dict: OrderedDict) -> None:
1730
+ """
1731
+ This function fix the state dict of the model to take into account some changes that were made in the model
1732
+ architecture:
1733
+ - deprecated attention blocks (happened before we introduced sharded checkpoint,
1734
+ so this is why we apply this method only when loading non sharded checkpoints for now)
1735
+ """
1736
+ deprecated_attention_block_paths = []
1737
+
1738
+ def recursive_find_attn_block(name, module):
1739
+ if hasattr(module, "_from_deprecated_attn_block") and module._from_deprecated_attn_block:
1740
+ deprecated_attention_block_paths.append(name)
1741
+
1742
+ for sub_name, sub_module in module.named_children():
1743
+ sub_name = sub_name if name == "" else f"{name}.{sub_name}"
1744
+ recursive_find_attn_block(sub_name, sub_module)
1745
+
1746
+ recursive_find_attn_block("", self)
1747
+
1748
+ # NOTE: we have to check if the deprecated parameters are in the state dict
1749
+ # because it is possible we are loading from a state dict that was already
1750
+ # converted
1751
+
1752
+ for path in deprecated_attention_block_paths:
1753
+ # group_norm path stays the same
1754
+
1755
+ # query -> to_q
1756
+ if f"{path}.query.weight" in state_dict:
1757
+ state_dict[f"{path}.to_q.weight"] = state_dict.pop(f"{path}.query.weight")
1758
+ if f"{path}.query.bias" in state_dict:
1759
+ state_dict[f"{path}.to_q.bias"] = state_dict.pop(f"{path}.query.bias")
1760
+
1761
+ # key -> to_k
1762
+ if f"{path}.key.weight" in state_dict:
1763
+ state_dict[f"{path}.to_k.weight"] = state_dict.pop(f"{path}.key.weight")
1764
+ if f"{path}.key.bias" in state_dict:
1765
+ state_dict[f"{path}.to_k.bias"] = state_dict.pop(f"{path}.key.bias")
1766
+
1767
+ # value -> to_v
1768
+ if f"{path}.value.weight" in state_dict:
1769
+ state_dict[f"{path}.to_v.weight"] = state_dict.pop(f"{path}.value.weight")
1770
+ if f"{path}.value.bias" in state_dict:
1771
+ state_dict[f"{path}.to_v.bias"] = state_dict.pop(f"{path}.value.bias")
1772
+
1773
+ # proj_attn -> to_out.0
1774
+ if f"{path}.proj_attn.weight" in state_dict:
1775
+ state_dict[f"{path}.to_out.0.weight"] = state_dict.pop(f"{path}.proj_attn.weight")
1776
+ if f"{path}.proj_attn.bias" in state_dict:
1777
+ state_dict[f"{path}.to_out.0.bias"] = state_dict.pop(f"{path}.proj_attn.bias")
1778
+ return state_dict
1779
+
1780
+
1781
+ class LegacyModelMixin(ModelMixin):
1782
+ r"""
1783
+ A subclass of `ModelMixin` to resolve class mapping from legacy classes (like `Transformer2DModel`) to more
1784
+ pipeline-specific classes (like `DiTTransformer2DModel`).
1785
+ """
1786
+
1787
+ @classmethod
1788
+ @validate_hf_hub_args
1789
+ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
1790
+ # To prevent dependency import problem.
1791
+ from .model_loading_utils import _fetch_remapped_cls_from_config
1792
+
1793
+ # Create a copy of the kwargs so that we don't mess with the keyword arguments in the downstream calls.
1794
+ kwargs_copy = kwargs.copy()
1795
+
1796
+ cache_dir = kwargs.pop("cache_dir", None)
1797
+ force_download = kwargs.pop("force_download", False)
1798
+ proxies = kwargs.pop("proxies", None)
1799
+ local_files_only = kwargs.pop("local_files_only", None)
1800
+ token = kwargs.pop("token", None)
1801
+ revision = kwargs.pop("revision", None)
1802
+ subfolder = kwargs.pop("subfolder", None)
1803
+
1804
+ # Load config if we don't provide a configuration
1805
+ config_path = pretrained_model_name_or_path
1806
+
1807
+ user_agent = {
1808
+ "diffusers": __version__,
1809
+ "file_type": "model",
1810
+ "framework": "pytorch",
1811
+ }
1812
+
1813
+ # load config
1814
+ config, _, _ = cls.load_config(
1815
+ config_path,
1816
+ cache_dir=cache_dir,
1817
+ return_unused_kwargs=True,
1818
+ return_commit_hash=True,
1819
+ force_download=force_download,
1820
+ proxies=proxies,
1821
+ local_files_only=local_files_only,
1822
+ token=token,
1823
+ revision=revision,
1824
+ subfolder=subfolder,
1825
+ user_agent=user_agent,
1826
+ **kwargs,
1827
+ )
1828
+ # resolve remapping
1829
+ remapped_class = _fetch_remapped_cls_from_config(config, cls)
1830
+
1831
+ return remapped_class.from_pretrained(pretrained_model_name_or_path, **kwargs_copy)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/normalization.py ADDED
@@ -0,0 +1,648 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2024 HuggingFace Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import numbers
17
+ from typing import Dict, Optional, Tuple
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from ..utils import is_torch_npu_available, is_torch_version
24
+ from .activations import get_activation
25
+ from .embeddings import CombinedTimestepLabelEmbeddings, PixArtAlphaCombinedTimestepSizeEmbeddings
26
+
27
+
28
+ class AdaLayerNorm(nn.Module):
29
+ r"""
30
+ Norm layer modified to incorporate timestep embeddings.
31
+
32
+ Parameters:
33
+ embedding_dim (`int`): The size of each embedding vector.
34
+ num_embeddings (`int`, *optional*): The size of the embeddings dictionary.
35
+ output_dim (`int`, *optional*):
36
+ norm_elementwise_affine (`bool`, defaults to `False):
37
+ norm_eps (`bool`, defaults to `False`):
38
+ chunk_dim (`int`, defaults to `0`):
39
+ """
40
+
41
+ def __init__(
42
+ self,
43
+ embedding_dim: int,
44
+ num_embeddings: Optional[int] = None,
45
+ output_dim: Optional[int] = None,
46
+ norm_elementwise_affine: bool = False,
47
+ norm_eps: float = 1e-5,
48
+ chunk_dim: int = 0,
49
+ ):
50
+ super().__init__()
51
+
52
+ self.chunk_dim = chunk_dim
53
+ output_dim = output_dim or embedding_dim * 2
54
+
55
+ if num_embeddings is not None:
56
+ self.emb = nn.Embedding(num_embeddings, embedding_dim)
57
+ else:
58
+ self.emb = None
59
+
60
+ self.silu = nn.SiLU()
61
+ self.linear = nn.Linear(embedding_dim, output_dim)
62
+ self.norm = nn.LayerNorm(output_dim // 2, norm_eps, norm_elementwise_affine)
63
+
64
+ def forward(
65
+ self, x: torch.Tensor, timestep: Optional[torch.Tensor] = None, temb: Optional[torch.Tensor] = None
66
+ ) -> torch.Tensor:
67
+ if self.emb is not None:
68
+ temb = self.emb(timestep)
69
+
70
+ temb = self.linear(self.silu(temb))
71
+
72
+ if self.chunk_dim == 1:
73
+ # This is a bit weird why we have the order of "shift, scale" here and "scale, shift" in the
74
+ # other if-branch. This branch is specific to CogVideoX and OmniGen for now.
75
+ shift, scale = temb.chunk(2, dim=1)
76
+ shift = shift[:, None, :]
77
+ scale = scale[:, None, :]
78
+ else:
79
+ scale, shift = temb.chunk(2, dim=0)
80
+
81
+ x = self.norm(x) * (1 + scale) + shift
82
+ return x
83
+
84
+
85
+ class FP32LayerNorm(nn.LayerNorm):
86
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
87
+ origin_dtype = inputs.dtype
88
+ return F.layer_norm(
89
+ inputs.float(),
90
+ self.normalized_shape,
91
+ self.weight.float() if self.weight is not None else None,
92
+ self.bias.float() if self.bias is not None else None,
93
+ self.eps,
94
+ ).to(origin_dtype)
95
+
96
+
97
+ class SD35AdaLayerNormZeroX(nn.Module):
98
+ r"""
99
+ Norm layer adaptive layer norm zero (AdaLN-Zero).
100
+
101
+ Parameters:
102
+ embedding_dim (`int`): The size of each embedding vector.
103
+ num_embeddings (`int`): The size of the embeddings dictionary.
104
+ """
105
+
106
+ def __init__(self, embedding_dim: int, norm_type: str = "layer_norm", bias: bool = True) -> None:
107
+ super().__init__()
108
+
109
+ self.silu = nn.SiLU()
110
+ self.linear = nn.Linear(embedding_dim, 9 * embedding_dim, bias=bias)
111
+ if norm_type == "layer_norm":
112
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
113
+ else:
114
+ raise ValueError(f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm'.")
115
+
116
+ def forward(
117
+ self,
118
+ hidden_states: torch.Tensor,
119
+ emb: Optional[torch.Tensor] = None,
120
+ ) -> Tuple[torch.Tensor, ...]:
121
+ emb = self.linear(self.silu(emb))
122
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp, shift_msa2, scale_msa2, gate_msa2 = emb.chunk(
123
+ 9, dim=1
124
+ )
125
+ norm_hidden_states = self.norm(hidden_states)
126
+ hidden_states = norm_hidden_states * (1 + scale_msa[:, None]) + shift_msa[:, None]
127
+ norm_hidden_states2 = norm_hidden_states * (1 + scale_msa2[:, None]) + shift_msa2[:, None]
128
+ return hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp, norm_hidden_states2, gate_msa2
129
+
130
+
131
+ class AdaLayerNormZero(nn.Module):
132
+ r"""
133
+ Norm layer adaptive layer norm zero (adaLN-Zero).
134
+
135
+ Parameters:
136
+ embedding_dim (`int`): The size of each embedding vector.
137
+ num_embeddings (`int`): The size of the embeddings dictionary.
138
+ """
139
+
140
+ def __init__(self, embedding_dim: int, num_embeddings: Optional[int] = None, norm_type="layer_norm", bias=True):
141
+ super().__init__()
142
+ if num_embeddings is not None:
143
+ self.emb = CombinedTimestepLabelEmbeddings(num_embeddings, embedding_dim)
144
+ else:
145
+ self.emb = None
146
+
147
+ self.silu = nn.SiLU()
148
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=bias)
149
+ if norm_type == "layer_norm":
150
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
151
+ elif norm_type == "fp32_layer_norm":
152
+ self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=False, bias=False)
153
+ else:
154
+ raise ValueError(
155
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
156
+ )
157
+
158
+ def forward(
159
+ self,
160
+ x: torch.Tensor,
161
+ timestep: Optional[torch.Tensor] = None,
162
+ class_labels: Optional[torch.LongTensor] = None,
163
+ hidden_dtype: Optional[torch.dtype] = None,
164
+ emb: Optional[torch.Tensor] = None,
165
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
166
+ if self.emb is not None:
167
+ emb = self.emb(timestep, class_labels, hidden_dtype=hidden_dtype)
168
+ emb = self.linear(self.silu(emb))
169
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
170
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
171
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp
172
+
173
+
174
+ class AdaLayerNormZeroSingle(nn.Module):
175
+ r"""
176
+ Norm layer adaptive layer norm zero (adaLN-Zero).
177
+
178
+ Parameters:
179
+ embedding_dim (`int`): The size of each embedding vector.
180
+ num_embeddings (`int`): The size of the embeddings dictionary.
181
+ """
182
+
183
+ def __init__(self, embedding_dim: int, norm_type="layer_norm", bias=True):
184
+ super().__init__()
185
+
186
+ self.silu = nn.SiLU()
187
+ self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
188
+ if norm_type == "layer_norm":
189
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
190
+ else:
191
+ raise ValueError(
192
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
193
+ )
194
+
195
+ def forward(
196
+ self,
197
+ x: torch.Tensor,
198
+ emb: Optional[torch.Tensor] = None,
199
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
200
+ emb = self.linear(self.silu(emb))
201
+ shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
202
+ x = self.norm(x) * (1 + scale_msa[:, None]) + shift_msa[:, None]
203
+ return x, gate_msa
204
+
205
+
206
+ class LuminaRMSNormZero(nn.Module):
207
+ """
208
+ Norm layer adaptive RMS normalization zero.
209
+
210
+ Parameters:
211
+ embedding_dim (`int`): The size of each embedding vector.
212
+ """
213
+
214
+ def __init__(self, embedding_dim: int, norm_eps: float, norm_elementwise_affine: bool):
215
+ super().__init__()
216
+ self.silu = nn.SiLU()
217
+ self.linear = nn.Linear(
218
+ min(embedding_dim, 1024),
219
+ 4 * embedding_dim,
220
+ bias=True,
221
+ )
222
+ self.norm = RMSNorm(embedding_dim, eps=norm_eps)
223
+
224
+ def forward(
225
+ self,
226
+ x: torch.Tensor,
227
+ emb: Optional[torch.Tensor] = None,
228
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
229
+ emb = self.linear(self.silu(emb))
230
+ scale_msa, gate_msa, scale_mlp, gate_mlp = emb.chunk(4, dim=1)
231
+ x = self.norm(x) * (1 + scale_msa[:, None])
232
+
233
+ return x, gate_msa, scale_mlp, gate_mlp
234
+
235
+
236
+ class AdaLayerNormSingle(nn.Module):
237
+ r"""
238
+ Norm layer adaptive layer norm single (adaLN-single).
239
+
240
+ As proposed in PixArt-Alpha (see: https://arxiv.org/abs/2310.00426; Section 2.3).
241
+
242
+ Parameters:
243
+ embedding_dim (`int`): The size of each embedding vector.
244
+ use_additional_conditions (`bool`): To use additional conditions for normalization or not.
245
+ """
246
+
247
+ def __init__(self, embedding_dim: int, use_additional_conditions: bool = False):
248
+ super().__init__()
249
+
250
+ self.emb = PixArtAlphaCombinedTimestepSizeEmbeddings(
251
+ embedding_dim, size_emb_dim=embedding_dim // 3, use_additional_conditions=use_additional_conditions
252
+ )
253
+
254
+ self.silu = nn.SiLU()
255
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
256
+
257
+ def forward(
258
+ self,
259
+ timestep: torch.Tensor,
260
+ added_cond_kwargs: Optional[Dict[str, torch.Tensor]] = None,
261
+ batch_size: Optional[int] = None,
262
+ hidden_dtype: Optional[torch.dtype] = None,
263
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
264
+ # No modulation happening here.
265
+ added_cond_kwargs = added_cond_kwargs or {"resolution": None, "aspect_ratio": None}
266
+ embedded_timestep = self.emb(timestep, **added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_dtype)
267
+ return self.linear(self.silu(embedded_timestep)), embedded_timestep
268
+
269
+
270
+ class AdaGroupNorm(nn.Module):
271
+ r"""
272
+ GroupNorm layer modified to incorporate timestep embeddings.
273
+
274
+ Parameters:
275
+ embedding_dim (`int`): The size of each embedding vector.
276
+ num_embeddings (`int`): The size of the embeddings dictionary.
277
+ num_groups (`int`): The number of groups to separate the channels into.
278
+ act_fn (`str`, *optional*, defaults to `None`): The activation function to use.
279
+ eps (`float`, *optional*, defaults to `1e-5`): The epsilon value to use for numerical stability.
280
+ """
281
+
282
+ def __init__(
283
+ self, embedding_dim: int, out_dim: int, num_groups: int, act_fn: Optional[str] = None, eps: float = 1e-5
284
+ ):
285
+ super().__init__()
286
+ self.num_groups = num_groups
287
+ self.eps = eps
288
+
289
+ if act_fn is None:
290
+ self.act = None
291
+ else:
292
+ self.act = get_activation(act_fn)
293
+
294
+ self.linear = nn.Linear(embedding_dim, out_dim * 2)
295
+
296
+ def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
297
+ if self.act:
298
+ emb = self.act(emb)
299
+ emb = self.linear(emb)
300
+ emb = emb[:, :, None, None]
301
+ scale, shift = emb.chunk(2, dim=1)
302
+
303
+ x = F.group_norm(x, self.num_groups, eps=self.eps)
304
+ x = x * (1 + scale) + shift
305
+ return x
306
+
307
+
308
+ class AdaLayerNormContinuous(nn.Module):
309
+ r"""
310
+ Adaptive normalization layer with a norm layer (layer_norm or rms_norm).
311
+
312
+ Args:
313
+ embedding_dim (`int`): Embedding dimension to use during projection.
314
+ conditioning_embedding_dim (`int`): Dimension of the input condition.
315
+ elementwise_affine (`bool`, defaults to `True`):
316
+ Boolean flag to denote if affine transformation should be applied.
317
+ eps (`float`, defaults to 1e-5): Epsilon factor.
318
+ bias (`bias`, defaults to `True`): Boolean flag to denote if bias should be use.
319
+ norm_type (`str`, defaults to `"layer_norm"`):
320
+ Normalization layer to use. Values supported: "layer_norm", "rms_norm".
321
+ """
322
+
323
+ def __init__(
324
+ self,
325
+ embedding_dim: int,
326
+ conditioning_embedding_dim: int,
327
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
328
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
329
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
330
+ # However, this is how it was implemented in the original code, and it's rather likely you should
331
+ # set `elementwise_affine` to False.
332
+ elementwise_affine=True,
333
+ eps=1e-5,
334
+ bias=True,
335
+ norm_type="layer_norm",
336
+ ):
337
+ super().__init__()
338
+ self.silu = nn.SiLU()
339
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=bias)
340
+ if norm_type == "layer_norm":
341
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
342
+ elif norm_type == "rms_norm":
343
+ self.norm = RMSNorm(embedding_dim, eps, elementwise_affine)
344
+ else:
345
+ raise ValueError(f"unknown norm_type {norm_type}")
346
+
347
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
348
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
349
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
350
+ scale, shift = torch.chunk(emb, 2, dim=1)
351
+ x = self.norm(x) * (1 + scale)[:, None, :] + shift[:, None, :]
352
+ return x
353
+
354
+
355
+ class LuminaLayerNormContinuous(nn.Module):
356
+ def __init__(
357
+ self,
358
+ embedding_dim: int,
359
+ conditioning_embedding_dim: int,
360
+ # NOTE: It is a bit weird that the norm layer can be configured to have scale and shift parameters
361
+ # because the output is immediately scaled and shifted by the projected conditioning embeddings.
362
+ # Note that AdaLayerNorm does not let the norm layer have scale and shift parameters.
363
+ # However, this is how it was implemented in the original code, and it's rather likely you should
364
+ # set `elementwise_affine` to False.
365
+ elementwise_affine=True,
366
+ eps=1e-5,
367
+ bias=True,
368
+ norm_type="layer_norm",
369
+ out_dim: Optional[int] = None,
370
+ ):
371
+ super().__init__()
372
+
373
+ # AdaLN
374
+ self.silu = nn.SiLU()
375
+ self.linear_1 = nn.Linear(conditioning_embedding_dim, embedding_dim, bias=bias)
376
+
377
+ if norm_type == "layer_norm":
378
+ self.norm = LayerNorm(embedding_dim, eps, elementwise_affine, bias)
379
+ elif norm_type == "rms_norm":
380
+ self.norm = RMSNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
381
+ else:
382
+ raise ValueError(f"unknown norm_type {norm_type}")
383
+
384
+ self.linear_2 = None
385
+ if out_dim is not None:
386
+ self.linear_2 = nn.Linear(embedding_dim, out_dim, bias=bias)
387
+
388
+ def forward(
389
+ self,
390
+ x: torch.Tensor,
391
+ conditioning_embedding: torch.Tensor,
392
+ ) -> torch.Tensor:
393
+ # convert back to the original dtype in case `conditioning_embedding`` is upcasted to float32 (needed for hunyuanDiT)
394
+ emb = self.linear_1(self.silu(conditioning_embedding).to(x.dtype))
395
+ scale = emb
396
+ x = self.norm(x) * (1 + scale)[:, None, :]
397
+
398
+ if self.linear_2 is not None:
399
+ x = self.linear_2(x)
400
+
401
+ return x
402
+
403
+
404
+ class CogView3PlusAdaLayerNormZeroTextImage(nn.Module):
405
+ r"""
406
+ Norm layer adaptive layer norm zero (adaLN-Zero).
407
+
408
+ Parameters:
409
+ embedding_dim (`int`): The size of each embedding vector.
410
+ num_embeddings (`int`): The size of the embeddings dictionary.
411
+ """
412
+
413
+ def __init__(self, embedding_dim: int, dim: int):
414
+ super().__init__()
415
+
416
+ self.silu = nn.SiLU()
417
+ self.linear = nn.Linear(embedding_dim, 12 * dim, bias=True)
418
+ self.norm_x = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
419
+ self.norm_c = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
420
+
421
+ def forward(
422
+ self,
423
+ x: torch.Tensor,
424
+ context: torch.Tensor,
425
+ emb: Optional[torch.Tensor] = None,
426
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
427
+ emb = self.linear(self.silu(emb))
428
+ (
429
+ shift_msa,
430
+ scale_msa,
431
+ gate_msa,
432
+ shift_mlp,
433
+ scale_mlp,
434
+ gate_mlp,
435
+ c_shift_msa,
436
+ c_scale_msa,
437
+ c_gate_msa,
438
+ c_shift_mlp,
439
+ c_scale_mlp,
440
+ c_gate_mlp,
441
+ ) = emb.chunk(12, dim=1)
442
+ normed_x = self.norm_x(x)
443
+ normed_context = self.norm_c(context)
444
+ x = normed_x * (1 + scale_msa[:, None]) + shift_msa[:, None]
445
+ context = normed_context * (1 + c_scale_msa[:, None]) + c_shift_msa[:, None]
446
+ return x, gate_msa, shift_mlp, scale_mlp, gate_mlp, context, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp
447
+
448
+
449
+ class CogVideoXLayerNormZero(nn.Module):
450
+ def __init__(
451
+ self,
452
+ conditioning_dim: int,
453
+ embedding_dim: int,
454
+ elementwise_affine: bool = True,
455
+ eps: float = 1e-5,
456
+ bias: bool = True,
457
+ ) -> None:
458
+ super().__init__()
459
+
460
+ self.silu = nn.SiLU()
461
+ self.linear = nn.Linear(conditioning_dim, 6 * embedding_dim, bias=bias)
462
+ self.norm = nn.LayerNorm(embedding_dim, eps=eps, elementwise_affine=elementwise_affine)
463
+
464
+ def forward(
465
+ self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
466
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
467
+ shift, scale, gate, enc_shift, enc_scale, enc_gate = self.linear(self.silu(temb)).chunk(6, dim=1)
468
+ hidden_states = self.norm(hidden_states) * (1 + scale)[:, None, :] + shift[:, None, :]
469
+ encoder_hidden_states = self.norm(encoder_hidden_states) * (1 + enc_scale)[:, None, :] + enc_shift[:, None, :]
470
+ return hidden_states, encoder_hidden_states, gate[:, None, :], enc_gate[:, None, :]
471
+
472
+
473
+ if is_torch_version(">=", "2.1.0"):
474
+ LayerNorm = nn.LayerNorm
475
+ else:
476
+ # Has optional bias parameter compared to torch layer norm
477
+ # TODO: replace with torch layernorm once min required torch version >= 2.1
478
+ class LayerNorm(nn.Module):
479
+ r"""
480
+ LayerNorm with the bias parameter.
481
+
482
+ Args:
483
+ dim (`int`): Dimensionality to use for the parameters.
484
+ eps (`float`, defaults to 1e-5): Epsilon factor.
485
+ elementwise_affine (`bool`, defaults to `True`):
486
+ Boolean flag to denote if affine transformation should be applied.
487
+ bias (`bias`, defaults to `True`): Boolean flag to denote if bias should be use.
488
+ """
489
+
490
+ def __init__(self, dim, eps: float = 1e-5, elementwise_affine: bool = True, bias: bool = True):
491
+ super().__init__()
492
+
493
+ self.eps = eps
494
+
495
+ if isinstance(dim, numbers.Integral):
496
+ dim = (dim,)
497
+
498
+ self.dim = torch.Size(dim)
499
+
500
+ if elementwise_affine:
501
+ self.weight = nn.Parameter(torch.ones(dim))
502
+ self.bias = nn.Parameter(torch.zeros(dim)) if bias else None
503
+ else:
504
+ self.weight = None
505
+ self.bias = None
506
+
507
+ def forward(self, input):
508
+ return F.layer_norm(input, self.dim, self.weight, self.bias, self.eps)
509
+
510
+
511
+ class RMSNorm(nn.Module):
512
+ r"""
513
+ RMS Norm as introduced in https://arxiv.org/abs/1910.07467 by Zhang et al.
514
+
515
+ Args:
516
+ dim (`int`): Number of dimensions to use for `weights`. Only effective when `elementwise_affine` is True.
517
+ eps (`float`): Small value to use when calculating the reciprocal of the square-root.
518
+ elementwise_affine (`bool`, defaults to `True`):
519
+ Boolean flag to denote if affine transformation should be applied.
520
+ bias (`bool`, defaults to False): If also training the `bias` param.
521
+ """
522
+
523
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True, bias: bool = False):
524
+ super().__init__()
525
+
526
+ self.eps = eps
527
+ self.elementwise_affine = elementwise_affine
528
+
529
+ if isinstance(dim, numbers.Integral):
530
+ dim = (dim,)
531
+
532
+ self.dim = torch.Size(dim)
533
+
534
+ self.weight = None
535
+ self.bias = None
536
+
537
+ if elementwise_affine:
538
+ self.weight = nn.Parameter(torch.ones(dim))
539
+ if bias:
540
+ self.bias = nn.Parameter(torch.zeros(dim))
541
+
542
+ def forward(self, hidden_states):
543
+ if is_torch_npu_available():
544
+ import torch_npu
545
+
546
+ if self.weight is not None:
547
+ # convert into half-precision if necessary
548
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
549
+ hidden_states = hidden_states.to(self.weight.dtype)
550
+ hidden_states = torch_npu.npu_rms_norm(hidden_states, self.weight, epsilon=self.eps)[0]
551
+ if self.bias is not None:
552
+ hidden_states = hidden_states + self.bias
553
+ else:
554
+ input_dtype = hidden_states.dtype
555
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
556
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
557
+
558
+ if self.weight is not None:
559
+ # convert into half-precision if necessary
560
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
561
+ hidden_states = hidden_states.to(self.weight.dtype)
562
+ hidden_states = hidden_states * self.weight
563
+ if self.bias is not None:
564
+ hidden_states = hidden_states + self.bias
565
+ else:
566
+ hidden_states = hidden_states.to(input_dtype)
567
+
568
+ return hidden_states
569
+
570
+
571
+ # TODO: (Dhruv) This can be replaced with regular RMSNorm in Mochi once `_keep_in_fp32_modules` is supported
572
+ # for sharded checkpoints, see: https://github.com/huggingface/diffusers/issues/10013
573
+ class MochiRMSNorm(nn.Module):
574
+ def __init__(self, dim, eps: float, elementwise_affine: bool = True):
575
+ super().__init__()
576
+
577
+ self.eps = eps
578
+
579
+ if isinstance(dim, numbers.Integral):
580
+ dim = (dim,)
581
+
582
+ self.dim = torch.Size(dim)
583
+
584
+ if elementwise_affine:
585
+ self.weight = nn.Parameter(torch.ones(dim))
586
+ else:
587
+ self.weight = None
588
+
589
+ def forward(self, hidden_states):
590
+ input_dtype = hidden_states.dtype
591
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
592
+ hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
593
+
594
+ if self.weight is not None:
595
+ hidden_states = hidden_states * self.weight
596
+ hidden_states = hidden_states.to(input_dtype)
597
+
598
+ return hidden_states
599
+
600
+
601
+ class GlobalResponseNorm(nn.Module):
602
+ r"""
603
+ Global response normalization as introduced in ConvNeXt-v2 (https://arxiv.org/abs/2301.00808).
604
+
605
+ Args:
606
+ dim (`int`): Number of dimensions to use for the `gamma` and `beta`.
607
+ """
608
+
609
+ # Taken from https://github.com/facebookresearch/ConvNeXt-V2/blob/3608f67cc1dae164790c5d0aead7bf2d73d9719b/models/utils.py#L105
610
+ def __init__(self, dim):
611
+ super().__init__()
612
+ self.gamma = nn.Parameter(torch.zeros(1, 1, 1, dim))
613
+ self.beta = nn.Parameter(torch.zeros(1, 1, 1, dim))
614
+
615
+ def forward(self, x):
616
+ gx = torch.norm(x, p=2, dim=(1, 2), keepdim=True)
617
+ nx = gx / (gx.mean(dim=-1, keepdim=True) + 1e-6)
618
+ return self.gamma * (x * nx) + self.beta + x
619
+
620
+
621
+ class LpNorm(nn.Module):
622
+ def __init__(self, p: int = 2, dim: int = -1, eps: float = 1e-12):
623
+ super().__init__()
624
+
625
+ self.p = p
626
+ self.dim = dim
627
+ self.eps = eps
628
+
629
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
630
+ return F.normalize(hidden_states, p=self.p, dim=self.dim, eps=self.eps)
631
+
632
+
633
+ def get_normalization(
634
+ norm_type: str = "batch_norm",
635
+ num_features: Optional[int] = None,
636
+ eps: float = 1e-5,
637
+ elementwise_affine: bool = True,
638
+ bias: bool = True,
639
+ ) -> nn.Module:
640
+ if norm_type == "rms_norm":
641
+ norm = RMSNorm(num_features, eps=eps, elementwise_affine=elementwise_affine, bias=bias)
642
+ elif norm_type == "layer_norm":
643
+ norm = nn.LayerNorm(num_features, eps=eps, elementwise_affine=elementwise_affine, bias=bias)
644
+ elif norm_type == "batch_norm":
645
+ norm = nn.BatchNorm2d(num_features, eps=eps, affine=elementwise_affine)
646
+ else:
647
+ raise ValueError(f"{norm_type=} is not supported.")
648
+ return norm
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/resnet.py ADDED
@@ -0,0 +1,797 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ # `TemporalConvLayer` Copyright 2024 Alibaba DAMO-VILAB, The ModelScope Team and The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from functools import partial
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+
23
+ from ..utils import deprecate
24
+ from .activations import get_activation
25
+ from .attention_processor import SpatialNorm
26
+ from .downsampling import ( # noqa
27
+ Downsample1D,
28
+ Downsample2D,
29
+ FirDownsample2D,
30
+ KDownsample2D,
31
+ downsample_2d,
32
+ )
33
+ from .normalization import AdaGroupNorm
34
+ from .upsampling import ( # noqa
35
+ FirUpsample2D,
36
+ KUpsample2D,
37
+ Upsample1D,
38
+ Upsample2D,
39
+ upfirdn2d_native,
40
+ upsample_2d,
41
+ )
42
+
43
+
44
+ class ResnetBlockCondNorm2D(nn.Module):
45
+ r"""
46
+ A Resnet block that use normalization layer that incorporate conditioning information.
47
+
48
+ Parameters:
49
+ in_channels (`int`): The number of channels in the input.
50
+ out_channels (`int`, *optional*, default to be `None`):
51
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
52
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
53
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
54
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
55
+ groups_out (`int`, *optional*, default to None):
56
+ The number of groups to use for the second normalization layer. if set to None, same as `groups`.
57
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
58
+ non_linearity (`str`, *optional*, default to `"swish"`): the activation function to use.
59
+ time_embedding_norm (`str`, *optional*, default to `"ada_group"` ):
60
+ The normalization layer for time embedding `temb`. Currently only support "ada_group" or "spatial".
61
+ kernel (`torch.Tensor`, optional, default to None): FIR filter, see
62
+ [`~models.resnet.FirUpsample2D`] and [`~models.resnet.FirDownsample2D`].
63
+ output_scale_factor (`float`, *optional*, default to be `1.0`): the scale factor to use for the output.
64
+ use_in_shortcut (`bool`, *optional*, default to `True`):
65
+ If `True`, add a 1x1 nn.conv2d layer for skip-connection.
66
+ up (`bool`, *optional*, default to `False`): If `True`, add an upsample layer.
67
+ down (`bool`, *optional*, default to `False`): If `True`, add a downsample layer.
68
+ conv_shortcut_bias (`bool`, *optional*, default to `True`): If `True`, adds a learnable bias to the
69
+ `conv_shortcut` output.
70
+ conv_2d_out_channels (`int`, *optional*, default to `None`): the number of channels in the output.
71
+ If None, same as `out_channels`.
72
+ """
73
+
74
+ def __init__(
75
+ self,
76
+ *,
77
+ in_channels: int,
78
+ out_channels: Optional[int] = None,
79
+ conv_shortcut: bool = False,
80
+ dropout: float = 0.0,
81
+ temb_channels: int = 512,
82
+ groups: int = 32,
83
+ groups_out: Optional[int] = None,
84
+ eps: float = 1e-6,
85
+ non_linearity: str = "swish",
86
+ time_embedding_norm: str = "ada_group", # ada_group, spatial
87
+ output_scale_factor: float = 1.0,
88
+ use_in_shortcut: Optional[bool] = None,
89
+ up: bool = False,
90
+ down: bool = False,
91
+ conv_shortcut_bias: bool = True,
92
+ conv_2d_out_channels: Optional[int] = None,
93
+ ):
94
+ super().__init__()
95
+ self.in_channels = in_channels
96
+ out_channels = in_channels if out_channels is None else out_channels
97
+ self.out_channels = out_channels
98
+ self.use_conv_shortcut = conv_shortcut
99
+ self.up = up
100
+ self.down = down
101
+ self.output_scale_factor = output_scale_factor
102
+ self.time_embedding_norm = time_embedding_norm
103
+
104
+ if groups_out is None:
105
+ groups_out = groups
106
+
107
+ if self.time_embedding_norm == "ada_group": # ada_group
108
+ self.norm1 = AdaGroupNorm(temb_channels, in_channels, groups, eps=eps)
109
+ elif self.time_embedding_norm == "spatial":
110
+ self.norm1 = SpatialNorm(in_channels, temb_channels)
111
+ else:
112
+ raise ValueError(f" unsupported time_embedding_norm: {self.time_embedding_norm}")
113
+
114
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
115
+
116
+ if self.time_embedding_norm == "ada_group": # ada_group
117
+ self.norm2 = AdaGroupNorm(temb_channels, out_channels, groups_out, eps=eps)
118
+ elif self.time_embedding_norm == "spatial": # spatial
119
+ self.norm2 = SpatialNorm(out_channels, temb_channels)
120
+ else:
121
+ raise ValueError(f" unsupported time_embedding_norm: {self.time_embedding_norm}")
122
+
123
+ self.dropout = torch.nn.Dropout(dropout)
124
+
125
+ conv_2d_out_channels = conv_2d_out_channels or out_channels
126
+ self.conv2 = nn.Conv2d(out_channels, conv_2d_out_channels, kernel_size=3, stride=1, padding=1)
127
+
128
+ self.nonlinearity = get_activation(non_linearity)
129
+
130
+ self.upsample = self.downsample = None
131
+ if self.up:
132
+ self.upsample = Upsample2D(in_channels, use_conv=False)
133
+ elif self.down:
134
+ self.downsample = Downsample2D(in_channels, use_conv=False, padding=1, name="op")
135
+
136
+ self.use_in_shortcut = self.in_channels != conv_2d_out_channels if use_in_shortcut is None else use_in_shortcut
137
+
138
+ self.conv_shortcut = None
139
+ if self.use_in_shortcut:
140
+ self.conv_shortcut = nn.Conv2d(
141
+ in_channels,
142
+ conv_2d_out_channels,
143
+ kernel_size=1,
144
+ stride=1,
145
+ padding=0,
146
+ bias=conv_shortcut_bias,
147
+ )
148
+
149
+ def forward(self, input_tensor: torch.Tensor, temb: torch.Tensor, *args, **kwargs) -> torch.Tensor:
150
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
151
+ 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`."
152
+ deprecate("scale", "1.0.0", deprecation_message)
153
+
154
+ hidden_states = input_tensor
155
+
156
+ hidden_states = self.norm1(hidden_states, temb)
157
+
158
+ hidden_states = self.nonlinearity(hidden_states)
159
+
160
+ if self.upsample is not None:
161
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
162
+ if hidden_states.shape[0] >= 64:
163
+ input_tensor = input_tensor.contiguous()
164
+ hidden_states = hidden_states.contiguous()
165
+ input_tensor = self.upsample(input_tensor)
166
+ hidden_states = self.upsample(hidden_states)
167
+
168
+ elif self.downsample is not None:
169
+ input_tensor = self.downsample(input_tensor)
170
+ hidden_states = self.downsample(hidden_states)
171
+
172
+ hidden_states = self.conv1(hidden_states)
173
+
174
+ hidden_states = self.norm2(hidden_states, temb)
175
+
176
+ hidden_states = self.nonlinearity(hidden_states)
177
+
178
+ hidden_states = self.dropout(hidden_states)
179
+ hidden_states = self.conv2(hidden_states)
180
+
181
+ if self.conv_shortcut is not None:
182
+ input_tensor = self.conv_shortcut(input_tensor)
183
+
184
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
185
+
186
+ return output_tensor
187
+
188
+
189
+ class ResnetBlock2D(nn.Module):
190
+ r"""
191
+ A Resnet block.
192
+
193
+ Parameters:
194
+ in_channels (`int`): The number of channels in the input.
195
+ out_channels (`int`, *optional*, default to be `None`):
196
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
197
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
198
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
199
+ groups (`int`, *optional*, default to `32`): The number of groups to use for the first normalization layer.
200
+ groups_out (`int`, *optional*, default to None):
201
+ The number of groups to use for the second normalization layer. if set to None, same as `groups`.
202
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
203
+ non_linearity (`str`, *optional*, default to `"swish"`): the activation function to use.
204
+ time_embedding_norm (`str`, *optional*, default to `"default"` ): Time scale shift config.
205
+ By default, apply timestep embedding conditioning with a simple shift mechanism. Choose "scale_shift" for a
206
+ stronger conditioning with scale and shift.
207
+ kernel (`torch.Tensor`, optional, default to None): FIR filter, see
208
+ [`~models.resnet.FirUpsample2D`] and [`~models.resnet.FirDownsample2D`].
209
+ output_scale_factor (`float`, *optional*, default to be `1.0`): the scale factor to use for the output.
210
+ use_in_shortcut (`bool`, *optional*, default to `True`):
211
+ If `True`, add a 1x1 nn.conv2d layer for skip-connection.
212
+ up (`bool`, *optional*, default to `False`): If `True`, add an upsample layer.
213
+ down (`bool`, *optional*, default to `False`): If `True`, add a downsample layer.
214
+ conv_shortcut_bias (`bool`, *optional*, default to `True`): If `True`, adds a learnable bias to the
215
+ `conv_shortcut` output.
216
+ conv_2d_out_channels (`int`, *optional*, default to `None`): the number of channels in the output.
217
+ If None, same as `out_channels`.
218
+ """
219
+
220
+ def __init__(
221
+ self,
222
+ *,
223
+ in_channels: int,
224
+ out_channels: Optional[int] = None,
225
+ conv_shortcut: bool = False,
226
+ dropout: float = 0.0,
227
+ temb_channels: int = 512,
228
+ groups: int = 32,
229
+ groups_out: Optional[int] = None,
230
+ pre_norm: bool = True,
231
+ eps: float = 1e-6,
232
+ non_linearity: str = "swish",
233
+ skip_time_act: bool = False,
234
+ time_embedding_norm: str = "default", # default, scale_shift,
235
+ kernel: Optional[torch.Tensor] = None,
236
+ output_scale_factor: float = 1.0,
237
+ use_in_shortcut: Optional[bool] = None,
238
+ up: bool = False,
239
+ down: bool = False,
240
+ conv_shortcut_bias: bool = True,
241
+ conv_2d_out_channels: Optional[int] = None,
242
+ ):
243
+ super().__init__()
244
+ if time_embedding_norm == "ada_group":
245
+ raise ValueError(
246
+ "This class cannot be used with `time_embedding_norm==ada_group`, please use `ResnetBlockCondNorm2D` instead",
247
+ )
248
+ if time_embedding_norm == "spatial":
249
+ raise ValueError(
250
+ "This class cannot be used with `time_embedding_norm==spatial`, please use `ResnetBlockCondNorm2D` instead",
251
+ )
252
+
253
+ self.pre_norm = True
254
+ self.in_channels = in_channels
255
+ out_channels = in_channels if out_channels is None else out_channels
256
+ self.out_channels = out_channels
257
+ self.use_conv_shortcut = conv_shortcut
258
+ self.up = up
259
+ self.down = down
260
+ self.output_scale_factor = output_scale_factor
261
+ self.time_embedding_norm = time_embedding_norm
262
+ self.skip_time_act = skip_time_act
263
+
264
+ if groups_out is None:
265
+ groups_out = groups
266
+
267
+ self.norm1 = torch.nn.GroupNorm(num_groups=groups, num_channels=in_channels, eps=eps, affine=True)
268
+
269
+ self.conv1 = nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1)
270
+
271
+ if temb_channels is not None:
272
+ if self.time_embedding_norm == "default":
273
+ self.time_emb_proj = nn.Linear(temb_channels, out_channels)
274
+ elif self.time_embedding_norm == "scale_shift":
275
+ self.time_emb_proj = nn.Linear(temb_channels, 2 * out_channels)
276
+ else:
277
+ raise ValueError(f"unknown time_embedding_norm : {self.time_embedding_norm} ")
278
+ else:
279
+ self.time_emb_proj = None
280
+
281
+ self.norm2 = torch.nn.GroupNorm(num_groups=groups_out, num_channels=out_channels, eps=eps, affine=True)
282
+
283
+ self.dropout = torch.nn.Dropout(dropout)
284
+ conv_2d_out_channels = conv_2d_out_channels or out_channels
285
+ self.conv2 = nn.Conv2d(out_channels, conv_2d_out_channels, kernel_size=3, stride=1, padding=1)
286
+
287
+ self.nonlinearity = get_activation(non_linearity)
288
+
289
+ self.upsample = self.downsample = None
290
+ if self.up:
291
+ if kernel == "fir":
292
+ fir_kernel = (1, 3, 3, 1)
293
+ self.upsample = lambda x: upsample_2d(x, kernel=fir_kernel)
294
+ elif kernel == "sde_vp":
295
+ self.upsample = partial(F.interpolate, scale_factor=2.0, mode="nearest")
296
+ else:
297
+ self.upsample = Upsample2D(in_channels, use_conv=False)
298
+ elif self.down:
299
+ if kernel == "fir":
300
+ fir_kernel = (1, 3, 3, 1)
301
+ self.downsample = lambda x: downsample_2d(x, kernel=fir_kernel)
302
+ elif kernel == "sde_vp":
303
+ self.downsample = partial(F.avg_pool2d, kernel_size=2, stride=2)
304
+ else:
305
+ self.downsample = Downsample2D(in_channels, use_conv=False, padding=1, name="op")
306
+
307
+ self.use_in_shortcut = self.in_channels != conv_2d_out_channels if use_in_shortcut is None else use_in_shortcut
308
+
309
+ self.conv_shortcut = None
310
+ if self.use_in_shortcut:
311
+ self.conv_shortcut = nn.Conv2d(
312
+ in_channels,
313
+ conv_2d_out_channels,
314
+ kernel_size=1,
315
+ stride=1,
316
+ padding=0,
317
+ bias=conv_shortcut_bias,
318
+ )
319
+
320
+ def forward(self, input_tensor: torch.Tensor, temb: torch.Tensor, *args, **kwargs) -> torch.Tensor:
321
+ if len(args) > 0 or kwargs.get("scale", None) is not None:
322
+ 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`."
323
+ deprecate("scale", "1.0.0", deprecation_message)
324
+
325
+ hidden_states = input_tensor
326
+
327
+ hidden_states = self.norm1(hidden_states)
328
+ hidden_states = self.nonlinearity(hidden_states)
329
+
330
+ if self.upsample is not None:
331
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
332
+ if hidden_states.shape[0] >= 64:
333
+ input_tensor = input_tensor.contiguous()
334
+ hidden_states = hidden_states.contiguous()
335
+ input_tensor = self.upsample(input_tensor)
336
+ hidden_states = self.upsample(hidden_states)
337
+ elif self.downsample is not None:
338
+ input_tensor = self.downsample(input_tensor)
339
+ hidden_states = self.downsample(hidden_states)
340
+
341
+ hidden_states = self.conv1(hidden_states)
342
+
343
+ if self.time_emb_proj is not None:
344
+ if not self.skip_time_act:
345
+ temb = self.nonlinearity(temb)
346
+ temb = self.time_emb_proj(temb)[:, :, None, None]
347
+
348
+ if self.time_embedding_norm == "default":
349
+ if temb is not None:
350
+ hidden_states = hidden_states + temb
351
+ hidden_states = self.norm2(hidden_states)
352
+ elif self.time_embedding_norm == "scale_shift":
353
+ if temb is None:
354
+ raise ValueError(
355
+ f" `temb` should not be None when `time_embedding_norm` is {self.time_embedding_norm}"
356
+ )
357
+ time_scale, time_shift = torch.chunk(temb, 2, dim=1)
358
+ hidden_states = self.norm2(hidden_states)
359
+ hidden_states = hidden_states * (1 + time_scale) + time_shift
360
+ else:
361
+ hidden_states = self.norm2(hidden_states)
362
+
363
+ hidden_states = self.nonlinearity(hidden_states)
364
+
365
+ hidden_states = self.dropout(hidden_states)
366
+ hidden_states = self.conv2(hidden_states)
367
+
368
+ if self.conv_shortcut is not None:
369
+ input_tensor = self.conv_shortcut(input_tensor.contiguous())
370
+
371
+ output_tensor = (input_tensor + hidden_states) / self.output_scale_factor
372
+
373
+ return output_tensor
374
+
375
+
376
+ # unet_rl.py
377
+ def rearrange_dims(tensor: torch.Tensor) -> torch.Tensor:
378
+ if len(tensor.shape) == 2:
379
+ return tensor[:, :, None]
380
+ if len(tensor.shape) == 3:
381
+ return tensor[:, :, None, :]
382
+ elif len(tensor.shape) == 4:
383
+ return tensor[:, :, 0, :]
384
+ else:
385
+ raise ValueError(f"`len(tensor)`: {len(tensor)} has to be 2, 3 or 4.")
386
+
387
+
388
+ class Conv1dBlock(nn.Module):
389
+ """
390
+ Conv1d --> GroupNorm --> Mish
391
+
392
+ Parameters:
393
+ inp_channels (`int`): Number of input channels.
394
+ out_channels (`int`): Number of output channels.
395
+ kernel_size (`int` or `tuple`): Size of the convolving kernel.
396
+ n_groups (`int`, default `8`): Number of groups to separate the channels into.
397
+ activation (`str`, defaults to `mish`): Name of the activation function.
398
+ """
399
+
400
+ def __init__(
401
+ self,
402
+ inp_channels: int,
403
+ out_channels: int,
404
+ kernel_size: Union[int, Tuple[int, int]],
405
+ n_groups: int = 8,
406
+ activation: str = "mish",
407
+ ):
408
+ super().__init__()
409
+
410
+ self.conv1d = nn.Conv1d(inp_channels, out_channels, kernel_size, padding=kernel_size // 2)
411
+ self.group_norm = nn.GroupNorm(n_groups, out_channels)
412
+ self.mish = get_activation(activation)
413
+
414
+ def forward(self, inputs: torch.Tensor) -> torch.Tensor:
415
+ intermediate_repr = self.conv1d(inputs)
416
+ intermediate_repr = rearrange_dims(intermediate_repr)
417
+ intermediate_repr = self.group_norm(intermediate_repr)
418
+ intermediate_repr = rearrange_dims(intermediate_repr)
419
+ output = self.mish(intermediate_repr)
420
+ return output
421
+
422
+
423
+ # unet_rl.py
424
+ class ResidualTemporalBlock1D(nn.Module):
425
+ """
426
+ Residual 1D block with temporal convolutions.
427
+
428
+ Parameters:
429
+ inp_channels (`int`): Number of input channels.
430
+ out_channels (`int`): Number of output channels.
431
+ embed_dim (`int`): Embedding dimension.
432
+ kernel_size (`int` or `tuple`): Size of the convolving kernel.
433
+ activation (`str`, defaults `mish`): It is possible to choose the right activation function.
434
+ """
435
+
436
+ def __init__(
437
+ self,
438
+ inp_channels: int,
439
+ out_channels: int,
440
+ embed_dim: int,
441
+ kernel_size: Union[int, Tuple[int, int]] = 5,
442
+ activation: str = "mish",
443
+ ):
444
+ super().__init__()
445
+ self.conv_in = Conv1dBlock(inp_channels, out_channels, kernel_size)
446
+ self.conv_out = Conv1dBlock(out_channels, out_channels, kernel_size)
447
+
448
+ self.time_emb_act = get_activation(activation)
449
+ self.time_emb = nn.Linear(embed_dim, out_channels)
450
+
451
+ self.residual_conv = (
452
+ nn.Conv1d(inp_channels, out_channels, 1) if inp_channels != out_channels else nn.Identity()
453
+ )
454
+
455
+ def forward(self, inputs: torch.Tensor, t: torch.Tensor) -> torch.Tensor:
456
+ """
457
+ Args:
458
+ inputs : [ batch_size x inp_channels x horizon ]
459
+ t : [ batch_size x embed_dim ]
460
+
461
+ returns:
462
+ out : [ batch_size x out_channels x horizon ]
463
+ """
464
+ t = self.time_emb_act(t)
465
+ t = self.time_emb(t)
466
+ out = self.conv_in(inputs) + rearrange_dims(t)
467
+ out = self.conv_out(out)
468
+ return out + self.residual_conv(inputs)
469
+
470
+
471
+ class TemporalConvLayer(nn.Module):
472
+ """
473
+ Temporal convolutional layer that can be used for video (sequence of images) input Code mostly copied from:
474
+ https://github.com/modelscope/modelscope/blob/1509fdb973e5871f37148a4b5e5964cafd43e64d/modelscope/models/multi_modal/video_synthesis/unet_sd.py#L1016
475
+
476
+ Parameters:
477
+ in_dim (`int`): Number of input channels.
478
+ out_dim (`int`): Number of output channels.
479
+ dropout (`float`, *optional*, defaults to `0.0`): The dropout probability to use.
480
+ """
481
+
482
+ def __init__(
483
+ self,
484
+ in_dim: int,
485
+ out_dim: Optional[int] = None,
486
+ dropout: float = 0.0,
487
+ norm_num_groups: int = 32,
488
+ ):
489
+ super().__init__()
490
+ out_dim = out_dim or in_dim
491
+ self.in_dim = in_dim
492
+ self.out_dim = out_dim
493
+
494
+ # conv layers
495
+ self.conv1 = nn.Sequential(
496
+ nn.GroupNorm(norm_num_groups, in_dim),
497
+ nn.SiLU(),
498
+ nn.Conv3d(in_dim, out_dim, (3, 1, 1), padding=(1, 0, 0)),
499
+ )
500
+ self.conv2 = nn.Sequential(
501
+ nn.GroupNorm(norm_num_groups, out_dim),
502
+ nn.SiLU(),
503
+ nn.Dropout(dropout),
504
+ nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
505
+ )
506
+ self.conv3 = nn.Sequential(
507
+ nn.GroupNorm(norm_num_groups, out_dim),
508
+ nn.SiLU(),
509
+ nn.Dropout(dropout),
510
+ nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
511
+ )
512
+ self.conv4 = nn.Sequential(
513
+ nn.GroupNorm(norm_num_groups, out_dim),
514
+ nn.SiLU(),
515
+ nn.Dropout(dropout),
516
+ nn.Conv3d(out_dim, in_dim, (3, 1, 1), padding=(1, 0, 0)),
517
+ )
518
+
519
+ # zero out the last layer params,so the conv block is identity
520
+ nn.init.zeros_(self.conv4[-1].weight)
521
+ nn.init.zeros_(self.conv4[-1].bias)
522
+
523
+ def forward(self, hidden_states: torch.Tensor, num_frames: int = 1) -> torch.Tensor:
524
+ hidden_states = (
525
+ hidden_states[None, :].reshape((-1, num_frames) + hidden_states.shape[1:]).permute(0, 2, 1, 3, 4)
526
+ )
527
+
528
+ identity = hidden_states
529
+ hidden_states = self.conv1(hidden_states)
530
+ hidden_states = self.conv2(hidden_states)
531
+ hidden_states = self.conv3(hidden_states)
532
+ hidden_states = self.conv4(hidden_states)
533
+
534
+ hidden_states = identity + hidden_states
535
+
536
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).reshape(
537
+ (hidden_states.shape[0] * hidden_states.shape[2], -1) + hidden_states.shape[3:]
538
+ )
539
+ return hidden_states
540
+
541
+
542
+ class TemporalResnetBlock(nn.Module):
543
+ r"""
544
+ A Resnet block.
545
+
546
+ Parameters:
547
+ in_channels (`int`): The number of channels in the input.
548
+ out_channels (`int`, *optional*, default to be `None`):
549
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
550
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
551
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the normalization.
552
+ """
553
+
554
+ def __init__(
555
+ self,
556
+ in_channels: int,
557
+ out_channels: Optional[int] = None,
558
+ temb_channels: int = 512,
559
+ eps: float = 1e-6,
560
+ ):
561
+ super().__init__()
562
+ self.in_channels = in_channels
563
+ out_channels = in_channels if out_channels is None else out_channels
564
+ self.out_channels = out_channels
565
+
566
+ kernel_size = (3, 1, 1)
567
+ padding = [k // 2 for k in kernel_size]
568
+
569
+ self.norm1 = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=eps, affine=True)
570
+ self.conv1 = nn.Conv3d(
571
+ in_channels,
572
+ out_channels,
573
+ kernel_size=kernel_size,
574
+ stride=1,
575
+ padding=padding,
576
+ )
577
+
578
+ if temb_channels is not None:
579
+ self.time_emb_proj = nn.Linear(temb_channels, out_channels)
580
+ else:
581
+ self.time_emb_proj = None
582
+
583
+ self.norm2 = torch.nn.GroupNorm(num_groups=32, num_channels=out_channels, eps=eps, affine=True)
584
+
585
+ self.dropout = torch.nn.Dropout(0.0)
586
+ self.conv2 = nn.Conv3d(
587
+ out_channels,
588
+ out_channels,
589
+ kernel_size=kernel_size,
590
+ stride=1,
591
+ padding=padding,
592
+ )
593
+
594
+ self.nonlinearity = get_activation("silu")
595
+
596
+ self.use_in_shortcut = self.in_channels != out_channels
597
+
598
+ self.conv_shortcut = None
599
+ if self.use_in_shortcut:
600
+ self.conv_shortcut = nn.Conv3d(
601
+ in_channels,
602
+ out_channels,
603
+ kernel_size=1,
604
+ stride=1,
605
+ padding=0,
606
+ )
607
+
608
+ def forward(self, input_tensor: torch.Tensor, temb: torch.Tensor) -> torch.Tensor:
609
+ hidden_states = input_tensor
610
+
611
+ hidden_states = self.norm1(hidden_states)
612
+ hidden_states = self.nonlinearity(hidden_states)
613
+ hidden_states = self.conv1(hidden_states)
614
+
615
+ if self.time_emb_proj is not None:
616
+ temb = self.nonlinearity(temb)
617
+ temb = self.time_emb_proj(temb)[:, :, :, None, None]
618
+ temb = temb.permute(0, 2, 1, 3, 4)
619
+ hidden_states = hidden_states + temb
620
+
621
+ hidden_states = self.norm2(hidden_states)
622
+ hidden_states = self.nonlinearity(hidden_states)
623
+ hidden_states = self.dropout(hidden_states)
624
+ hidden_states = self.conv2(hidden_states)
625
+
626
+ if self.conv_shortcut is not None:
627
+ input_tensor = self.conv_shortcut(input_tensor)
628
+
629
+ output_tensor = input_tensor + hidden_states
630
+
631
+ return output_tensor
632
+
633
+
634
+ # VideoResBlock
635
+ class SpatioTemporalResBlock(nn.Module):
636
+ r"""
637
+ A SpatioTemporal Resnet block.
638
+
639
+ Parameters:
640
+ in_channels (`int`): The number of channels in the input.
641
+ out_channels (`int`, *optional*, default to be `None`):
642
+ The number of output channels for the first conv2d layer. If None, same as `in_channels`.
643
+ temb_channels (`int`, *optional*, default to `512`): the number of channels in timestep embedding.
644
+ eps (`float`, *optional*, defaults to `1e-6`): The epsilon to use for the spatial resenet.
645
+ temporal_eps (`float`, *optional*, defaults to `eps`): The epsilon to use for the temporal resnet.
646
+ merge_factor (`float`, *optional*, defaults to `0.5`): The merge factor to use for the temporal mixing.
647
+ merge_strategy (`str`, *optional*, defaults to `learned_with_images`):
648
+ The merge strategy to use for the temporal mixing.
649
+ switch_spatial_to_temporal_mix (`bool`, *optional*, defaults to `False`):
650
+ If `True`, switch the spatial and temporal mixing.
651
+ """
652
+
653
+ def __init__(
654
+ self,
655
+ in_channels: int,
656
+ out_channels: Optional[int] = None,
657
+ temb_channels: int = 512,
658
+ eps: float = 1e-6,
659
+ temporal_eps: Optional[float] = None,
660
+ merge_factor: float = 0.5,
661
+ merge_strategy="learned_with_images",
662
+ switch_spatial_to_temporal_mix: bool = False,
663
+ ):
664
+ super().__init__()
665
+
666
+ self.spatial_res_block = ResnetBlock2D(
667
+ in_channels=in_channels,
668
+ out_channels=out_channels,
669
+ temb_channels=temb_channels,
670
+ eps=eps,
671
+ )
672
+
673
+ self.temporal_res_block = TemporalResnetBlock(
674
+ in_channels=out_channels if out_channels is not None else in_channels,
675
+ out_channels=out_channels if out_channels is not None else in_channels,
676
+ temb_channels=temb_channels,
677
+ eps=temporal_eps if temporal_eps is not None else eps,
678
+ )
679
+
680
+ self.time_mixer = AlphaBlender(
681
+ alpha=merge_factor,
682
+ merge_strategy=merge_strategy,
683
+ switch_spatial_to_temporal_mix=switch_spatial_to_temporal_mix,
684
+ )
685
+
686
+ def forward(
687
+ self,
688
+ hidden_states: torch.Tensor,
689
+ temb: Optional[torch.Tensor] = None,
690
+ image_only_indicator: Optional[torch.Tensor] = None,
691
+ ):
692
+ num_frames = image_only_indicator.shape[-1]
693
+ hidden_states = self.spatial_res_block(hidden_states, temb)
694
+
695
+ batch_frames, channels, height, width = hidden_states.shape
696
+ batch_size = batch_frames // num_frames
697
+
698
+ hidden_states_mix = (
699
+ hidden_states[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
700
+ )
701
+ hidden_states = (
702
+ hidden_states[None, :].reshape(batch_size, num_frames, channels, height, width).permute(0, 2, 1, 3, 4)
703
+ )
704
+
705
+ if temb is not None:
706
+ temb = temb.reshape(batch_size, num_frames, -1)
707
+
708
+ hidden_states = self.temporal_res_block(hidden_states, temb)
709
+ hidden_states = self.time_mixer(
710
+ x_spatial=hidden_states_mix,
711
+ x_temporal=hidden_states,
712
+ image_only_indicator=image_only_indicator,
713
+ )
714
+
715
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).reshape(batch_frames, channels, height, width)
716
+ return hidden_states
717
+
718
+
719
+ class AlphaBlender(nn.Module):
720
+ r"""
721
+ A module to blend spatial and temporal features.
722
+
723
+ Parameters:
724
+ alpha (`float`): The initial value of the blending factor.
725
+ merge_strategy (`str`, *optional*, defaults to `learned_with_images`):
726
+ The merge strategy to use for the temporal mixing.
727
+ switch_spatial_to_temporal_mix (`bool`, *optional*, defaults to `False`):
728
+ If `True`, switch the spatial and temporal mixing.
729
+ """
730
+
731
+ strategies = ["learned", "fixed", "learned_with_images"]
732
+
733
+ def __init__(
734
+ self,
735
+ alpha: float,
736
+ merge_strategy: str = "learned_with_images",
737
+ switch_spatial_to_temporal_mix: bool = False,
738
+ ):
739
+ super().__init__()
740
+ self.merge_strategy = merge_strategy
741
+ self.switch_spatial_to_temporal_mix = switch_spatial_to_temporal_mix # For TemporalVAE
742
+
743
+ if merge_strategy not in self.strategies:
744
+ raise ValueError(f"merge_strategy needs to be in {self.strategies}")
745
+
746
+ if self.merge_strategy == "fixed":
747
+ self.register_buffer("mix_factor", torch.Tensor([alpha]))
748
+ elif self.merge_strategy == "learned" or self.merge_strategy == "learned_with_images":
749
+ self.register_parameter("mix_factor", torch.nn.Parameter(torch.Tensor([alpha])))
750
+ else:
751
+ raise ValueError(f"Unknown merge strategy {self.merge_strategy}")
752
+
753
+ def get_alpha(self, image_only_indicator: torch.Tensor, ndims: int) -> torch.Tensor:
754
+ if self.merge_strategy == "fixed":
755
+ alpha = self.mix_factor
756
+
757
+ elif self.merge_strategy == "learned":
758
+ alpha = torch.sigmoid(self.mix_factor)
759
+
760
+ elif self.merge_strategy == "learned_with_images":
761
+ if image_only_indicator is None:
762
+ raise ValueError("Please provide image_only_indicator to use learned_with_images merge strategy")
763
+
764
+ alpha = torch.where(
765
+ image_only_indicator.bool(),
766
+ torch.ones(1, 1, device=image_only_indicator.device),
767
+ torch.sigmoid(self.mix_factor)[..., None],
768
+ )
769
+
770
+ # (batch, channel, frames, height, width)
771
+ if ndims == 5:
772
+ alpha = alpha[:, None, :, None, None]
773
+ # (batch*frames, height*width, channels)
774
+ elif ndims == 3:
775
+ alpha = alpha.reshape(-1)[:, None, None]
776
+ else:
777
+ raise ValueError(f"Unexpected ndims {ndims}. Dimensions should be 3 or 5")
778
+
779
+ else:
780
+ raise NotImplementedError
781
+
782
+ return alpha
783
+
784
+ def forward(
785
+ self,
786
+ x_spatial: torch.Tensor,
787
+ x_temporal: torch.Tensor,
788
+ image_only_indicator: Optional[torch.Tensor] = None,
789
+ ) -> torch.Tensor:
790
+ alpha = self.get_alpha(image_only_indicator, x_spatial.ndim)
791
+ alpha = alpha.to(x_spatial.dtype)
792
+
793
+ if self.switch_spatial_to_temporal_mix:
794
+ alpha = 1.0 - alpha
795
+
796
+ x = alpha * x_spatial + (1.0 - alpha) * x_temporal
797
+ return x
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/resnet_flax.py ADDED
@@ -0,0 +1,124 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import flax.linen as nn
15
+ import jax
16
+ import jax.numpy as jnp
17
+
18
+
19
+ class FlaxUpsample2D(nn.Module):
20
+ out_channels: int
21
+ dtype: jnp.dtype = jnp.float32
22
+
23
+ def setup(self):
24
+ self.conv = nn.Conv(
25
+ self.out_channels,
26
+ kernel_size=(3, 3),
27
+ strides=(1, 1),
28
+ padding=((1, 1), (1, 1)),
29
+ dtype=self.dtype,
30
+ )
31
+
32
+ def __call__(self, hidden_states):
33
+ batch, height, width, channels = hidden_states.shape
34
+ hidden_states = jax.image.resize(
35
+ hidden_states,
36
+ shape=(batch, height * 2, width * 2, channels),
37
+ method="nearest",
38
+ )
39
+ hidden_states = self.conv(hidden_states)
40
+ return hidden_states
41
+
42
+
43
+ class FlaxDownsample2D(nn.Module):
44
+ out_channels: int
45
+ dtype: jnp.dtype = jnp.float32
46
+
47
+ def setup(self):
48
+ self.conv = nn.Conv(
49
+ self.out_channels,
50
+ kernel_size=(3, 3),
51
+ strides=(2, 2),
52
+ padding=((1, 1), (1, 1)), # padding="VALID",
53
+ dtype=self.dtype,
54
+ )
55
+
56
+ def __call__(self, hidden_states):
57
+ # pad = ((0, 0), (0, 1), (0, 1), (0, 0)) # pad height and width dim
58
+ # hidden_states = jnp.pad(hidden_states, pad_width=pad)
59
+ hidden_states = self.conv(hidden_states)
60
+ return hidden_states
61
+
62
+
63
+ class FlaxResnetBlock2D(nn.Module):
64
+ in_channels: int
65
+ out_channels: int = None
66
+ dropout_prob: float = 0.0
67
+ use_nin_shortcut: bool = None
68
+ dtype: jnp.dtype = jnp.float32
69
+
70
+ def setup(self):
71
+ out_channels = self.in_channels if self.out_channels is None else self.out_channels
72
+
73
+ self.norm1 = nn.GroupNorm(num_groups=32, epsilon=1e-5)
74
+ self.conv1 = nn.Conv(
75
+ out_channels,
76
+ kernel_size=(3, 3),
77
+ strides=(1, 1),
78
+ padding=((1, 1), (1, 1)),
79
+ dtype=self.dtype,
80
+ )
81
+
82
+ self.time_emb_proj = nn.Dense(out_channels, dtype=self.dtype)
83
+
84
+ self.norm2 = nn.GroupNorm(num_groups=32, epsilon=1e-5)
85
+ self.dropout = nn.Dropout(self.dropout_prob)
86
+ self.conv2 = nn.Conv(
87
+ out_channels,
88
+ kernel_size=(3, 3),
89
+ strides=(1, 1),
90
+ padding=((1, 1), (1, 1)),
91
+ dtype=self.dtype,
92
+ )
93
+
94
+ use_nin_shortcut = self.in_channels != out_channels if self.use_nin_shortcut is None else self.use_nin_shortcut
95
+
96
+ self.conv_shortcut = None
97
+ if use_nin_shortcut:
98
+ self.conv_shortcut = nn.Conv(
99
+ out_channels,
100
+ kernel_size=(1, 1),
101
+ strides=(1, 1),
102
+ padding="VALID",
103
+ dtype=self.dtype,
104
+ )
105
+
106
+ def __call__(self, hidden_states, temb, deterministic=True):
107
+ residual = hidden_states
108
+ hidden_states = self.norm1(hidden_states)
109
+ hidden_states = nn.swish(hidden_states)
110
+ hidden_states = self.conv1(hidden_states)
111
+
112
+ temb = self.time_emb_proj(nn.swish(temb))
113
+ temb = jnp.expand_dims(jnp.expand_dims(temb, 1), 1)
114
+ hidden_states = hidden_states + temb
115
+
116
+ hidden_states = self.norm2(hidden_states)
117
+ hidden_states = nn.swish(hidden_states)
118
+ hidden_states = self.dropout(hidden_states, deterministic)
119
+ hidden_states = self.conv2(hidden_states)
120
+
121
+ if self.conv_shortcut is not None:
122
+ residual = self.conv_shortcut(residual)
123
+
124
+ return hidden_states + residual
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/__init__.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from ...utils import is_torch_available
2
+
3
+
4
+ if is_torch_available():
5
+ from .auraflow_transformer_2d import AuraFlowTransformer2DModel
6
+ from .cogvideox_transformer_3d import CogVideoXTransformer3DModel
7
+ from .consisid_transformer_3d import ConsisIDTransformer3DModel
8
+ from .dit_transformer_2d import DiTTransformer2DModel
9
+ from .dual_transformer_2d import DualTransformer2DModel
10
+ from .hunyuan_transformer_2d import HunyuanDiT2DModel
11
+ from .latte_transformer_3d import LatteTransformer3DModel
12
+ from .lumina_nextdit2d import LuminaNextDiT2DModel
13
+ from .pixart_transformer_2d import PixArtTransformer2DModel
14
+ from .prior_transformer import PriorTransformer
15
+ from .sana_transformer import SanaTransformer2DModel
16
+ from .stable_audio_transformer import StableAudioDiTModel
17
+ from .t5_film_transformer import T5FilmDecoder
18
+ from .transformer_2d import Transformer2DModel
19
+ from .transformer_allegro import AllegroTransformer3DModel
20
+ from .transformer_cogview3plus import CogView3PlusTransformer2DModel
21
+ from .transformer_cogview4 import CogView4Transformer2DModel
22
+ from .transformer_easyanimate import EasyAnimateTransformer3DModel
23
+ from .transformer_flux import FluxTransformer2DModel
24
+ from .transformer_hidream_image import HiDreamImageTransformer2DModel
25
+ from .transformer_hunyuan_video import HunyuanVideoTransformer3DModel
26
+ from .transformer_ltx import LTXVideoTransformer3DModel
27
+ from .transformer_lumina2 import Lumina2Transformer2DModel
28
+ from .transformer_mochi import MochiTransformer3DModel
29
+ from .transformer_omnigen import OmniGenTransformer2DModel
30
+ from .transformer_sd3 import SD3Transformer2DModel
31
+ from .transformer_temporal import TransformerTemporalModel
32
+ from .transformer_wan import WanTransformer3DModel
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/auraflow_transformer_2d.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 AuraFlow Authors, The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Any, Dict, Optional, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...loaders import FromOriginalModelMixin, PeftAdapterMixin
24
+ from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
25
+ from ...utils.torch_utils import maybe_allow_in_graph
26
+ from ..attention_processor import (
27
+ Attention,
28
+ AttentionProcessor,
29
+ AuraFlowAttnProcessor2_0,
30
+ FusedAuraFlowAttnProcessor2_0,
31
+ )
32
+ from ..embeddings import TimestepEmbedding, Timesteps
33
+ from ..modeling_outputs import Transformer2DModelOutput
34
+ from ..modeling_utils import ModelMixin
35
+ from ..normalization import AdaLayerNormZero, FP32LayerNorm
36
+
37
+
38
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
39
+
40
+
41
+ # Taken from the original aura flow inference code.
42
+ def find_multiple(n: int, k: int) -> int:
43
+ if n % k == 0:
44
+ return n
45
+ return n + k - (n % k)
46
+
47
+
48
+ # Aura Flow patch embed doesn't use convs for projections.
49
+ # Additionally, it uses learned positional embeddings.
50
+ class AuraFlowPatchEmbed(nn.Module):
51
+ def __init__(
52
+ self,
53
+ height=224,
54
+ width=224,
55
+ patch_size=16,
56
+ in_channels=3,
57
+ embed_dim=768,
58
+ pos_embed_max_size=None,
59
+ ):
60
+ super().__init__()
61
+
62
+ self.num_patches = (height // patch_size) * (width // patch_size)
63
+ self.pos_embed_max_size = pos_embed_max_size
64
+
65
+ self.proj = nn.Linear(patch_size * patch_size * in_channels, embed_dim)
66
+ self.pos_embed = nn.Parameter(torch.randn(1, pos_embed_max_size, embed_dim) * 0.1)
67
+
68
+ self.patch_size = patch_size
69
+ self.height, self.width = height // patch_size, width // patch_size
70
+ self.base_size = height // patch_size
71
+
72
+ def pe_selection_index_based_on_dim(self, h, w):
73
+ # select subset of positional embedding based on H, W, where H, W is size of latent
74
+ # PE will be viewed as 2d-grid, and H/p x W/p of the PE will be selected
75
+ # because original input are in flattened format, we have to flatten this 2d grid as well.
76
+ h_p, w_p = h // self.patch_size, w // self.patch_size
77
+ h_max, w_max = int(self.pos_embed_max_size**0.5), int(self.pos_embed_max_size**0.5)
78
+
79
+ # Calculate the top-left corner indices for the centered patch grid
80
+ starth = h_max // 2 - h_p // 2
81
+ startw = w_max // 2 - w_p // 2
82
+
83
+ # Generate the row and column indices for the desired patch grid
84
+ rows = torch.arange(starth, starth + h_p, device=self.pos_embed.device)
85
+ cols = torch.arange(startw, startw + w_p, device=self.pos_embed.device)
86
+
87
+ # Create a 2D grid of indices
88
+ row_indices, col_indices = torch.meshgrid(rows, cols, indexing="ij")
89
+
90
+ # Convert the 2D grid indices to flattened 1D indices
91
+ selected_indices = (row_indices * w_max + col_indices).flatten()
92
+
93
+ return selected_indices
94
+
95
+ def forward(self, latent):
96
+ batch_size, num_channels, height, width = latent.size()
97
+ latent = latent.view(
98
+ batch_size,
99
+ num_channels,
100
+ height // self.patch_size,
101
+ self.patch_size,
102
+ width // self.patch_size,
103
+ self.patch_size,
104
+ )
105
+ latent = latent.permute(0, 2, 4, 1, 3, 5).flatten(-3).flatten(1, 2)
106
+ latent = self.proj(latent)
107
+ pe_index = self.pe_selection_index_based_on_dim(height, width)
108
+ return latent + self.pos_embed[:, pe_index]
109
+
110
+
111
+ # Taken from the original Aura flow inference code.
112
+ # Our feedforward only has GELU but Aura uses SiLU.
113
+ class AuraFlowFeedForward(nn.Module):
114
+ def __init__(self, dim, hidden_dim=None) -> None:
115
+ super().__init__()
116
+ if hidden_dim is None:
117
+ hidden_dim = 4 * dim
118
+
119
+ final_hidden_dim = int(2 * hidden_dim / 3)
120
+ final_hidden_dim = find_multiple(final_hidden_dim, 256)
121
+
122
+ self.linear_1 = nn.Linear(dim, final_hidden_dim, bias=False)
123
+ self.linear_2 = nn.Linear(dim, final_hidden_dim, bias=False)
124
+ self.out_projection = nn.Linear(final_hidden_dim, dim, bias=False)
125
+
126
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
127
+ x = F.silu(self.linear_1(x)) * self.linear_2(x)
128
+ x = self.out_projection(x)
129
+ return x
130
+
131
+
132
+ class AuraFlowPreFinalBlock(nn.Module):
133
+ def __init__(self, embedding_dim: int, conditioning_embedding_dim: int):
134
+ super().__init__()
135
+
136
+ self.silu = nn.SiLU()
137
+ self.linear = nn.Linear(conditioning_embedding_dim, embedding_dim * 2, bias=False)
138
+
139
+ def forward(self, x: torch.Tensor, conditioning_embedding: torch.Tensor) -> torch.Tensor:
140
+ emb = self.linear(self.silu(conditioning_embedding).to(x.dtype))
141
+ scale, shift = torch.chunk(emb, 2, dim=1)
142
+ x = x * (1 + scale)[:, None, :] + shift[:, None, :]
143
+ return x
144
+
145
+
146
+ @maybe_allow_in_graph
147
+ class AuraFlowSingleTransformerBlock(nn.Module):
148
+ """Similar to `AuraFlowJointTransformerBlock` with a single DiT instead of an MMDiT."""
149
+
150
+ def __init__(self, dim, num_attention_heads, attention_head_dim):
151
+ super().__init__()
152
+
153
+ self.norm1 = AdaLayerNormZero(dim, bias=False, norm_type="fp32_layer_norm")
154
+
155
+ processor = AuraFlowAttnProcessor2_0()
156
+ self.attn = Attention(
157
+ query_dim=dim,
158
+ cross_attention_dim=None,
159
+ dim_head=attention_head_dim,
160
+ heads=num_attention_heads,
161
+ qk_norm="fp32_layer_norm",
162
+ out_dim=dim,
163
+ bias=False,
164
+ out_bias=False,
165
+ processor=processor,
166
+ )
167
+
168
+ self.norm2 = FP32LayerNorm(dim, elementwise_affine=False, bias=False)
169
+ self.ff = AuraFlowFeedForward(dim, dim * 4)
170
+
171
+ def forward(
172
+ self,
173
+ hidden_states: torch.FloatTensor,
174
+ temb: torch.FloatTensor,
175
+ attention_kwargs: Optional[Dict[str, Any]] = None,
176
+ ):
177
+ residual = hidden_states
178
+ attention_kwargs = attention_kwargs or {}
179
+
180
+ # Norm + Projection.
181
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
182
+
183
+ # Attention.
184
+ attn_output = self.attn(hidden_states=norm_hidden_states, **attention_kwargs)
185
+
186
+ # Process attention outputs for the `hidden_states`.
187
+ hidden_states = self.norm2(residual + gate_msa.unsqueeze(1) * attn_output)
188
+ hidden_states = hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
189
+ ff_output = self.ff(hidden_states)
190
+ hidden_states = gate_mlp.unsqueeze(1) * ff_output
191
+ hidden_states = residual + hidden_states
192
+
193
+ return hidden_states
194
+
195
+
196
+ @maybe_allow_in_graph
197
+ class AuraFlowJointTransformerBlock(nn.Module):
198
+ r"""
199
+ Transformer block for Aura Flow. Similar to SD3 MMDiT. Differences (non-exhaustive):
200
+
201
+ * QK Norm in the attention blocks
202
+ * No bias in the attention blocks
203
+ * Most LayerNorms are in FP32
204
+
205
+ Parameters:
206
+ dim (`int`): The number of channels in the input and output.
207
+ num_attention_heads (`int`): The number of heads to use for multi-head attention.
208
+ attention_head_dim (`int`): The number of channels in each head.
209
+ is_last (`bool`): Boolean to determine if this is the last block in the model.
210
+ """
211
+
212
+ def __init__(self, dim, num_attention_heads, attention_head_dim):
213
+ super().__init__()
214
+
215
+ self.norm1 = AdaLayerNormZero(dim, bias=False, norm_type="fp32_layer_norm")
216
+ self.norm1_context = AdaLayerNormZero(dim, bias=False, norm_type="fp32_layer_norm")
217
+
218
+ processor = AuraFlowAttnProcessor2_0()
219
+ self.attn = Attention(
220
+ query_dim=dim,
221
+ cross_attention_dim=None,
222
+ added_kv_proj_dim=dim,
223
+ added_proj_bias=False,
224
+ dim_head=attention_head_dim,
225
+ heads=num_attention_heads,
226
+ qk_norm="fp32_layer_norm",
227
+ out_dim=dim,
228
+ bias=False,
229
+ out_bias=False,
230
+ processor=processor,
231
+ context_pre_only=False,
232
+ )
233
+
234
+ self.norm2 = FP32LayerNorm(dim, elementwise_affine=False, bias=False)
235
+ self.ff = AuraFlowFeedForward(dim, dim * 4)
236
+ self.norm2_context = FP32LayerNorm(dim, elementwise_affine=False, bias=False)
237
+ self.ff_context = AuraFlowFeedForward(dim, dim * 4)
238
+
239
+ def forward(
240
+ self,
241
+ hidden_states: torch.FloatTensor,
242
+ encoder_hidden_states: torch.FloatTensor,
243
+ temb: torch.FloatTensor,
244
+ attention_kwargs: Optional[Dict[str, Any]] = None,
245
+ ):
246
+ residual = hidden_states
247
+ residual_context = encoder_hidden_states
248
+ attention_kwargs = attention_kwargs or {}
249
+
250
+ # Norm + Projection.
251
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
252
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
253
+ encoder_hidden_states, emb=temb
254
+ )
255
+
256
+ # Attention.
257
+ attn_output, context_attn_output = self.attn(
258
+ hidden_states=norm_hidden_states,
259
+ encoder_hidden_states=norm_encoder_hidden_states,
260
+ **attention_kwargs,
261
+ )
262
+
263
+ # Process attention outputs for the `hidden_states`.
264
+ hidden_states = self.norm2(residual + gate_msa.unsqueeze(1) * attn_output)
265
+ hidden_states = hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
266
+ hidden_states = gate_mlp.unsqueeze(1) * self.ff(hidden_states)
267
+ hidden_states = residual + hidden_states
268
+
269
+ # Process attention outputs for the `encoder_hidden_states`.
270
+ encoder_hidden_states = self.norm2_context(residual_context + c_gate_msa.unsqueeze(1) * context_attn_output)
271
+ encoder_hidden_states = encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
272
+ encoder_hidden_states = c_gate_mlp.unsqueeze(1) * self.ff_context(encoder_hidden_states)
273
+ encoder_hidden_states = residual_context + encoder_hidden_states
274
+
275
+ return encoder_hidden_states, hidden_states
276
+
277
+
278
+ class AuraFlowTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
279
+ r"""
280
+ A 2D Transformer model as introduced in AuraFlow (https://blog.fal.ai/auraflow/).
281
+
282
+ Parameters:
283
+ sample_size (`int`): The width of the latent images. This is fixed during training since
284
+ it is used to learn a number of position embeddings.
285
+ patch_size (`int`): Patch size to turn the input data into small patches.
286
+ in_channels (`int`, *optional*, defaults to 4): The number of channels in the input.
287
+ num_mmdit_layers (`int`, *optional*, defaults to 4): The number of layers of MMDiT Transformer blocks to use.
288
+ num_single_dit_layers (`int`, *optional*, defaults to 32):
289
+ The number of layers of Transformer blocks to use. These blocks use concatenated image and text
290
+ representations.
291
+ attention_head_dim (`int`, *optional*, defaults to 256): The number of channels in each head.
292
+ num_attention_heads (`int`, *optional*, defaults to 12): The number of heads to use for multi-head attention.
293
+ joint_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
294
+ caption_projection_dim (`int`): Number of dimensions to use when projecting the `encoder_hidden_states`.
295
+ out_channels (`int`, defaults to 4): Number of output channels.
296
+ pos_embed_max_size (`int`, defaults to 1024): Maximum positions to embed from the image latents.
297
+ """
298
+
299
+ _no_split_modules = ["AuraFlowJointTransformerBlock", "AuraFlowSingleTransformerBlock", "AuraFlowPatchEmbed"]
300
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
301
+ _supports_gradient_checkpointing = True
302
+
303
+ @register_to_config
304
+ def __init__(
305
+ self,
306
+ sample_size: int = 64,
307
+ patch_size: int = 2,
308
+ in_channels: int = 4,
309
+ num_mmdit_layers: int = 4,
310
+ num_single_dit_layers: int = 32,
311
+ attention_head_dim: int = 256,
312
+ num_attention_heads: int = 12,
313
+ joint_attention_dim: int = 2048,
314
+ caption_projection_dim: int = 3072,
315
+ out_channels: int = 4,
316
+ pos_embed_max_size: int = 1024,
317
+ ):
318
+ super().__init__()
319
+ default_out_channels = in_channels
320
+ self.out_channels = out_channels if out_channels is not None else default_out_channels
321
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
322
+
323
+ self.pos_embed = AuraFlowPatchEmbed(
324
+ height=self.config.sample_size,
325
+ width=self.config.sample_size,
326
+ patch_size=self.config.patch_size,
327
+ in_channels=self.config.in_channels,
328
+ embed_dim=self.inner_dim,
329
+ pos_embed_max_size=pos_embed_max_size,
330
+ )
331
+
332
+ self.context_embedder = nn.Linear(
333
+ self.config.joint_attention_dim, self.config.caption_projection_dim, bias=False
334
+ )
335
+ self.time_step_embed = Timesteps(num_channels=256, downscale_freq_shift=0, scale=1000, flip_sin_to_cos=True)
336
+ self.time_step_proj = TimestepEmbedding(in_channels=256, time_embed_dim=self.inner_dim)
337
+
338
+ self.joint_transformer_blocks = nn.ModuleList(
339
+ [
340
+ AuraFlowJointTransformerBlock(
341
+ dim=self.inner_dim,
342
+ num_attention_heads=self.config.num_attention_heads,
343
+ attention_head_dim=self.config.attention_head_dim,
344
+ )
345
+ for i in range(self.config.num_mmdit_layers)
346
+ ]
347
+ )
348
+ self.single_transformer_blocks = nn.ModuleList(
349
+ [
350
+ AuraFlowSingleTransformerBlock(
351
+ dim=self.inner_dim,
352
+ num_attention_heads=self.config.num_attention_heads,
353
+ attention_head_dim=self.config.attention_head_dim,
354
+ )
355
+ for _ in range(self.config.num_single_dit_layers)
356
+ ]
357
+ )
358
+
359
+ self.norm_out = AuraFlowPreFinalBlock(self.inner_dim, self.inner_dim)
360
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=False)
361
+
362
+ # https://arxiv.org/abs/2309.16588
363
+ # prevents artifacts in the attention maps
364
+ self.register_tokens = nn.Parameter(torch.randn(1, 8, self.inner_dim) * 0.02)
365
+
366
+ self.gradient_checkpointing = False
367
+
368
+ @property
369
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
370
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
371
+ r"""
372
+ Returns:
373
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
374
+ indexed by its weight name.
375
+ """
376
+ # set recursively
377
+ processors = {}
378
+
379
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
380
+ if hasattr(module, "get_processor"):
381
+ processors[f"{name}.processor"] = module.get_processor()
382
+
383
+ for sub_name, child in module.named_children():
384
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
385
+
386
+ return processors
387
+
388
+ for name, module in self.named_children():
389
+ fn_recursive_add_processors(name, module, processors)
390
+
391
+ return processors
392
+
393
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
394
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
395
+ r"""
396
+ Sets the attention processor to use to compute attention.
397
+
398
+ Parameters:
399
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
400
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
401
+ for **all** `Attention` layers.
402
+
403
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
404
+ processor. This is strongly recommended when setting trainable attention processors.
405
+
406
+ """
407
+ count = len(self.attn_processors.keys())
408
+
409
+ if isinstance(processor, dict) and len(processor) != count:
410
+ raise ValueError(
411
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
412
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
413
+ )
414
+
415
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
416
+ if hasattr(module, "set_processor"):
417
+ if not isinstance(processor, dict):
418
+ module.set_processor(processor)
419
+ else:
420
+ module.set_processor(processor.pop(f"{name}.processor"))
421
+
422
+ for sub_name, child in module.named_children():
423
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
424
+
425
+ for name, module in self.named_children():
426
+ fn_recursive_attn_processor(name, module, processor)
427
+
428
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedAuraFlowAttnProcessor2_0
429
+ def fuse_qkv_projections(self):
430
+ """
431
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
432
+ are fused. For cross-attention modules, key and value projection matrices are fused.
433
+
434
+ <Tip warning={true}>
435
+
436
+ This API is 🧪 experimental.
437
+
438
+ </Tip>
439
+ """
440
+ self.original_attn_processors = None
441
+
442
+ for _, attn_processor in self.attn_processors.items():
443
+ if "Added" in str(attn_processor.__class__.__name__):
444
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
445
+
446
+ self.original_attn_processors = self.attn_processors
447
+
448
+ for module in self.modules():
449
+ if isinstance(module, Attention):
450
+ module.fuse_projections(fuse=True)
451
+
452
+ self.set_attn_processor(FusedAuraFlowAttnProcessor2_0())
453
+
454
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
455
+ def unfuse_qkv_projections(self):
456
+ """Disables the fused QKV projection if enabled.
457
+
458
+ <Tip warning={true}>
459
+
460
+ This API is 🧪 experimental.
461
+
462
+ </Tip>
463
+
464
+ """
465
+ if self.original_attn_processors is not None:
466
+ self.set_attn_processor(self.original_attn_processors)
467
+
468
+ def forward(
469
+ self,
470
+ hidden_states: torch.FloatTensor,
471
+ encoder_hidden_states: torch.FloatTensor = None,
472
+ timestep: torch.LongTensor = None,
473
+ attention_kwargs: Optional[Dict[str, Any]] = None,
474
+ return_dict: bool = True,
475
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
476
+ if attention_kwargs is not None:
477
+ attention_kwargs = attention_kwargs.copy()
478
+ lora_scale = attention_kwargs.pop("scale", 1.0)
479
+ else:
480
+ lora_scale = 1.0
481
+
482
+ if USE_PEFT_BACKEND:
483
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
484
+ scale_lora_layers(self, lora_scale)
485
+ else:
486
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
487
+ logger.warning(
488
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
489
+ )
490
+
491
+ height, width = hidden_states.shape[-2:]
492
+
493
+ # Apply patch embedding, timestep embedding, and project the caption embeddings.
494
+ hidden_states = self.pos_embed(hidden_states) # takes care of adding positional embeddings too.
495
+ temb = self.time_step_embed(timestep).to(dtype=next(self.parameters()).dtype)
496
+ temb = self.time_step_proj(temb)
497
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
498
+ encoder_hidden_states = torch.cat(
499
+ [self.register_tokens.repeat(encoder_hidden_states.size(0), 1, 1), encoder_hidden_states], dim=1
500
+ )
501
+
502
+ # MMDiT blocks.
503
+ for index_block, block in enumerate(self.joint_transformer_blocks):
504
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
505
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
506
+ block,
507
+ hidden_states,
508
+ encoder_hidden_states,
509
+ temb,
510
+ )
511
+
512
+ else:
513
+ encoder_hidden_states, hidden_states = block(
514
+ hidden_states=hidden_states,
515
+ encoder_hidden_states=encoder_hidden_states,
516
+ temb=temb,
517
+ attention_kwargs=attention_kwargs,
518
+ )
519
+
520
+ # Single DiT blocks that combine the `hidden_states` (image) and `encoder_hidden_states` (text)
521
+ if len(self.single_transformer_blocks) > 0:
522
+ encoder_seq_len = encoder_hidden_states.size(1)
523
+ combined_hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
524
+
525
+ for index_block, block in enumerate(self.single_transformer_blocks):
526
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
527
+ combined_hidden_states = self._gradient_checkpointing_func(
528
+ block,
529
+ combined_hidden_states,
530
+ temb,
531
+ )
532
+
533
+ else:
534
+ combined_hidden_states = block(
535
+ hidden_states=combined_hidden_states, temb=temb, attention_kwargs=attention_kwargs
536
+ )
537
+
538
+ hidden_states = combined_hidden_states[:, encoder_seq_len:]
539
+
540
+ hidden_states = self.norm_out(hidden_states, temb)
541
+ hidden_states = self.proj_out(hidden_states)
542
+
543
+ # unpatchify
544
+ patch_size = self.config.patch_size
545
+ out_channels = self.config.out_channels
546
+ height = height // patch_size
547
+ width = width // patch_size
548
+
549
+ hidden_states = hidden_states.reshape(
550
+ shape=(hidden_states.shape[0], height, width, patch_size, patch_size, out_channels)
551
+ )
552
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
553
+ output = hidden_states.reshape(
554
+ shape=(hidden_states.shape[0], out_channels, height * patch_size, width * patch_size)
555
+ )
556
+
557
+ if USE_PEFT_BACKEND:
558
+ # remove `lora_scale` from each PEFT layer
559
+ unscale_lora_layers(self, lora_scale)
560
+
561
+ if not return_dict:
562
+ return (output,)
563
+
564
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/cogvideox_transformer_3d.py ADDED
@@ -0,0 +1,531 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The CogVideoX team, Tsinghua University & ZhipuAI and The HuggingFace Team.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Any, Dict, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...loaders import PeftAdapterMixin
23
+ from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
24
+ from ...utils.torch_utils import maybe_allow_in_graph
25
+ from ..attention import Attention, FeedForward
26
+ from ..attention_processor import AttentionProcessor, CogVideoXAttnProcessor2_0, FusedCogVideoXAttnProcessor2_0
27
+ from ..cache_utils import CacheMixin
28
+ from ..embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps
29
+ from ..modeling_outputs import Transformer2DModelOutput
30
+ from ..modeling_utils import ModelMixin
31
+ from ..normalization import AdaLayerNorm, CogVideoXLayerNormZero
32
+
33
+
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+
37
+ @maybe_allow_in_graph
38
+ class CogVideoXBlock(nn.Module):
39
+ r"""
40
+ Transformer block used in [CogVideoX](https://github.com/THUDM/CogVideo) model.
41
+
42
+ Parameters:
43
+ dim (`int`):
44
+ The number of channels in the input and output.
45
+ num_attention_heads (`int`):
46
+ The number of heads to use for multi-head attention.
47
+ attention_head_dim (`int`):
48
+ The number of channels in each head.
49
+ time_embed_dim (`int`):
50
+ The number of channels in timestep embedding.
51
+ dropout (`float`, defaults to `0.0`):
52
+ The dropout probability to use.
53
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
54
+ Activation function to be used in feed-forward.
55
+ attention_bias (`bool`, defaults to `False`):
56
+ Whether or not to use bias in attention projection layers.
57
+ qk_norm (`bool`, defaults to `True`):
58
+ Whether or not to use normalization after query and key projections in Attention.
59
+ norm_elementwise_affine (`bool`, defaults to `True`):
60
+ Whether to use learnable elementwise affine parameters for normalization.
61
+ norm_eps (`float`, defaults to `1e-5`):
62
+ Epsilon value for normalization layers.
63
+ final_dropout (`bool` defaults to `False`):
64
+ Whether to apply a final dropout after the last feed-forward layer.
65
+ ff_inner_dim (`int`, *optional*, defaults to `None`):
66
+ Custom hidden dimension of Feed-forward layer. If not provided, `4 * dim` is used.
67
+ ff_bias (`bool`, defaults to `True`):
68
+ Whether or not to use bias in Feed-forward layer.
69
+ attention_out_bias (`bool`, defaults to `True`):
70
+ Whether or not to use bias in Attention output projection layer.
71
+ """
72
+
73
+ def __init__(
74
+ self,
75
+ dim: int,
76
+ num_attention_heads: int,
77
+ attention_head_dim: int,
78
+ time_embed_dim: int,
79
+ dropout: float = 0.0,
80
+ activation_fn: str = "gelu-approximate",
81
+ attention_bias: bool = False,
82
+ qk_norm: bool = True,
83
+ norm_elementwise_affine: bool = True,
84
+ norm_eps: float = 1e-5,
85
+ final_dropout: bool = True,
86
+ ff_inner_dim: Optional[int] = None,
87
+ ff_bias: bool = True,
88
+ attention_out_bias: bool = True,
89
+ ):
90
+ super().__init__()
91
+
92
+ # 1. Self Attention
93
+ self.norm1 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
94
+
95
+ self.attn1 = Attention(
96
+ query_dim=dim,
97
+ dim_head=attention_head_dim,
98
+ heads=num_attention_heads,
99
+ qk_norm="layer_norm" if qk_norm else None,
100
+ eps=1e-6,
101
+ bias=attention_bias,
102
+ out_bias=attention_out_bias,
103
+ processor=CogVideoXAttnProcessor2_0(),
104
+ )
105
+
106
+ # 2. Feed Forward
107
+ self.norm2 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
108
+
109
+ self.ff = FeedForward(
110
+ dim,
111
+ dropout=dropout,
112
+ activation_fn=activation_fn,
113
+ final_dropout=final_dropout,
114
+ inner_dim=ff_inner_dim,
115
+ bias=ff_bias,
116
+ )
117
+
118
+ def forward(
119
+ self,
120
+ hidden_states: torch.Tensor,
121
+ encoder_hidden_states: torch.Tensor,
122
+ temb: torch.Tensor,
123
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
124
+ attention_kwargs: Optional[Dict[str, Any]] = None,
125
+ ) -> torch.Tensor:
126
+ text_seq_length = encoder_hidden_states.size(1)
127
+ attention_kwargs = attention_kwargs or {}
128
+
129
+ # norm & modulate
130
+ norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(
131
+ hidden_states, encoder_hidden_states, temb
132
+ )
133
+
134
+ # attention
135
+ attn_hidden_states, attn_encoder_hidden_states = self.attn1(
136
+ hidden_states=norm_hidden_states,
137
+ encoder_hidden_states=norm_encoder_hidden_states,
138
+ image_rotary_emb=image_rotary_emb,
139
+ **attention_kwargs,
140
+ )
141
+
142
+ hidden_states = hidden_states + gate_msa * attn_hidden_states
143
+ encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states
144
+
145
+ # norm & modulate
146
+ norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2(
147
+ hidden_states, encoder_hidden_states, temb
148
+ )
149
+
150
+ # feed-forward
151
+ norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
152
+ ff_output = self.ff(norm_hidden_states)
153
+
154
+ hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:]
155
+ encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length]
156
+
157
+ return hidden_states, encoder_hidden_states
158
+
159
+
160
+ class CogVideoXTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, CacheMixin):
161
+ """
162
+ A Transformer model for video-like data in [CogVideoX](https://github.com/THUDM/CogVideo).
163
+
164
+ Parameters:
165
+ num_attention_heads (`int`, defaults to `30`):
166
+ The number of heads to use for multi-head attention.
167
+ attention_head_dim (`int`, defaults to `64`):
168
+ The number of channels in each head.
169
+ in_channels (`int`, defaults to `16`):
170
+ The number of channels in the input.
171
+ out_channels (`int`, *optional*, defaults to `16`):
172
+ The number of channels in the output.
173
+ flip_sin_to_cos (`bool`, defaults to `True`):
174
+ Whether to flip the sin to cos in the time embedding.
175
+ time_embed_dim (`int`, defaults to `512`):
176
+ Output dimension of timestep embeddings.
177
+ ofs_embed_dim (`int`, defaults to `512`):
178
+ Output dimension of "ofs" embeddings used in CogVideoX-5b-I2B in version 1.5
179
+ text_embed_dim (`int`, defaults to `4096`):
180
+ Input dimension of text embeddings from the text encoder.
181
+ num_layers (`int`, defaults to `30`):
182
+ The number of layers of Transformer blocks to use.
183
+ dropout (`float`, defaults to `0.0`):
184
+ The dropout probability to use.
185
+ attention_bias (`bool`, defaults to `True`):
186
+ Whether to use bias in the attention projection layers.
187
+ sample_width (`int`, defaults to `90`):
188
+ The width of the input latents.
189
+ sample_height (`int`, defaults to `60`):
190
+ The height of the input latents.
191
+ sample_frames (`int`, defaults to `49`):
192
+ The number of frames in the input latents. Note that this parameter was incorrectly initialized to 49
193
+ instead of 13 because CogVideoX processed 13 latent frames at once in its default and recommended settings,
194
+ but cannot be changed to the correct value to ensure backwards compatibility. To create a transformer with
195
+ K latent frames, the correct value to pass here would be: ((K - 1) * temporal_compression_ratio + 1).
196
+ patch_size (`int`, defaults to `2`):
197
+ The size of the patches to use in the patch embedding layer.
198
+ temporal_compression_ratio (`int`, defaults to `4`):
199
+ The compression ratio across the temporal dimension. See documentation for `sample_frames`.
200
+ max_text_seq_length (`int`, defaults to `226`):
201
+ The maximum sequence length of the input text embeddings.
202
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
203
+ Activation function to use in feed-forward.
204
+ timestep_activation_fn (`str`, defaults to `"silu"`):
205
+ Activation function to use when generating the timestep embeddings.
206
+ norm_elementwise_affine (`bool`, defaults to `True`):
207
+ Whether to use elementwise affine in normalization layers.
208
+ norm_eps (`float`, defaults to `1e-5`):
209
+ The epsilon value to use in normalization layers.
210
+ spatial_interpolation_scale (`float`, defaults to `1.875`):
211
+ Scaling factor to apply in 3D positional embeddings across spatial dimensions.
212
+ temporal_interpolation_scale (`float`, defaults to `1.0`):
213
+ Scaling factor to apply in 3D positional embeddings across temporal dimensions.
214
+ """
215
+
216
+ _skip_layerwise_casting_patterns = ["patch_embed", "norm"]
217
+ _supports_gradient_checkpointing = True
218
+ _no_split_modules = ["CogVideoXBlock", "CogVideoXPatchEmbed"]
219
+
220
+ @register_to_config
221
+ def __init__(
222
+ self,
223
+ num_attention_heads: int = 30,
224
+ attention_head_dim: int = 64,
225
+ in_channels: int = 16,
226
+ out_channels: Optional[int] = 16,
227
+ flip_sin_to_cos: bool = True,
228
+ freq_shift: int = 0,
229
+ time_embed_dim: int = 512,
230
+ ofs_embed_dim: Optional[int] = None,
231
+ text_embed_dim: int = 4096,
232
+ num_layers: int = 30,
233
+ dropout: float = 0.0,
234
+ attention_bias: bool = True,
235
+ sample_width: int = 90,
236
+ sample_height: int = 60,
237
+ sample_frames: int = 49,
238
+ patch_size: int = 2,
239
+ patch_size_t: Optional[int] = None,
240
+ temporal_compression_ratio: int = 4,
241
+ max_text_seq_length: int = 226,
242
+ activation_fn: str = "gelu-approximate",
243
+ timestep_activation_fn: str = "silu",
244
+ norm_elementwise_affine: bool = True,
245
+ norm_eps: float = 1e-5,
246
+ spatial_interpolation_scale: float = 1.875,
247
+ temporal_interpolation_scale: float = 1.0,
248
+ use_rotary_positional_embeddings: bool = False,
249
+ use_learned_positional_embeddings: bool = False,
250
+ patch_bias: bool = True,
251
+ ):
252
+ super().__init__()
253
+ inner_dim = num_attention_heads * attention_head_dim
254
+
255
+ if not use_rotary_positional_embeddings and use_learned_positional_embeddings:
256
+ raise ValueError(
257
+ "There are no CogVideoX checkpoints available with disable rotary embeddings and learned positional "
258
+ "embeddings. If you're using a custom model and/or believe this should be supported, please open an "
259
+ "issue at https://github.com/huggingface/diffusers/issues."
260
+ )
261
+
262
+ # 1. Patch embedding
263
+ self.patch_embed = CogVideoXPatchEmbed(
264
+ patch_size=patch_size,
265
+ patch_size_t=patch_size_t,
266
+ in_channels=in_channels,
267
+ embed_dim=inner_dim,
268
+ text_embed_dim=text_embed_dim,
269
+ bias=patch_bias,
270
+ sample_width=sample_width,
271
+ sample_height=sample_height,
272
+ sample_frames=sample_frames,
273
+ temporal_compression_ratio=temporal_compression_ratio,
274
+ max_text_seq_length=max_text_seq_length,
275
+ spatial_interpolation_scale=spatial_interpolation_scale,
276
+ temporal_interpolation_scale=temporal_interpolation_scale,
277
+ use_positional_embeddings=not use_rotary_positional_embeddings,
278
+ use_learned_positional_embeddings=use_learned_positional_embeddings,
279
+ )
280
+ self.embedding_dropout = nn.Dropout(dropout)
281
+
282
+ # 2. Time embeddings and ofs embedding(Only CogVideoX1.5-5B I2V have)
283
+
284
+ self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
285
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
286
+
287
+ self.ofs_proj = None
288
+ self.ofs_embedding = None
289
+ if ofs_embed_dim:
290
+ self.ofs_proj = Timesteps(ofs_embed_dim, flip_sin_to_cos, freq_shift)
291
+ self.ofs_embedding = TimestepEmbedding(
292
+ ofs_embed_dim, ofs_embed_dim, timestep_activation_fn
293
+ ) # same as time embeddings, for ofs
294
+
295
+ # 3. Define spatio-temporal transformers blocks
296
+ self.transformer_blocks = nn.ModuleList(
297
+ [
298
+ CogVideoXBlock(
299
+ dim=inner_dim,
300
+ num_attention_heads=num_attention_heads,
301
+ attention_head_dim=attention_head_dim,
302
+ time_embed_dim=time_embed_dim,
303
+ dropout=dropout,
304
+ activation_fn=activation_fn,
305
+ attention_bias=attention_bias,
306
+ norm_elementwise_affine=norm_elementwise_affine,
307
+ norm_eps=norm_eps,
308
+ )
309
+ for _ in range(num_layers)
310
+ ]
311
+ )
312
+ self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine)
313
+
314
+ # 4. Output blocks
315
+ self.norm_out = AdaLayerNorm(
316
+ embedding_dim=time_embed_dim,
317
+ output_dim=2 * inner_dim,
318
+ norm_elementwise_affine=norm_elementwise_affine,
319
+ norm_eps=norm_eps,
320
+ chunk_dim=1,
321
+ )
322
+
323
+ if patch_size_t is None:
324
+ # For CogVideox 1.0
325
+ output_dim = patch_size * patch_size * out_channels
326
+ else:
327
+ # For CogVideoX 1.5
328
+ output_dim = patch_size * patch_size * patch_size_t * out_channels
329
+
330
+ self.proj_out = nn.Linear(inner_dim, output_dim)
331
+
332
+ self.gradient_checkpointing = False
333
+
334
+ @property
335
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
336
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
337
+ r"""
338
+ Returns:
339
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
340
+ indexed by its weight name.
341
+ """
342
+ # set recursively
343
+ processors = {}
344
+
345
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
346
+ if hasattr(module, "get_processor"):
347
+ processors[f"{name}.processor"] = module.get_processor()
348
+
349
+ for sub_name, child in module.named_children():
350
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
351
+
352
+ return processors
353
+
354
+ for name, module in self.named_children():
355
+ fn_recursive_add_processors(name, module, processors)
356
+
357
+ return processors
358
+
359
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
360
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
361
+ r"""
362
+ Sets the attention processor to use to compute attention.
363
+
364
+ Parameters:
365
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
366
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
367
+ for **all** `Attention` layers.
368
+
369
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
370
+ processor. This is strongly recommended when setting trainable attention processors.
371
+
372
+ """
373
+ count = len(self.attn_processors.keys())
374
+
375
+ if isinstance(processor, dict) and len(processor) != count:
376
+ raise ValueError(
377
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
378
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
379
+ )
380
+
381
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
382
+ if hasattr(module, "set_processor"):
383
+ if not isinstance(processor, dict):
384
+ module.set_processor(processor)
385
+ else:
386
+ module.set_processor(processor.pop(f"{name}.processor"))
387
+
388
+ for sub_name, child in module.named_children():
389
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
390
+
391
+ for name, module in self.named_children():
392
+ fn_recursive_attn_processor(name, module, processor)
393
+
394
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedCogVideoXAttnProcessor2_0
395
+ def fuse_qkv_projections(self):
396
+ """
397
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
398
+ are fused. For cross-attention modules, key and value projection matrices are fused.
399
+
400
+ <Tip warning={true}>
401
+
402
+ This API is 🧪 experimental.
403
+
404
+ </Tip>
405
+ """
406
+ self.original_attn_processors = None
407
+
408
+ for _, attn_processor in self.attn_processors.items():
409
+ if "Added" in str(attn_processor.__class__.__name__):
410
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
411
+
412
+ self.original_attn_processors = self.attn_processors
413
+
414
+ for module in self.modules():
415
+ if isinstance(module, Attention):
416
+ module.fuse_projections(fuse=True)
417
+
418
+ self.set_attn_processor(FusedCogVideoXAttnProcessor2_0())
419
+
420
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
421
+ def unfuse_qkv_projections(self):
422
+ """Disables the fused QKV projection if enabled.
423
+
424
+ <Tip warning={true}>
425
+
426
+ This API is 🧪 experimental.
427
+
428
+ </Tip>
429
+
430
+ """
431
+ if self.original_attn_processors is not None:
432
+ self.set_attn_processor(self.original_attn_processors)
433
+
434
+ def forward(
435
+ self,
436
+ hidden_states: torch.Tensor,
437
+ encoder_hidden_states: torch.Tensor,
438
+ timestep: Union[int, float, torch.LongTensor],
439
+ timestep_cond: Optional[torch.Tensor] = None,
440
+ ofs: Optional[Union[int, float, torch.LongTensor]] = None,
441
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
442
+ attention_kwargs: Optional[Dict[str, Any]] = None,
443
+ return_dict: bool = True,
444
+ ):
445
+ if attention_kwargs is not None:
446
+ attention_kwargs = attention_kwargs.copy()
447
+ lora_scale = attention_kwargs.pop("scale", 1.0)
448
+ else:
449
+ lora_scale = 1.0
450
+
451
+ if USE_PEFT_BACKEND:
452
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
453
+ scale_lora_layers(self, lora_scale)
454
+ else:
455
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
456
+ logger.warning(
457
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
458
+ )
459
+
460
+ batch_size, num_frames, channels, height, width = hidden_states.shape
461
+
462
+ # 1. Time embedding
463
+ timesteps = timestep
464
+ t_emb = self.time_proj(timesteps)
465
+
466
+ # timesteps does not contain any weights and will always return f32 tensors
467
+ # but time_embedding might actually be running in fp16. so we need to cast here.
468
+ # there might be better ways to encapsulate this.
469
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
470
+ emb = self.time_embedding(t_emb, timestep_cond)
471
+
472
+ if self.ofs_embedding is not None:
473
+ ofs_emb = self.ofs_proj(ofs)
474
+ ofs_emb = ofs_emb.to(dtype=hidden_states.dtype)
475
+ ofs_emb = self.ofs_embedding(ofs_emb)
476
+ emb = emb + ofs_emb
477
+
478
+ # 2. Patch embedding
479
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states)
480
+ hidden_states = self.embedding_dropout(hidden_states)
481
+
482
+ text_seq_length = encoder_hidden_states.shape[1]
483
+ encoder_hidden_states = hidden_states[:, :text_seq_length]
484
+ hidden_states = hidden_states[:, text_seq_length:]
485
+
486
+ # 3. Transformer blocks
487
+ for i, block in enumerate(self.transformer_blocks):
488
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
489
+ hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
490
+ block,
491
+ hidden_states,
492
+ encoder_hidden_states,
493
+ emb,
494
+ image_rotary_emb,
495
+ attention_kwargs,
496
+ )
497
+ else:
498
+ hidden_states, encoder_hidden_states = block(
499
+ hidden_states=hidden_states,
500
+ encoder_hidden_states=encoder_hidden_states,
501
+ temb=emb,
502
+ image_rotary_emb=image_rotary_emb,
503
+ attention_kwargs=attention_kwargs,
504
+ )
505
+
506
+ hidden_states = self.norm_final(hidden_states)
507
+
508
+ # 4. Final block
509
+ hidden_states = self.norm_out(hidden_states, temb=emb)
510
+ hidden_states = self.proj_out(hidden_states)
511
+
512
+ # 5. Unpatchify
513
+ p = self.config.patch_size
514
+ p_t = self.config.patch_size_t
515
+
516
+ if p_t is None:
517
+ output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p)
518
+ output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
519
+ else:
520
+ output = hidden_states.reshape(
521
+ batch_size, (num_frames + p_t - 1) // p_t, height // p, width // p, -1, p_t, p, p
522
+ )
523
+ output = output.permute(0, 1, 5, 4, 2, 6, 3, 7).flatten(6, 7).flatten(4, 5).flatten(1, 2)
524
+
525
+ if USE_PEFT_BACKEND:
526
+ # remove `lora_scale` from each PEFT layer
527
+ unscale_lora_layers(self, lora_scale)
528
+
529
+ if not return_dict:
530
+ return (output,)
531
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/consisid_transformer_3d.py ADDED
@@ -0,0 +1,789 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 ConsisID Authors and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ import math
16
+ from typing import Any, Dict, List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ from torch import nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...loaders import PeftAdapterMixin
23
+ from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
24
+ from ...utils.torch_utils import maybe_allow_in_graph
25
+ from ..attention import Attention, FeedForward
26
+ from ..attention_processor import AttentionProcessor, CogVideoXAttnProcessor2_0
27
+ from ..embeddings import CogVideoXPatchEmbed, TimestepEmbedding, Timesteps
28
+ from ..modeling_outputs import Transformer2DModelOutput
29
+ from ..modeling_utils import ModelMixin
30
+ from ..normalization import AdaLayerNorm, CogVideoXLayerNormZero
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+
36
+ class PerceiverAttention(nn.Module):
37
+ def __init__(self, dim: int, dim_head: int = 64, heads: int = 8, kv_dim: Optional[int] = None):
38
+ super().__init__()
39
+
40
+ self.scale = dim_head**-0.5
41
+ self.dim_head = dim_head
42
+ self.heads = heads
43
+ inner_dim = dim_head * heads
44
+
45
+ self.norm1 = nn.LayerNorm(dim if kv_dim is None else kv_dim)
46
+ self.norm2 = nn.LayerNorm(dim)
47
+
48
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
49
+ self.to_kv = nn.Linear(dim if kv_dim is None else kv_dim, inner_dim * 2, bias=False)
50
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
51
+
52
+ def forward(self, image_embeds: torch.Tensor, latents: torch.Tensor) -> torch.Tensor:
53
+ # Apply normalization
54
+ image_embeds = self.norm1(image_embeds)
55
+ latents = self.norm2(latents)
56
+
57
+ batch_size, seq_len, _ = latents.shape # Get batch size and sequence length
58
+
59
+ # Compute query, key, and value matrices
60
+ query = self.to_q(latents)
61
+ kv_input = torch.cat((image_embeds, latents), dim=-2)
62
+ key, value = self.to_kv(kv_input).chunk(2, dim=-1)
63
+
64
+ # Reshape the tensors for multi-head attention
65
+ query = query.reshape(query.size(0), -1, self.heads, self.dim_head).transpose(1, 2)
66
+ key = key.reshape(key.size(0), -1, self.heads, self.dim_head).transpose(1, 2)
67
+ value = value.reshape(value.size(0), -1, self.heads, self.dim_head).transpose(1, 2)
68
+
69
+ # attention
70
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
71
+ weight = (query * scale) @ (key * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
72
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
73
+ output = weight @ value
74
+
75
+ # Reshape and return the final output
76
+ output = output.permute(0, 2, 1, 3).reshape(batch_size, seq_len, -1)
77
+
78
+ return self.to_out(output)
79
+
80
+
81
+ class LocalFacialExtractor(nn.Module):
82
+ def __init__(
83
+ self,
84
+ id_dim: int = 1280,
85
+ vit_dim: int = 1024,
86
+ depth: int = 10,
87
+ dim_head: int = 64,
88
+ heads: int = 16,
89
+ num_id_token: int = 5,
90
+ num_queries: int = 32,
91
+ output_dim: int = 2048,
92
+ ff_mult: int = 4,
93
+ num_scale: int = 5,
94
+ ):
95
+ super().__init__()
96
+
97
+ # Storing identity token and query information
98
+ self.num_id_token = num_id_token
99
+ self.vit_dim = vit_dim
100
+ self.num_queries = num_queries
101
+ assert depth % num_scale == 0
102
+ self.depth = depth // num_scale
103
+ self.num_scale = num_scale
104
+ scale = vit_dim**-0.5
105
+
106
+ # Learnable latent query embeddings
107
+ self.latents = nn.Parameter(torch.randn(1, num_queries, vit_dim) * scale)
108
+ # Projection layer to map the latent output to the desired dimension
109
+ self.proj_out = nn.Parameter(scale * torch.randn(vit_dim, output_dim))
110
+
111
+ # Attention and ConsisIDFeedForward layer stack
112
+ self.layers = nn.ModuleList([])
113
+ for _ in range(depth):
114
+ self.layers.append(
115
+ nn.ModuleList(
116
+ [
117
+ PerceiverAttention(dim=vit_dim, dim_head=dim_head, heads=heads), # Perceiver Attention layer
118
+ nn.Sequential(
119
+ nn.LayerNorm(vit_dim),
120
+ nn.Linear(vit_dim, vit_dim * ff_mult, bias=False),
121
+ nn.GELU(),
122
+ nn.Linear(vit_dim * ff_mult, vit_dim, bias=False),
123
+ ), # ConsisIDFeedForward layer
124
+ ]
125
+ )
126
+ )
127
+
128
+ # Mappings for each of the 5 different ViT features
129
+ for i in range(num_scale):
130
+ setattr(
131
+ self,
132
+ f"mapping_{i}",
133
+ nn.Sequential(
134
+ nn.Linear(vit_dim, vit_dim),
135
+ nn.LayerNorm(vit_dim),
136
+ nn.LeakyReLU(),
137
+ nn.Linear(vit_dim, vit_dim),
138
+ nn.LayerNorm(vit_dim),
139
+ nn.LeakyReLU(),
140
+ nn.Linear(vit_dim, vit_dim),
141
+ ),
142
+ )
143
+
144
+ # Mapping for identity embedding vectors
145
+ self.id_embedding_mapping = nn.Sequential(
146
+ nn.Linear(id_dim, vit_dim),
147
+ nn.LayerNorm(vit_dim),
148
+ nn.LeakyReLU(),
149
+ nn.Linear(vit_dim, vit_dim),
150
+ nn.LayerNorm(vit_dim),
151
+ nn.LeakyReLU(),
152
+ nn.Linear(vit_dim, vit_dim * num_id_token),
153
+ )
154
+
155
+ def forward(self, id_embeds: torch.Tensor, vit_hidden_states: List[torch.Tensor]) -> torch.Tensor:
156
+ # Repeat latent queries for the batch size
157
+ latents = self.latents.repeat(id_embeds.size(0), 1, 1)
158
+
159
+ # Map the identity embedding to tokens
160
+ id_embeds = self.id_embedding_mapping(id_embeds)
161
+ id_embeds = id_embeds.reshape(-1, self.num_id_token, self.vit_dim)
162
+
163
+ # Concatenate identity tokens with the latent queries
164
+ latents = torch.cat((latents, id_embeds), dim=1)
165
+
166
+ # Process each of the num_scale visual feature inputs
167
+ for i in range(self.num_scale):
168
+ vit_feature = getattr(self, f"mapping_{i}")(vit_hidden_states[i])
169
+ ctx_feature = torch.cat((id_embeds, vit_feature), dim=1)
170
+
171
+ # Pass through the PerceiverAttention and ConsisIDFeedForward layers
172
+ for attn, ff in self.layers[i * self.depth : (i + 1) * self.depth]:
173
+ latents = attn(ctx_feature, latents) + latents
174
+ latents = ff(latents) + latents
175
+
176
+ # Retain only the query latents
177
+ latents = latents[:, : self.num_queries]
178
+ # Project the latents to the output dimension
179
+ latents = latents @ self.proj_out
180
+ return latents
181
+
182
+
183
+ class PerceiverCrossAttention(nn.Module):
184
+ def __init__(self, dim: int = 3072, dim_head: int = 128, heads: int = 16, kv_dim: int = 2048):
185
+ super().__init__()
186
+
187
+ self.scale = dim_head**-0.5
188
+ self.dim_head = dim_head
189
+ self.heads = heads
190
+ inner_dim = dim_head * heads
191
+
192
+ # Layer normalization to stabilize training
193
+ self.norm1 = nn.LayerNorm(dim if kv_dim is None else kv_dim)
194
+ self.norm2 = nn.LayerNorm(dim)
195
+
196
+ # Linear transformations to produce queries, keys, and values
197
+ self.to_q = nn.Linear(dim, inner_dim, bias=False)
198
+ self.to_kv = nn.Linear(dim if kv_dim is None else kv_dim, inner_dim * 2, bias=False)
199
+ self.to_out = nn.Linear(inner_dim, dim, bias=False)
200
+
201
+ def forward(self, image_embeds: torch.Tensor, hidden_states: torch.Tensor) -> torch.Tensor:
202
+ # Apply layer normalization to the input image and latent features
203
+ image_embeds = self.norm1(image_embeds)
204
+ hidden_states = self.norm2(hidden_states)
205
+
206
+ batch_size, seq_len, _ = hidden_states.shape
207
+
208
+ # Compute queries, keys, and values
209
+ query = self.to_q(hidden_states)
210
+ key, value = self.to_kv(image_embeds).chunk(2, dim=-1)
211
+
212
+ # Reshape tensors to split into attention heads
213
+ query = query.reshape(query.size(0), -1, self.heads, self.dim_head).transpose(1, 2)
214
+ key = key.reshape(key.size(0), -1, self.heads, self.dim_head).transpose(1, 2)
215
+ value = value.reshape(value.size(0), -1, self.heads, self.dim_head).transpose(1, 2)
216
+
217
+ # Compute attention weights
218
+ scale = 1 / math.sqrt(math.sqrt(self.dim_head))
219
+ weight = (query * scale) @ (key * scale).transpose(-2, -1) # More stable scaling than post-division
220
+ weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
221
+
222
+ # Compute the output via weighted combination of values
223
+ out = weight @ value
224
+
225
+ # Reshape and permute to prepare for final linear transformation
226
+ out = out.permute(0, 2, 1, 3).reshape(batch_size, seq_len, -1)
227
+
228
+ return self.to_out(out)
229
+
230
+
231
+ @maybe_allow_in_graph
232
+ class ConsisIDBlock(nn.Module):
233
+ r"""
234
+ Transformer block used in [ConsisID](https://github.com/PKU-YuanGroup/ConsisID) model.
235
+
236
+ Parameters:
237
+ dim (`int`):
238
+ The number of channels in the input and output.
239
+ num_attention_heads (`int`):
240
+ The number of heads to use for multi-head attention.
241
+ attention_head_dim (`int`):
242
+ The number of channels in each head.
243
+ time_embed_dim (`int`):
244
+ The number of channels in timestep embedding.
245
+ dropout (`float`, defaults to `0.0`):
246
+ The dropout probability to use.
247
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
248
+ Activation function to be used in feed-forward.
249
+ attention_bias (`bool`, defaults to `False`):
250
+ Whether or not to use bias in attention projection layers.
251
+ qk_norm (`bool`, defaults to `True`):
252
+ Whether or not to use normalization after query and key projections in Attention.
253
+ norm_elementwise_affine (`bool`, defaults to `True`):
254
+ Whether to use learnable elementwise affine parameters for normalization.
255
+ norm_eps (`float`, defaults to `1e-5`):
256
+ Epsilon value for normalization layers.
257
+ final_dropout (`bool` defaults to `False`):
258
+ Whether to apply a final dropout after the last feed-forward layer.
259
+ ff_inner_dim (`int`, *optional*, defaults to `None`):
260
+ Custom hidden dimension of Feed-forward layer. If not provided, `4 * dim` is used.
261
+ ff_bias (`bool`, defaults to `True`):
262
+ Whether or not to use bias in Feed-forward layer.
263
+ attention_out_bias (`bool`, defaults to `True`):
264
+ Whether or not to use bias in Attention output projection layer.
265
+ """
266
+
267
+ def __init__(
268
+ self,
269
+ dim: int,
270
+ num_attention_heads: int,
271
+ attention_head_dim: int,
272
+ time_embed_dim: int,
273
+ dropout: float = 0.0,
274
+ activation_fn: str = "gelu-approximate",
275
+ attention_bias: bool = False,
276
+ qk_norm: bool = True,
277
+ norm_elementwise_affine: bool = True,
278
+ norm_eps: float = 1e-5,
279
+ final_dropout: bool = True,
280
+ ff_inner_dim: Optional[int] = None,
281
+ ff_bias: bool = True,
282
+ attention_out_bias: bool = True,
283
+ ):
284
+ super().__init__()
285
+
286
+ # 1. Self Attention
287
+ self.norm1 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
288
+
289
+ self.attn1 = Attention(
290
+ query_dim=dim,
291
+ dim_head=attention_head_dim,
292
+ heads=num_attention_heads,
293
+ qk_norm="layer_norm" if qk_norm else None,
294
+ eps=1e-6,
295
+ bias=attention_bias,
296
+ out_bias=attention_out_bias,
297
+ processor=CogVideoXAttnProcessor2_0(),
298
+ )
299
+
300
+ # 2. Feed Forward
301
+ self.norm2 = CogVideoXLayerNormZero(time_embed_dim, dim, norm_elementwise_affine, norm_eps, bias=True)
302
+
303
+ self.ff = FeedForward(
304
+ dim,
305
+ dropout=dropout,
306
+ activation_fn=activation_fn,
307
+ final_dropout=final_dropout,
308
+ inner_dim=ff_inner_dim,
309
+ bias=ff_bias,
310
+ )
311
+
312
+ def forward(
313
+ self,
314
+ hidden_states: torch.Tensor,
315
+ encoder_hidden_states: torch.Tensor,
316
+ temb: torch.Tensor,
317
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
318
+ ) -> torch.Tensor:
319
+ text_seq_length = encoder_hidden_states.size(1)
320
+
321
+ # norm & modulate
322
+ norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(
323
+ hidden_states, encoder_hidden_states, temb
324
+ )
325
+
326
+ # attention
327
+ attn_hidden_states, attn_encoder_hidden_states = self.attn1(
328
+ hidden_states=norm_hidden_states,
329
+ encoder_hidden_states=norm_encoder_hidden_states,
330
+ image_rotary_emb=image_rotary_emb,
331
+ )
332
+
333
+ hidden_states = hidden_states + gate_msa * attn_hidden_states
334
+ encoder_hidden_states = encoder_hidden_states + enc_gate_msa * attn_encoder_hidden_states
335
+
336
+ # norm & modulate
337
+ norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2(
338
+ hidden_states, encoder_hidden_states, temb
339
+ )
340
+
341
+ # feed-forward
342
+ norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
343
+ ff_output = self.ff(norm_hidden_states)
344
+
345
+ hidden_states = hidden_states + gate_ff * ff_output[:, text_seq_length:]
346
+ encoder_hidden_states = encoder_hidden_states + enc_gate_ff * ff_output[:, :text_seq_length]
347
+
348
+ return hidden_states, encoder_hidden_states
349
+
350
+
351
+ class ConsisIDTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
352
+ """
353
+ A Transformer model for video-like data in [ConsisID](https://github.com/PKU-YuanGroup/ConsisID).
354
+
355
+ Parameters:
356
+ num_attention_heads (`int`, defaults to `30`):
357
+ The number of heads to use for multi-head attention.
358
+ attention_head_dim (`int`, defaults to `64`):
359
+ The number of channels in each head.
360
+ in_channels (`int`, defaults to `16`):
361
+ The number of channels in the input.
362
+ out_channels (`int`, *optional*, defaults to `16`):
363
+ The number of channels in the output.
364
+ flip_sin_to_cos (`bool`, defaults to `True`):
365
+ Whether to flip the sin to cos in the time embedding.
366
+ time_embed_dim (`int`, defaults to `512`):
367
+ Output dimension of timestep embeddings.
368
+ text_embed_dim (`int`, defaults to `4096`):
369
+ Input dimension of text embeddings from the text encoder.
370
+ num_layers (`int`, defaults to `30`):
371
+ The number of layers of Transformer blocks to use.
372
+ dropout (`float`, defaults to `0.0`):
373
+ The dropout probability to use.
374
+ attention_bias (`bool`, defaults to `True`):
375
+ Whether to use bias in the attention projection layers.
376
+ sample_width (`int`, defaults to `90`):
377
+ The width of the input latents.
378
+ sample_height (`int`, defaults to `60`):
379
+ The height of the input latents.
380
+ sample_frames (`int`, defaults to `49`):
381
+ The number of frames in the input latents. Note that this parameter was incorrectly initialized to 49
382
+ instead of 13 because ConsisID processed 13 latent frames at once in its default and recommended settings,
383
+ but cannot be changed to the correct value to ensure backwards compatibility. To create a transformer with
384
+ K latent frames, the correct value to pass here would be: ((K - 1) * temporal_compression_ratio + 1).
385
+ patch_size (`int`, defaults to `2`):
386
+ The size of the patches to use in the patch embedding layer.
387
+ temporal_compression_ratio (`int`, defaults to `4`):
388
+ The compression ratio across the temporal dimension. See documentation for `sample_frames`.
389
+ max_text_seq_length (`int`, defaults to `226`):
390
+ The maximum sequence length of the input text embeddings.
391
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
392
+ Activation function to use in feed-forward.
393
+ timestep_activation_fn (`str`, defaults to `"silu"`):
394
+ Activation function to use when generating the timestep embeddings.
395
+ norm_elementwise_affine (`bool`, defaults to `True`):
396
+ Whether to use elementwise affine in normalization layers.
397
+ norm_eps (`float`, defaults to `1e-5`):
398
+ The epsilon value to use in normalization layers.
399
+ spatial_interpolation_scale (`float`, defaults to `1.875`):
400
+ Scaling factor to apply in 3D positional embeddings across spatial dimensions.
401
+ temporal_interpolation_scale (`float`, defaults to `1.0`):
402
+ Scaling factor to apply in 3D positional embeddings across temporal dimensions.
403
+ is_train_face (`bool`, defaults to `False`):
404
+ Whether to use enable the identity-preserving module during the training process. When set to `True`, the
405
+ model will focus on identity-preserving tasks.
406
+ is_kps (`bool`, defaults to `False`):
407
+ Whether to enable keypoint for global facial extractor. If `True`, keypoints will be in the model.
408
+ cross_attn_interval (`int`, defaults to `2`):
409
+ The interval between cross-attention layers in the Transformer architecture. A larger value may reduce the
410
+ frequency of cross-attention computations, which can help reduce computational overhead.
411
+ cross_attn_dim_head (`int`, optional, defaults to `128`):
412
+ The dimensionality of each attention head in the cross-attention layers of the Transformer architecture. A
413
+ larger value increases the capacity to attend to more complex patterns, but also increases memory and
414
+ computation costs.
415
+ cross_attn_num_heads (`int`, optional, defaults to `16`):
416
+ The number of attention heads in the cross-attention layers. More heads allow for more parallel attention
417
+ mechanisms, capturing diverse relationships between different components of the input, but can also
418
+ increase computational requirements.
419
+ LFE_id_dim (`int`, optional, defaults to `1280`):
420
+ The dimensionality of the identity vector used in the Local Facial Extractor (LFE). This vector represents
421
+ the identity features of a face, which are important for tasks like face recognition and identity
422
+ preservation across different frames.
423
+ LFE_vit_dim (`int`, optional, defaults to `1024`):
424
+ The dimension of the vision transformer (ViT) output used in the Local Facial Extractor (LFE). This value
425
+ dictates the size of the transformer-generated feature vectors that will be processed for facial feature
426
+ extraction.
427
+ LFE_depth (`int`, optional, defaults to `10`):
428
+ The number of layers in the Local Facial Extractor (LFE). Increasing the depth allows the model to capture
429
+ more complex representations of facial features, but also increases the computational load.
430
+ LFE_dim_head (`int`, optional, defaults to `64`):
431
+ The dimensionality of each attention head in the Local Facial Extractor (LFE). This parameter affects how
432
+ finely the model can process and focus on different parts of the facial features during the extraction
433
+ process.
434
+ LFE_num_heads (`int`, optional, defaults to `16`):
435
+ The number of attention heads in the Local Facial Extractor (LFE). More heads can improve the model's
436
+ ability to capture diverse facial features, but at the cost of increased computational complexity.
437
+ LFE_num_id_token (`int`, optional, defaults to `5`):
438
+ The number of identity tokens used in the Local Facial Extractor (LFE). This defines how many
439
+ identity-related tokens the model will process to ensure face identity preservation during feature
440
+ extraction.
441
+ LFE_num_querie (`int`, optional, defaults to `32`):
442
+ The number of query tokens used in the Local Facial Extractor (LFE). These tokens are used to capture
443
+ high-frequency face-related information that aids in accurate facial feature extraction.
444
+ LFE_output_dim (`int`, optional, defaults to `2048`):
445
+ The output dimension of the Local Facial Extractor (LFE). This dimension determines the size of the feature
446
+ vectors produced by the LFE module, which will be used for subsequent tasks such as face recognition or
447
+ tracking.
448
+ LFE_ff_mult (`int`, optional, defaults to `4`):
449
+ The multiplication factor applied to the feed-forward network's hidden layer size in the Local Facial
450
+ Extractor (LFE). A higher value increases the model's capacity to learn more complex facial feature
451
+ transformations, but also increases the computation and memory requirements.
452
+ LFE_num_scale (`int`, optional, defaults to `5`):
453
+ The number of different scales visual feature. A higher value increases the model's capacity to learn more
454
+ complex facial feature transformations, but also increases the computation and memory requirements.
455
+ local_face_scale (`float`, defaults to `1.0`):
456
+ A scaling factor used to adjust the importance of local facial features in the model. This can influence
457
+ how strongly the model focuses on high frequency face-related content.
458
+ """
459
+
460
+ _supports_gradient_checkpointing = True
461
+
462
+ @register_to_config
463
+ def __init__(
464
+ self,
465
+ num_attention_heads: int = 30,
466
+ attention_head_dim: int = 64,
467
+ in_channels: int = 16,
468
+ out_channels: Optional[int] = 16,
469
+ flip_sin_to_cos: bool = True,
470
+ freq_shift: int = 0,
471
+ time_embed_dim: int = 512,
472
+ text_embed_dim: int = 4096,
473
+ num_layers: int = 30,
474
+ dropout: float = 0.0,
475
+ attention_bias: bool = True,
476
+ sample_width: int = 90,
477
+ sample_height: int = 60,
478
+ sample_frames: int = 49,
479
+ patch_size: int = 2,
480
+ temporal_compression_ratio: int = 4,
481
+ max_text_seq_length: int = 226,
482
+ activation_fn: str = "gelu-approximate",
483
+ timestep_activation_fn: str = "silu",
484
+ norm_elementwise_affine: bool = True,
485
+ norm_eps: float = 1e-5,
486
+ spatial_interpolation_scale: float = 1.875,
487
+ temporal_interpolation_scale: float = 1.0,
488
+ use_rotary_positional_embeddings: bool = False,
489
+ use_learned_positional_embeddings: bool = False,
490
+ is_train_face: bool = False,
491
+ is_kps: bool = False,
492
+ cross_attn_interval: int = 2,
493
+ cross_attn_dim_head: int = 128,
494
+ cross_attn_num_heads: int = 16,
495
+ LFE_id_dim: int = 1280,
496
+ LFE_vit_dim: int = 1024,
497
+ LFE_depth: int = 10,
498
+ LFE_dim_head: int = 64,
499
+ LFE_num_heads: int = 16,
500
+ LFE_num_id_token: int = 5,
501
+ LFE_num_querie: int = 32,
502
+ LFE_output_dim: int = 2048,
503
+ LFE_ff_mult: int = 4,
504
+ LFE_num_scale: int = 5,
505
+ local_face_scale: float = 1.0,
506
+ ):
507
+ super().__init__()
508
+ inner_dim = num_attention_heads * attention_head_dim
509
+
510
+ if not use_rotary_positional_embeddings and use_learned_positional_embeddings:
511
+ raise ValueError(
512
+ "There are no ConsisID checkpoints available with disable rotary embeddings and learned positional "
513
+ "embeddings. If you're using a custom model and/or believe this should be supported, please open an "
514
+ "issue at https://github.com/huggingface/diffusers/issues."
515
+ )
516
+
517
+ # 1. Patch embedding
518
+ self.patch_embed = CogVideoXPatchEmbed(
519
+ patch_size=patch_size,
520
+ in_channels=in_channels,
521
+ embed_dim=inner_dim,
522
+ text_embed_dim=text_embed_dim,
523
+ bias=True,
524
+ sample_width=sample_width,
525
+ sample_height=sample_height,
526
+ sample_frames=sample_frames,
527
+ temporal_compression_ratio=temporal_compression_ratio,
528
+ max_text_seq_length=max_text_seq_length,
529
+ spatial_interpolation_scale=spatial_interpolation_scale,
530
+ temporal_interpolation_scale=temporal_interpolation_scale,
531
+ use_positional_embeddings=not use_rotary_positional_embeddings,
532
+ use_learned_positional_embeddings=use_learned_positional_embeddings,
533
+ )
534
+ self.embedding_dropout = nn.Dropout(dropout)
535
+
536
+ # 2. Time embeddings
537
+ self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
538
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
539
+
540
+ # 3. Define spatio-temporal transformers blocks
541
+ self.transformer_blocks = nn.ModuleList(
542
+ [
543
+ ConsisIDBlock(
544
+ dim=inner_dim,
545
+ num_attention_heads=num_attention_heads,
546
+ attention_head_dim=attention_head_dim,
547
+ time_embed_dim=time_embed_dim,
548
+ dropout=dropout,
549
+ activation_fn=activation_fn,
550
+ attention_bias=attention_bias,
551
+ norm_elementwise_affine=norm_elementwise_affine,
552
+ norm_eps=norm_eps,
553
+ )
554
+ for _ in range(num_layers)
555
+ ]
556
+ )
557
+ self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine)
558
+
559
+ # 4. Output blocks
560
+ self.norm_out = AdaLayerNorm(
561
+ embedding_dim=time_embed_dim,
562
+ output_dim=2 * inner_dim,
563
+ norm_elementwise_affine=norm_elementwise_affine,
564
+ norm_eps=norm_eps,
565
+ chunk_dim=1,
566
+ )
567
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels)
568
+
569
+ self.is_train_face = is_train_face
570
+ self.is_kps = is_kps
571
+
572
+ # 5. Define identity-preserving config
573
+ if is_train_face:
574
+ # LFE configs
575
+ self.LFE_id_dim = LFE_id_dim
576
+ self.LFE_vit_dim = LFE_vit_dim
577
+ self.LFE_depth = LFE_depth
578
+ self.LFE_dim_head = LFE_dim_head
579
+ self.LFE_num_heads = LFE_num_heads
580
+ self.LFE_num_id_token = LFE_num_id_token
581
+ self.LFE_num_querie = LFE_num_querie
582
+ self.LFE_output_dim = LFE_output_dim
583
+ self.LFE_ff_mult = LFE_ff_mult
584
+ self.LFE_num_scale = LFE_num_scale
585
+ # cross configs
586
+ self.inner_dim = inner_dim
587
+ self.cross_attn_interval = cross_attn_interval
588
+ self.num_cross_attn = num_layers // cross_attn_interval
589
+ self.cross_attn_dim_head = cross_attn_dim_head
590
+ self.cross_attn_num_heads = cross_attn_num_heads
591
+ self.cross_attn_kv_dim = int(self.inner_dim / 3 * 2)
592
+ self.local_face_scale = local_face_scale
593
+ # face modules
594
+ self._init_face_inputs()
595
+
596
+ self.gradient_checkpointing = False
597
+
598
+ def _init_face_inputs(self):
599
+ self.local_facial_extractor = LocalFacialExtractor(
600
+ id_dim=self.LFE_id_dim,
601
+ vit_dim=self.LFE_vit_dim,
602
+ depth=self.LFE_depth,
603
+ dim_head=self.LFE_dim_head,
604
+ heads=self.LFE_num_heads,
605
+ num_id_token=self.LFE_num_id_token,
606
+ num_queries=self.LFE_num_querie,
607
+ output_dim=self.LFE_output_dim,
608
+ ff_mult=self.LFE_ff_mult,
609
+ num_scale=self.LFE_num_scale,
610
+ )
611
+ self.perceiver_cross_attention = nn.ModuleList(
612
+ [
613
+ PerceiverCrossAttention(
614
+ dim=self.inner_dim,
615
+ dim_head=self.cross_attn_dim_head,
616
+ heads=self.cross_attn_num_heads,
617
+ kv_dim=self.cross_attn_kv_dim,
618
+ )
619
+ for _ in range(self.num_cross_attn)
620
+ ]
621
+ )
622
+
623
+ @property
624
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
625
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
626
+ r"""
627
+ Returns:
628
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
629
+ indexed by its weight name.
630
+ """
631
+ # set recursively
632
+ processors = {}
633
+
634
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
635
+ if hasattr(module, "get_processor"):
636
+ processors[f"{name}.processor"] = module.get_processor()
637
+
638
+ for sub_name, child in module.named_children():
639
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
640
+
641
+ return processors
642
+
643
+ for name, module in self.named_children():
644
+ fn_recursive_add_processors(name, module, processors)
645
+
646
+ return processors
647
+
648
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
649
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
650
+ r"""
651
+ Sets the attention processor to use to compute attention.
652
+
653
+ Parameters:
654
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
655
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
656
+ for **all** `Attention` layers.
657
+
658
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
659
+ processor. This is strongly recommended when setting trainable attention processors.
660
+
661
+ """
662
+ count = len(self.attn_processors.keys())
663
+
664
+ if isinstance(processor, dict) and len(processor) != count:
665
+ raise ValueError(
666
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
667
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
668
+ )
669
+
670
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
671
+ if hasattr(module, "set_processor"):
672
+ if not isinstance(processor, dict):
673
+ module.set_processor(processor)
674
+ else:
675
+ module.set_processor(processor.pop(f"{name}.processor"))
676
+
677
+ for sub_name, child in module.named_children():
678
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
679
+
680
+ for name, module in self.named_children():
681
+ fn_recursive_attn_processor(name, module, processor)
682
+
683
+ def forward(
684
+ self,
685
+ hidden_states: torch.Tensor,
686
+ encoder_hidden_states: torch.Tensor,
687
+ timestep: Union[int, float, torch.LongTensor],
688
+ timestep_cond: Optional[torch.Tensor] = None,
689
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
690
+ attention_kwargs: Optional[Dict[str, Any]] = None,
691
+ id_cond: Optional[torch.Tensor] = None,
692
+ id_vit_hidden: Optional[torch.Tensor] = None,
693
+ return_dict: bool = True,
694
+ ):
695
+ if attention_kwargs is not None:
696
+ attention_kwargs = attention_kwargs.copy()
697
+ lora_scale = attention_kwargs.pop("scale", 1.0)
698
+ else:
699
+ lora_scale = 1.0
700
+
701
+ if USE_PEFT_BACKEND:
702
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
703
+ scale_lora_layers(self, lora_scale)
704
+ else:
705
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
706
+ logger.warning(
707
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
708
+ )
709
+
710
+ # fuse clip and insightface
711
+ valid_face_emb = None
712
+ if self.is_train_face:
713
+ id_cond = id_cond.to(device=hidden_states.device, dtype=hidden_states.dtype)
714
+ id_vit_hidden = [
715
+ tensor.to(device=hidden_states.device, dtype=hidden_states.dtype) for tensor in id_vit_hidden
716
+ ]
717
+ valid_face_emb = self.local_facial_extractor(
718
+ id_cond, id_vit_hidden
719
+ ) # torch.Size([1, 1280]), list[5](torch.Size([1, 577, 1024])) -> torch.Size([1, 32, 2048])
720
+
721
+ batch_size, num_frames, channels, height, width = hidden_states.shape
722
+
723
+ # 1. Time embedding
724
+ timesteps = timestep
725
+ t_emb = self.time_proj(timesteps)
726
+
727
+ # timesteps does not contain any weights and will always return f32 tensors
728
+ # but time_embedding might actually be running in fp16. so we need to cast here.
729
+ # there might be better ways to encapsulate this.
730
+ t_emb = t_emb.to(dtype=hidden_states.dtype)
731
+ emb = self.time_embedding(t_emb, timestep_cond)
732
+
733
+ # 2. Patch embedding
734
+ # torch.Size([1, 226, 4096]) torch.Size([1, 13, 32, 60, 90])
735
+ hidden_states = self.patch_embed(encoder_hidden_states, hidden_states) # torch.Size([1, 17776, 3072])
736
+ hidden_states = self.embedding_dropout(hidden_states) # torch.Size([1, 17776, 3072])
737
+
738
+ text_seq_length = encoder_hidden_states.shape[1]
739
+ encoder_hidden_states = hidden_states[:, :text_seq_length] # torch.Size([1, 226, 3072])
740
+ hidden_states = hidden_states[:, text_seq_length:] # torch.Size([1, 17550, 3072])
741
+
742
+ # 3. Transformer blocks
743
+ ca_idx = 0
744
+ for i, block in enumerate(self.transformer_blocks):
745
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
746
+ hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
747
+ block,
748
+ hidden_states,
749
+ encoder_hidden_states,
750
+ emb,
751
+ image_rotary_emb,
752
+ )
753
+ else:
754
+ hidden_states, encoder_hidden_states = block(
755
+ hidden_states=hidden_states,
756
+ encoder_hidden_states=encoder_hidden_states,
757
+ temb=emb,
758
+ image_rotary_emb=image_rotary_emb,
759
+ )
760
+
761
+ if self.is_train_face:
762
+ if i % self.cross_attn_interval == 0 and valid_face_emb is not None:
763
+ hidden_states = hidden_states + self.local_face_scale * self.perceiver_cross_attention[ca_idx](
764
+ valid_face_emb, hidden_states
765
+ ) # torch.Size([2, 32, 2048]) torch.Size([2, 17550, 3072])
766
+ ca_idx += 1
767
+
768
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
769
+ hidden_states = self.norm_final(hidden_states)
770
+ hidden_states = hidden_states[:, text_seq_length:]
771
+
772
+ # 4. Final block
773
+ hidden_states = self.norm_out(hidden_states, temb=emb)
774
+ hidden_states = self.proj_out(hidden_states)
775
+
776
+ # 5. Unpatchify
777
+ # Note: we use `-1` instead of `channels`:
778
+ # - It is okay to `channels` use for ConsisID (number of input channels is equal to output channels)
779
+ p = self.config.patch_size
780
+ output = hidden_states.reshape(batch_size, num_frames, height // p, width // p, -1, p, p)
781
+ output = output.permute(0, 1, 4, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
782
+
783
+ if USE_PEFT_BACKEND:
784
+ # remove `lora_scale` from each PEFT layer
785
+ unscale_lora_layers(self, lora_scale)
786
+
787
+ if not return_dict:
788
+ return (output,)
789
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/dit_transformer_2d.py ADDED
@@ -0,0 +1,226 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Dict, Optional
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+ from torch import nn
19
+
20
+ from ...configuration_utils import ConfigMixin, register_to_config
21
+ from ...utils import logging
22
+ from ..attention import BasicTransformerBlock
23
+ from ..embeddings import PatchEmbed
24
+ from ..modeling_outputs import Transformer2DModelOutput
25
+ from ..modeling_utils import ModelMixin
26
+
27
+
28
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
29
+
30
+
31
+ class DiTTransformer2DModel(ModelMixin, ConfigMixin):
32
+ r"""
33
+ A 2D Transformer model as introduced in DiT (https://arxiv.org/abs/2212.09748).
34
+
35
+ Parameters:
36
+ num_attention_heads (int, optional, defaults to 16): The number of heads to use for multi-head attention.
37
+ attention_head_dim (int, optional, defaults to 72): The number of channels in each head.
38
+ in_channels (int, defaults to 4): The number of channels in the input.
39
+ out_channels (int, optional):
40
+ The number of channels in the output. Specify this parameter if the output channel number differs from the
41
+ input.
42
+ num_layers (int, optional, defaults to 28): The number of layers of Transformer blocks to use.
43
+ dropout (float, optional, defaults to 0.0): The dropout probability to use within the Transformer blocks.
44
+ norm_num_groups (int, optional, defaults to 32):
45
+ Number of groups for group normalization within Transformer blocks.
46
+ attention_bias (bool, optional, defaults to True):
47
+ Configure if the Transformer blocks' attention should contain a bias parameter.
48
+ sample_size (int, defaults to 32):
49
+ The width of the latent images. This parameter is fixed during training.
50
+ patch_size (int, defaults to 2):
51
+ Size of the patches the model processes, relevant for architectures working on non-sequential data.
52
+ activation_fn (str, optional, defaults to "gelu-approximate"):
53
+ Activation function to use in feed-forward networks within Transformer blocks.
54
+ num_embeds_ada_norm (int, optional, defaults to 1000):
55
+ Number of embeddings for AdaLayerNorm, fixed during training and affects the maximum denoising steps during
56
+ inference.
57
+ upcast_attention (bool, optional, defaults to False):
58
+ If true, upcasts the attention mechanism dimensions for potentially improved performance.
59
+ norm_type (str, optional, defaults to "ada_norm_zero"):
60
+ Specifies the type of normalization used, can be 'ada_norm_zero'.
61
+ norm_elementwise_affine (bool, optional, defaults to False):
62
+ If true, enables element-wise affine parameters in the normalization layers.
63
+ norm_eps (float, optional, defaults to 1e-5):
64
+ A small constant added to the denominator in normalization layers to prevent division by zero.
65
+ """
66
+
67
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
68
+ _supports_gradient_checkpointing = True
69
+ _supports_group_offloading = False
70
+
71
+ @register_to_config
72
+ def __init__(
73
+ self,
74
+ num_attention_heads: int = 16,
75
+ attention_head_dim: int = 72,
76
+ in_channels: int = 4,
77
+ out_channels: Optional[int] = None,
78
+ num_layers: int = 28,
79
+ dropout: float = 0.0,
80
+ norm_num_groups: int = 32,
81
+ attention_bias: bool = True,
82
+ sample_size: int = 32,
83
+ patch_size: int = 2,
84
+ activation_fn: str = "gelu-approximate",
85
+ num_embeds_ada_norm: Optional[int] = 1000,
86
+ upcast_attention: bool = False,
87
+ norm_type: str = "ada_norm_zero",
88
+ norm_elementwise_affine: bool = False,
89
+ norm_eps: float = 1e-5,
90
+ ):
91
+ super().__init__()
92
+
93
+ # Validate inputs.
94
+ if norm_type != "ada_norm_zero":
95
+ raise NotImplementedError(
96
+ f"Forward pass is not implemented when `patch_size` is not None and `norm_type` is '{norm_type}'."
97
+ )
98
+ elif norm_type == "ada_norm_zero" and num_embeds_ada_norm is None:
99
+ raise ValueError(
100
+ f"When using a `patch_size` and this `norm_type` ({norm_type}), `num_embeds_ada_norm` cannot be None."
101
+ )
102
+
103
+ # Set some common variables used across the board.
104
+ self.attention_head_dim = attention_head_dim
105
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
106
+ self.out_channels = in_channels if out_channels is None else out_channels
107
+ self.gradient_checkpointing = False
108
+
109
+ # 2. Initialize the position embedding and transformer blocks.
110
+ self.height = self.config.sample_size
111
+ self.width = self.config.sample_size
112
+
113
+ self.patch_size = self.config.patch_size
114
+ self.pos_embed = PatchEmbed(
115
+ height=self.config.sample_size,
116
+ width=self.config.sample_size,
117
+ patch_size=self.config.patch_size,
118
+ in_channels=self.config.in_channels,
119
+ embed_dim=self.inner_dim,
120
+ )
121
+
122
+ self.transformer_blocks = nn.ModuleList(
123
+ [
124
+ BasicTransformerBlock(
125
+ self.inner_dim,
126
+ self.config.num_attention_heads,
127
+ self.config.attention_head_dim,
128
+ dropout=self.config.dropout,
129
+ activation_fn=self.config.activation_fn,
130
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
131
+ attention_bias=self.config.attention_bias,
132
+ upcast_attention=self.config.upcast_attention,
133
+ norm_type=norm_type,
134
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
135
+ norm_eps=self.config.norm_eps,
136
+ )
137
+ for _ in range(self.config.num_layers)
138
+ ]
139
+ )
140
+
141
+ # 3. Output blocks.
142
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
143
+ self.proj_out_1 = nn.Linear(self.inner_dim, 2 * self.inner_dim)
144
+ self.proj_out_2 = nn.Linear(
145
+ self.inner_dim, self.config.patch_size * self.config.patch_size * self.out_channels
146
+ )
147
+
148
+ def forward(
149
+ self,
150
+ hidden_states: torch.Tensor,
151
+ timestep: Optional[torch.LongTensor] = None,
152
+ class_labels: Optional[torch.LongTensor] = None,
153
+ cross_attention_kwargs: Dict[str, Any] = None,
154
+ return_dict: bool = True,
155
+ ):
156
+ """
157
+ The [`DiTTransformer2DModel`] forward method.
158
+
159
+ Args:
160
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.FloatTensor` of shape `(batch size, channel, height, width)` if continuous):
161
+ Input `hidden_states`.
162
+ timestep ( `torch.LongTensor`, *optional*):
163
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
164
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
165
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
166
+ `AdaLayerZeroNorm`.
167
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
168
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
169
+ `self.processor` in
170
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
171
+ return_dict (`bool`, *optional*, defaults to `True`):
172
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
173
+ tuple.
174
+
175
+ Returns:
176
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
177
+ `tuple` where the first element is the sample tensor.
178
+ """
179
+ # 1. Input
180
+ height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
181
+ hidden_states = self.pos_embed(hidden_states)
182
+
183
+ # 2. Blocks
184
+ for block in self.transformer_blocks:
185
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
186
+ hidden_states = self._gradient_checkpointing_func(
187
+ block,
188
+ hidden_states,
189
+ None,
190
+ None,
191
+ None,
192
+ timestep,
193
+ cross_attention_kwargs,
194
+ class_labels,
195
+ )
196
+ else:
197
+ hidden_states = block(
198
+ hidden_states,
199
+ attention_mask=None,
200
+ encoder_hidden_states=None,
201
+ encoder_attention_mask=None,
202
+ timestep=timestep,
203
+ cross_attention_kwargs=cross_attention_kwargs,
204
+ class_labels=class_labels,
205
+ )
206
+
207
+ # 3. Output
208
+ conditioning = self.transformer_blocks[0].norm1.emb(timestep, class_labels, hidden_dtype=hidden_states.dtype)
209
+ shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
210
+ hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
211
+ hidden_states = self.proj_out_2(hidden_states)
212
+
213
+ # unpatchify
214
+ height = width = int(hidden_states.shape[1] ** 0.5)
215
+ hidden_states = hidden_states.reshape(
216
+ shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
217
+ )
218
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
219
+ output = hidden_states.reshape(
220
+ shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
221
+ )
222
+
223
+ if not return_dict:
224
+ return (output,)
225
+
226
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/dual_transformer_2d.py ADDED
@@ -0,0 +1,156 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Optional
15
+
16
+ from torch import nn
17
+
18
+ from ..modeling_outputs import Transformer2DModelOutput
19
+ from .transformer_2d import Transformer2DModel
20
+
21
+
22
+ class DualTransformer2DModel(nn.Module):
23
+ """
24
+ Dual transformer wrapper that combines two `Transformer2DModel`s for mixed inference.
25
+
26
+ Parameters:
27
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
28
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
29
+ in_channels (`int`, *optional*):
30
+ Pass if the input is continuous. The number of channels in the input and output.
31
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
32
+ dropout (`float`, *optional*, defaults to 0.1): The dropout probability to use.
33
+ cross_attention_dim (`int`, *optional*): The number of encoder_hidden_states dimensions to use.
34
+ sample_size (`int`, *optional*): Pass if the input is discrete. The width of the latent images.
35
+ Note that this is fixed at training time as it is used for learning a number of position embeddings. See
36
+ `ImagePositionalEmbeddings`.
37
+ num_vector_embeds (`int`, *optional*):
38
+ Pass if the input is discrete. The number of classes of the vector embeddings of the latent pixels.
39
+ Includes the class for the masked latent pixel.
40
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
41
+ num_embeds_ada_norm ( `int`, *optional*): Pass if at least one of the norm_layers is `AdaLayerNorm`.
42
+ The number of diffusion steps used during training. Note that this is fixed at training time as it is used
43
+ to learn a number of embeddings that are added to the hidden states. During inference, you can denoise for
44
+ up to but not more than steps than `num_embeds_ada_norm`.
45
+ attention_bias (`bool`, *optional*):
46
+ Configure if the TransformerBlocks' attention should contain a bias parameter.
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ num_attention_heads: int = 16,
52
+ attention_head_dim: int = 88,
53
+ in_channels: Optional[int] = None,
54
+ num_layers: int = 1,
55
+ dropout: float = 0.0,
56
+ norm_num_groups: int = 32,
57
+ cross_attention_dim: Optional[int] = None,
58
+ attention_bias: bool = False,
59
+ sample_size: Optional[int] = None,
60
+ num_vector_embeds: Optional[int] = None,
61
+ activation_fn: str = "geglu",
62
+ num_embeds_ada_norm: Optional[int] = None,
63
+ ):
64
+ super().__init__()
65
+ self.transformers = nn.ModuleList(
66
+ [
67
+ Transformer2DModel(
68
+ num_attention_heads=num_attention_heads,
69
+ attention_head_dim=attention_head_dim,
70
+ in_channels=in_channels,
71
+ num_layers=num_layers,
72
+ dropout=dropout,
73
+ norm_num_groups=norm_num_groups,
74
+ cross_attention_dim=cross_attention_dim,
75
+ attention_bias=attention_bias,
76
+ sample_size=sample_size,
77
+ num_vector_embeds=num_vector_embeds,
78
+ activation_fn=activation_fn,
79
+ num_embeds_ada_norm=num_embeds_ada_norm,
80
+ )
81
+ for _ in range(2)
82
+ ]
83
+ )
84
+
85
+ # Variables that can be set by a pipeline:
86
+
87
+ # The ratio of transformer1 to transformer2's output states to be combined during inference
88
+ self.mix_ratio = 0.5
89
+
90
+ # The shape of `encoder_hidden_states` is expected to be
91
+ # `(batch_size, condition_lengths[0]+condition_lengths[1], num_features)`
92
+ self.condition_lengths = [77, 257]
93
+
94
+ # Which transformer to use to encode which condition.
95
+ # E.g. `(1, 0)` means that we'll use `transformers[1](conditions[0])` and `transformers[0](conditions[1])`
96
+ self.transformer_index_for_condition = [1, 0]
97
+
98
+ def forward(
99
+ self,
100
+ hidden_states,
101
+ encoder_hidden_states,
102
+ timestep=None,
103
+ attention_mask=None,
104
+ cross_attention_kwargs=None,
105
+ return_dict: bool = True,
106
+ ):
107
+ """
108
+ Args:
109
+ hidden_states ( When discrete, `torch.LongTensor` of shape `(batch size, num latent pixels)`.
110
+ When continuous, `torch.Tensor` of shape `(batch size, channel, height, width)`): Input hidden_states.
111
+ encoder_hidden_states ( `torch.LongTensor` of shape `(batch size, encoder_hidden_states dim)`, *optional*):
112
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
113
+ self-attention.
114
+ timestep ( `torch.long`, *optional*):
115
+ Optional timestep to be applied as an embedding in AdaLayerNorm's. Used to indicate denoising step.
116
+ attention_mask (`torch.Tensor`, *optional*):
117
+ Optional attention mask to be applied in Attention.
118
+ cross_attention_kwargs (`dict`, *optional*):
119
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
120
+ `self.processor` in
121
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
122
+ return_dict (`bool`, *optional*, defaults to `True`):
123
+ Whether or not to return a [`models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
124
+ tuple.
125
+
126
+ Returns:
127
+ [`~models.transformers.transformer_2d.Transformer2DModelOutput`] or `tuple`:
128
+ [`~models.transformers.transformer_2d.Transformer2DModelOutput`] if `return_dict` is True, otherwise a
129
+ `tuple`. When returning a tuple, the first element is the sample tensor.
130
+ """
131
+ input_states = hidden_states
132
+
133
+ encoded_states = []
134
+ tokens_start = 0
135
+ # attention_mask is not used yet
136
+ for i in range(2):
137
+ # for each of the two transformers, pass the corresponding condition tokens
138
+ condition_state = encoder_hidden_states[:, tokens_start : tokens_start + self.condition_lengths[i]]
139
+ transformer_index = self.transformer_index_for_condition[i]
140
+ encoded_state = self.transformers[transformer_index](
141
+ input_states,
142
+ encoder_hidden_states=condition_state,
143
+ timestep=timestep,
144
+ cross_attention_kwargs=cross_attention_kwargs,
145
+ return_dict=False,
146
+ )[0]
147
+ encoded_states.append(encoded_state - input_states)
148
+ tokens_start += self.condition_lengths[i]
149
+
150
+ output_states = encoded_states[0] * self.mix_ratio + encoded_states[1] * (1 - self.mix_ratio)
151
+ output_states = output_states + input_states
152
+
153
+ if not return_dict:
154
+ return (output_states,)
155
+
156
+ return Transformer2DModelOutput(sample=output_states)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/hunyuan_transformer_2d.py ADDED
@@ -0,0 +1,579 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 HunyuanDiT Authors, Qixun Wang and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Dict, Optional, Union
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ...configuration_utils import ConfigMixin, register_to_config
20
+ from ...utils import logging
21
+ from ...utils.torch_utils import maybe_allow_in_graph
22
+ from ..attention import FeedForward
23
+ from ..attention_processor import Attention, AttentionProcessor, FusedHunyuanAttnProcessor2_0, HunyuanAttnProcessor2_0
24
+ from ..embeddings import (
25
+ HunyuanCombinedTimestepTextSizeStyleEmbedding,
26
+ PatchEmbed,
27
+ PixArtAlphaTextProjection,
28
+ )
29
+ from ..modeling_outputs import Transformer2DModelOutput
30
+ from ..modeling_utils import ModelMixin
31
+ from ..normalization import AdaLayerNormContinuous, FP32LayerNorm
32
+
33
+
34
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
35
+
36
+
37
+ class AdaLayerNormShift(nn.Module):
38
+ r"""
39
+ Norm layer modified to incorporate timestep embeddings.
40
+
41
+ Parameters:
42
+ embedding_dim (`int`): The size of each embedding vector.
43
+ num_embeddings (`int`): The size of the embeddings dictionary.
44
+ """
45
+
46
+ def __init__(self, embedding_dim: int, elementwise_affine=True, eps=1e-6):
47
+ super().__init__()
48
+ self.silu = nn.SiLU()
49
+ self.linear = nn.Linear(embedding_dim, embedding_dim)
50
+ self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=elementwise_affine, eps=eps)
51
+
52
+ def forward(self, x: torch.Tensor, emb: torch.Tensor) -> torch.Tensor:
53
+ shift = self.linear(self.silu(emb.to(torch.float32)).to(emb.dtype))
54
+ x = self.norm(x) + shift.unsqueeze(dim=1)
55
+ return x
56
+
57
+
58
+ @maybe_allow_in_graph
59
+ class HunyuanDiTBlock(nn.Module):
60
+ r"""
61
+ Transformer block used in Hunyuan-DiT model (https://github.com/Tencent/HunyuanDiT). Allow skip connection and
62
+ QKNorm
63
+
64
+ Parameters:
65
+ dim (`int`):
66
+ The number of channels in the input and output.
67
+ num_attention_heads (`int`):
68
+ The number of headsto use for multi-head attention.
69
+ cross_attention_dim (`int`,*optional*):
70
+ The size of the encoder_hidden_states vector for cross attention.
71
+ dropout(`float`, *optional*, defaults to 0.0):
72
+ The dropout probability to use.
73
+ activation_fn (`str`,*optional*, defaults to `"geglu"`):
74
+ Activation function to be used in feed-forward. .
75
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
76
+ Whether to use learnable elementwise affine parameters for normalization.
77
+ norm_eps (`float`, *optional*, defaults to 1e-6):
78
+ A small constant added to the denominator in normalization layers to prevent division by zero.
79
+ final_dropout (`bool` *optional*, defaults to False):
80
+ Whether to apply a final dropout after the last feed-forward layer.
81
+ ff_inner_dim (`int`, *optional*):
82
+ The size of the hidden layer in the feed-forward block. Defaults to `None`.
83
+ ff_bias (`bool`, *optional*, defaults to `True`):
84
+ Whether to use bias in the feed-forward block.
85
+ skip (`bool`, *optional*, defaults to `False`):
86
+ Whether to use skip connection. Defaults to `False` for down-blocks and mid-blocks.
87
+ qk_norm (`bool`, *optional*, defaults to `True`):
88
+ Whether to use normalization in QK calculation. Defaults to `True`.
89
+ """
90
+
91
+ def __init__(
92
+ self,
93
+ dim: int,
94
+ num_attention_heads: int,
95
+ cross_attention_dim: int = 1024,
96
+ dropout=0.0,
97
+ activation_fn: str = "geglu",
98
+ norm_elementwise_affine: bool = True,
99
+ norm_eps: float = 1e-6,
100
+ final_dropout: bool = False,
101
+ ff_inner_dim: Optional[int] = None,
102
+ ff_bias: bool = True,
103
+ skip: bool = False,
104
+ qk_norm: bool = True,
105
+ ):
106
+ super().__init__()
107
+
108
+ # Define 3 blocks. Each block has its own normalization layer.
109
+ # NOTE: when new version comes, check norm2 and norm 3
110
+ # 1. Self-Attn
111
+ self.norm1 = AdaLayerNormShift(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
112
+
113
+ self.attn1 = Attention(
114
+ query_dim=dim,
115
+ cross_attention_dim=None,
116
+ dim_head=dim // num_attention_heads,
117
+ heads=num_attention_heads,
118
+ qk_norm="layer_norm" if qk_norm else None,
119
+ eps=1e-6,
120
+ bias=True,
121
+ processor=HunyuanAttnProcessor2_0(),
122
+ )
123
+
124
+ # 2. Cross-Attn
125
+ self.norm2 = FP32LayerNorm(dim, norm_eps, norm_elementwise_affine)
126
+
127
+ self.attn2 = Attention(
128
+ query_dim=dim,
129
+ cross_attention_dim=cross_attention_dim,
130
+ dim_head=dim // num_attention_heads,
131
+ heads=num_attention_heads,
132
+ qk_norm="layer_norm" if qk_norm else None,
133
+ eps=1e-6,
134
+ bias=True,
135
+ processor=HunyuanAttnProcessor2_0(),
136
+ )
137
+ # 3. Feed-forward
138
+ self.norm3 = FP32LayerNorm(dim, norm_eps, norm_elementwise_affine)
139
+
140
+ self.ff = FeedForward(
141
+ dim,
142
+ dropout=dropout, ### 0.0
143
+ activation_fn=activation_fn, ### approx GeLU
144
+ final_dropout=final_dropout, ### 0.0
145
+ inner_dim=ff_inner_dim, ### int(dim * mlp_ratio)
146
+ bias=ff_bias,
147
+ )
148
+
149
+ # 4. Skip Connection
150
+ if skip:
151
+ self.skip_norm = FP32LayerNorm(2 * dim, norm_eps, elementwise_affine=True)
152
+ self.skip_linear = nn.Linear(2 * dim, dim)
153
+ else:
154
+ self.skip_linear = None
155
+
156
+ # let chunk size default to None
157
+ self._chunk_size = None
158
+ self._chunk_dim = 0
159
+
160
+ # Copied from diffusers.models.attention.BasicTransformerBlock.set_chunk_feed_forward
161
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
162
+ # Sets chunk feed-forward
163
+ self._chunk_size = chunk_size
164
+ self._chunk_dim = dim
165
+
166
+ def forward(
167
+ self,
168
+ hidden_states: torch.Tensor,
169
+ encoder_hidden_states: Optional[torch.Tensor] = None,
170
+ temb: Optional[torch.Tensor] = None,
171
+ image_rotary_emb=None,
172
+ skip=None,
173
+ ) -> torch.Tensor:
174
+ # Notice that normalization is always applied before the real computation in the following blocks.
175
+ # 0. Long Skip Connection
176
+ if self.skip_linear is not None:
177
+ cat = torch.cat([hidden_states, skip], dim=-1)
178
+ cat = self.skip_norm(cat)
179
+ hidden_states = self.skip_linear(cat)
180
+
181
+ # 1. Self-Attention
182
+ norm_hidden_states = self.norm1(hidden_states, temb) ### checked: self.norm1 is correct
183
+ attn_output = self.attn1(
184
+ norm_hidden_states,
185
+ image_rotary_emb=image_rotary_emb,
186
+ )
187
+ hidden_states = hidden_states + attn_output
188
+
189
+ # 2. Cross-Attention
190
+ hidden_states = hidden_states + self.attn2(
191
+ self.norm2(hidden_states),
192
+ encoder_hidden_states=encoder_hidden_states,
193
+ image_rotary_emb=image_rotary_emb,
194
+ )
195
+
196
+ # FFN Layer ### TODO: switch norm2 and norm3 in the state dict
197
+ mlp_inputs = self.norm3(hidden_states)
198
+ hidden_states = hidden_states + self.ff(mlp_inputs)
199
+
200
+ return hidden_states
201
+
202
+
203
+ class HunyuanDiT2DModel(ModelMixin, ConfigMixin):
204
+ """
205
+ HunYuanDiT: Diffusion model with a Transformer backbone.
206
+
207
+ Inherit ModelMixin and ConfigMixin to be compatible with the sampler StableDiffusionPipeline of diffusers.
208
+
209
+ Parameters:
210
+ num_attention_heads (`int`, *optional*, defaults to 16):
211
+ The number of heads to use for multi-head attention.
212
+ attention_head_dim (`int`, *optional*, defaults to 88):
213
+ The number of channels in each head.
214
+ in_channels (`int`, *optional*):
215
+ The number of channels in the input and output (specify if the input is **continuous**).
216
+ patch_size (`int`, *optional*):
217
+ The size of the patch to use for the input.
218
+ activation_fn (`str`, *optional*, defaults to `"geglu"`):
219
+ Activation function to use in feed-forward.
220
+ sample_size (`int`, *optional*):
221
+ The width of the latent images. This is fixed during training since it is used to learn a number of
222
+ position embeddings.
223
+ dropout (`float`, *optional*, defaults to 0.0):
224
+ The dropout probability to use.
225
+ cross_attention_dim (`int`, *optional*):
226
+ The number of dimension in the clip text embedding.
227
+ hidden_size (`int`, *optional*):
228
+ The size of hidden layer in the conditioning embedding layers.
229
+ num_layers (`int`, *optional*, defaults to 1):
230
+ The number of layers of Transformer blocks to use.
231
+ mlp_ratio (`float`, *optional*, defaults to 4.0):
232
+ The ratio of the hidden layer size to the input size.
233
+ learn_sigma (`bool`, *optional*, defaults to `True`):
234
+ Whether to predict variance.
235
+ cross_attention_dim_t5 (`int`, *optional*):
236
+ The number dimensions in t5 text embedding.
237
+ pooled_projection_dim (`int`, *optional*):
238
+ The size of the pooled projection.
239
+ text_len (`int`, *optional*):
240
+ The length of the clip text embedding.
241
+ text_len_t5 (`int`, *optional*):
242
+ The length of the T5 text embedding.
243
+ use_style_cond_and_image_meta_size (`bool`, *optional*):
244
+ Whether or not to use style condition and image meta size. True for version <=1.1, False for version >= 1.2
245
+ """
246
+
247
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm", "pooler"]
248
+ _supports_group_offloading = False
249
+
250
+ @register_to_config
251
+ def __init__(
252
+ self,
253
+ num_attention_heads: int = 16,
254
+ attention_head_dim: int = 88,
255
+ in_channels: Optional[int] = None,
256
+ patch_size: Optional[int] = None,
257
+ activation_fn: str = "gelu-approximate",
258
+ sample_size=32,
259
+ hidden_size=1152,
260
+ num_layers: int = 28,
261
+ mlp_ratio: float = 4.0,
262
+ learn_sigma: bool = True,
263
+ cross_attention_dim: int = 1024,
264
+ norm_type: str = "layer_norm",
265
+ cross_attention_dim_t5: int = 2048,
266
+ pooled_projection_dim: int = 1024,
267
+ text_len: int = 77,
268
+ text_len_t5: int = 256,
269
+ use_style_cond_and_image_meta_size: bool = True,
270
+ ):
271
+ super().__init__()
272
+ self.out_channels = in_channels * 2 if learn_sigma else in_channels
273
+ self.num_heads = num_attention_heads
274
+ self.inner_dim = num_attention_heads * attention_head_dim
275
+
276
+ self.text_embedder = PixArtAlphaTextProjection(
277
+ in_features=cross_attention_dim_t5,
278
+ hidden_size=cross_attention_dim_t5 * 4,
279
+ out_features=cross_attention_dim,
280
+ act_fn="silu_fp32",
281
+ )
282
+
283
+ self.text_embedding_padding = nn.Parameter(torch.randn(text_len + text_len_t5, cross_attention_dim))
284
+
285
+ self.pos_embed = PatchEmbed(
286
+ height=sample_size,
287
+ width=sample_size,
288
+ in_channels=in_channels,
289
+ embed_dim=hidden_size,
290
+ patch_size=patch_size,
291
+ pos_embed_type=None,
292
+ )
293
+
294
+ self.time_extra_emb = HunyuanCombinedTimestepTextSizeStyleEmbedding(
295
+ hidden_size,
296
+ pooled_projection_dim=pooled_projection_dim,
297
+ seq_len=text_len_t5,
298
+ cross_attention_dim=cross_attention_dim_t5,
299
+ use_style_cond_and_image_meta_size=use_style_cond_and_image_meta_size,
300
+ )
301
+
302
+ # HunyuanDiT Blocks
303
+ self.blocks = nn.ModuleList(
304
+ [
305
+ HunyuanDiTBlock(
306
+ dim=self.inner_dim,
307
+ num_attention_heads=self.config.num_attention_heads,
308
+ activation_fn=activation_fn,
309
+ ff_inner_dim=int(self.inner_dim * mlp_ratio),
310
+ cross_attention_dim=cross_attention_dim,
311
+ qk_norm=True, # See http://arxiv.org/abs/2302.05442 for details.
312
+ skip=layer > num_layers // 2,
313
+ )
314
+ for layer in range(num_layers)
315
+ ]
316
+ )
317
+
318
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
319
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
320
+
321
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedHunyuanAttnProcessor2_0
322
+ def fuse_qkv_projections(self):
323
+ """
324
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
325
+ are fused. For cross-attention modules, key and value projection matrices are fused.
326
+
327
+ <Tip warning={true}>
328
+
329
+ This API is 🧪 experimental.
330
+
331
+ </Tip>
332
+ """
333
+ self.original_attn_processors = None
334
+
335
+ for _, attn_processor in self.attn_processors.items():
336
+ if "Added" in str(attn_processor.__class__.__name__):
337
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
338
+
339
+ self.original_attn_processors = self.attn_processors
340
+
341
+ for module in self.modules():
342
+ if isinstance(module, Attention):
343
+ module.fuse_projections(fuse=True)
344
+
345
+ self.set_attn_processor(FusedHunyuanAttnProcessor2_0())
346
+
347
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
348
+ def unfuse_qkv_projections(self):
349
+ """Disables the fused QKV projection if enabled.
350
+
351
+ <Tip warning={true}>
352
+
353
+ This API is 🧪 experimental.
354
+
355
+ </Tip>
356
+
357
+ """
358
+ if self.original_attn_processors is not None:
359
+ self.set_attn_processor(self.original_attn_processors)
360
+
361
+ @property
362
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
363
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
364
+ r"""
365
+ Returns:
366
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
367
+ indexed by its weight name.
368
+ """
369
+ # set recursively
370
+ processors = {}
371
+
372
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
373
+ if hasattr(module, "get_processor"):
374
+ processors[f"{name}.processor"] = module.get_processor()
375
+
376
+ for sub_name, child in module.named_children():
377
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
378
+
379
+ return processors
380
+
381
+ for name, module in self.named_children():
382
+ fn_recursive_add_processors(name, module, processors)
383
+
384
+ return processors
385
+
386
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
387
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
388
+ r"""
389
+ Sets the attention processor to use to compute attention.
390
+
391
+ Parameters:
392
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
393
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
394
+ for **all** `Attention` layers.
395
+
396
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
397
+ processor. This is strongly recommended when setting trainable attention processors.
398
+
399
+ """
400
+ count = len(self.attn_processors.keys())
401
+
402
+ if isinstance(processor, dict) and len(processor) != count:
403
+ raise ValueError(
404
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
405
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
406
+ )
407
+
408
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
409
+ if hasattr(module, "set_processor"):
410
+ if not isinstance(processor, dict):
411
+ module.set_processor(processor)
412
+ else:
413
+ module.set_processor(processor.pop(f"{name}.processor"))
414
+
415
+ for sub_name, child in module.named_children():
416
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
417
+
418
+ for name, module in self.named_children():
419
+ fn_recursive_attn_processor(name, module, processor)
420
+
421
+ def set_default_attn_processor(self):
422
+ """
423
+ Disables custom attention processors and sets the default attention implementation.
424
+ """
425
+ self.set_attn_processor(HunyuanAttnProcessor2_0())
426
+
427
+ def forward(
428
+ self,
429
+ hidden_states,
430
+ timestep,
431
+ encoder_hidden_states=None,
432
+ text_embedding_mask=None,
433
+ encoder_hidden_states_t5=None,
434
+ text_embedding_mask_t5=None,
435
+ image_meta_size=None,
436
+ style=None,
437
+ image_rotary_emb=None,
438
+ controlnet_block_samples=None,
439
+ return_dict=True,
440
+ ):
441
+ """
442
+ The [`HunyuanDiT2DModel`] forward method.
443
+
444
+ Args:
445
+ hidden_states (`torch.Tensor` of shape `(batch size, dim, height, width)`):
446
+ The input tensor.
447
+ timestep ( `torch.LongTensor`, *optional*):
448
+ Used to indicate denoising step.
449
+ encoder_hidden_states ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
450
+ Conditional embeddings for cross attention layer. This is the output of `BertModel`.
451
+ text_embedding_mask: torch.Tensor
452
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. This is the output
453
+ of `BertModel`.
454
+ encoder_hidden_states_t5 ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
455
+ Conditional embeddings for cross attention layer. This is the output of T5 Text Encoder.
456
+ text_embedding_mask_t5: torch.Tensor
457
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. This is the output
458
+ of T5 Text Encoder.
459
+ image_meta_size (torch.Tensor):
460
+ Conditional embedding indicate the image sizes
461
+ style: torch.Tensor:
462
+ Conditional embedding indicate the style
463
+ image_rotary_emb (`torch.Tensor`):
464
+ The image rotary embeddings to apply on query and key tensors during attention calculation.
465
+ return_dict: bool
466
+ Whether to return a dictionary.
467
+ """
468
+
469
+ height, width = hidden_states.shape[-2:]
470
+
471
+ hidden_states = self.pos_embed(hidden_states)
472
+
473
+ temb = self.time_extra_emb(
474
+ timestep, encoder_hidden_states_t5, image_meta_size, style, hidden_dtype=timestep.dtype
475
+ ) # [B, D]
476
+
477
+ # text projection
478
+ batch_size, sequence_length, _ = encoder_hidden_states_t5.shape
479
+ encoder_hidden_states_t5 = self.text_embedder(
480
+ encoder_hidden_states_t5.view(-1, encoder_hidden_states_t5.shape[-1])
481
+ )
482
+ encoder_hidden_states_t5 = encoder_hidden_states_t5.view(batch_size, sequence_length, -1)
483
+
484
+ encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states_t5], dim=1)
485
+ text_embedding_mask = torch.cat([text_embedding_mask, text_embedding_mask_t5], dim=-1)
486
+ text_embedding_mask = text_embedding_mask.unsqueeze(2).bool()
487
+
488
+ encoder_hidden_states = torch.where(text_embedding_mask, encoder_hidden_states, self.text_embedding_padding)
489
+
490
+ skips = []
491
+ for layer, block in enumerate(self.blocks):
492
+ if layer > self.config.num_layers // 2:
493
+ if controlnet_block_samples is not None:
494
+ skip = skips.pop() + controlnet_block_samples.pop()
495
+ else:
496
+ skip = skips.pop()
497
+ hidden_states = block(
498
+ hidden_states,
499
+ temb=temb,
500
+ encoder_hidden_states=encoder_hidden_states,
501
+ image_rotary_emb=image_rotary_emb,
502
+ skip=skip,
503
+ ) # (N, L, D)
504
+ else:
505
+ hidden_states = block(
506
+ hidden_states,
507
+ temb=temb,
508
+ encoder_hidden_states=encoder_hidden_states,
509
+ image_rotary_emb=image_rotary_emb,
510
+ ) # (N, L, D)
511
+
512
+ if layer < (self.config.num_layers // 2 - 1):
513
+ skips.append(hidden_states)
514
+
515
+ if controlnet_block_samples is not None and len(controlnet_block_samples) != 0:
516
+ raise ValueError("The number of controls is not equal to the number of skip connections.")
517
+
518
+ # final layer
519
+ hidden_states = self.norm_out(hidden_states, temb.to(torch.float32))
520
+ hidden_states = self.proj_out(hidden_states)
521
+ # (N, L, patch_size ** 2 * out_channels)
522
+
523
+ # unpatchify: (N, out_channels, H, W)
524
+ patch_size = self.pos_embed.patch_size
525
+ height = height // patch_size
526
+ width = width // patch_size
527
+
528
+ hidden_states = hidden_states.reshape(
529
+ shape=(hidden_states.shape[0], height, width, patch_size, patch_size, self.out_channels)
530
+ )
531
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
532
+ output = hidden_states.reshape(
533
+ shape=(hidden_states.shape[0], self.out_channels, height * patch_size, width * patch_size)
534
+ )
535
+ if not return_dict:
536
+ return (output,)
537
+ return Transformer2DModelOutput(sample=output)
538
+
539
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.enable_forward_chunking
540
+ def enable_forward_chunking(self, chunk_size: Optional[int] = None, dim: int = 0) -> None:
541
+ """
542
+ Sets the attention processor to use [feed forward
543
+ chunking](https://huggingface.co/blog/reformer#2-chunked-feed-forward-layers).
544
+
545
+ Parameters:
546
+ chunk_size (`int`, *optional*):
547
+ The chunk size of the feed-forward layers. If not specified, will run feed-forward layer individually
548
+ over each tensor of dim=`dim`.
549
+ dim (`int`, *optional*, defaults to `0`):
550
+ The dimension over which the feed-forward computation should be chunked. Choose between dim=0 (batch)
551
+ or dim=1 (sequence length).
552
+ """
553
+ if dim not in [0, 1]:
554
+ raise ValueError(f"Make sure to set `dim` to either 0 or 1, not {dim}")
555
+
556
+ # By default chunk size is 1
557
+ chunk_size = chunk_size or 1
558
+
559
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
560
+ if hasattr(module, "set_chunk_feed_forward"):
561
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
562
+
563
+ for child in module.children():
564
+ fn_recursive_feed_forward(child, chunk_size, dim)
565
+
566
+ for module in self.children():
567
+ fn_recursive_feed_forward(module, chunk_size, dim)
568
+
569
+ # Copied from diffusers.models.unets.unet_3d_condition.UNet3DConditionModel.disable_forward_chunking
570
+ def disable_forward_chunking(self):
571
+ def fn_recursive_feed_forward(module: torch.nn.Module, chunk_size: int, dim: int):
572
+ if hasattr(module, "set_chunk_feed_forward"):
573
+ module.set_chunk_feed_forward(chunk_size=chunk_size, dim=dim)
574
+
575
+ for child in module.children():
576
+ fn_recursive_feed_forward(child, chunk_size, dim)
577
+
578
+ for module in self.children():
579
+ fn_recursive_feed_forward(module, None, 0)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/latte_transformer_3d.py ADDED
@@ -0,0 +1,332 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 the Latte Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Optional
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from ...configuration_utils import ConfigMixin, register_to_config
21
+ from ...models.embeddings import PixArtAlphaTextProjection, get_1d_sincos_pos_embed_from_grid
22
+ from ..attention import BasicTransformerBlock
23
+ from ..cache_utils import CacheMixin
24
+ from ..embeddings import PatchEmbed
25
+ from ..modeling_outputs import Transformer2DModelOutput
26
+ from ..modeling_utils import ModelMixin
27
+ from ..normalization import AdaLayerNormSingle
28
+
29
+
30
+ class LatteTransformer3DModel(ModelMixin, ConfigMixin, CacheMixin):
31
+ _supports_gradient_checkpointing = True
32
+
33
+ """
34
+ A 3D Transformer model for video-like data, paper: https://arxiv.org/abs/2401.03048, offical code:
35
+ https://github.com/Vchitect/Latte
36
+
37
+ Parameters:
38
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
39
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
40
+ in_channels (`int`, *optional*):
41
+ The number of channels in the input.
42
+ out_channels (`int`, *optional*):
43
+ The number of channels in the output.
44
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
45
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
46
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
47
+ attention_bias (`bool`, *optional*):
48
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
49
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
50
+ This is fixed during training since it is used to learn a number of position embeddings.
51
+ patch_size (`int`, *optional*):
52
+ The size of the patches to use in the patch embedding layer.
53
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
54
+ num_embeds_ada_norm ( `int`, *optional*):
55
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
56
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
57
+ added to the hidden states. During inference, you can denoise for up to but not more steps than
58
+ `num_embeds_ada_norm`.
59
+ norm_type (`str`, *optional*, defaults to `"layer_norm"`):
60
+ The type of normalization to use. Options are `"layer_norm"` or `"ada_layer_norm"`.
61
+ norm_elementwise_affine (`bool`, *optional*, defaults to `True`):
62
+ Whether or not to use elementwise affine in normalization layers.
63
+ norm_eps (`float`, *optional*, defaults to 1e-5): The epsilon value to use in normalization layers.
64
+ caption_channels (`int`, *optional*):
65
+ The number of channels in the caption embeddings.
66
+ video_length (`int`, *optional*):
67
+ The number of frames in the video-like data.
68
+ """
69
+
70
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
71
+
72
+ @register_to_config
73
+ def __init__(
74
+ self,
75
+ num_attention_heads: int = 16,
76
+ attention_head_dim: int = 88,
77
+ in_channels: Optional[int] = None,
78
+ out_channels: Optional[int] = None,
79
+ num_layers: int = 1,
80
+ dropout: float = 0.0,
81
+ cross_attention_dim: Optional[int] = None,
82
+ attention_bias: bool = False,
83
+ sample_size: int = 64,
84
+ patch_size: Optional[int] = None,
85
+ activation_fn: str = "geglu",
86
+ num_embeds_ada_norm: Optional[int] = None,
87
+ norm_type: str = "layer_norm",
88
+ norm_elementwise_affine: bool = True,
89
+ norm_eps: float = 1e-5,
90
+ caption_channels: int = None,
91
+ video_length: int = 16,
92
+ ):
93
+ super().__init__()
94
+ inner_dim = num_attention_heads * attention_head_dim
95
+
96
+ # 1. Define input layers
97
+ self.height = sample_size
98
+ self.width = sample_size
99
+
100
+ interpolation_scale = self.config.sample_size // 64
101
+ interpolation_scale = max(interpolation_scale, 1)
102
+ self.pos_embed = PatchEmbed(
103
+ height=sample_size,
104
+ width=sample_size,
105
+ patch_size=patch_size,
106
+ in_channels=in_channels,
107
+ embed_dim=inner_dim,
108
+ interpolation_scale=interpolation_scale,
109
+ )
110
+
111
+ # 2. Define spatial transformers blocks
112
+ self.transformer_blocks = nn.ModuleList(
113
+ [
114
+ BasicTransformerBlock(
115
+ inner_dim,
116
+ num_attention_heads,
117
+ attention_head_dim,
118
+ dropout=dropout,
119
+ cross_attention_dim=cross_attention_dim,
120
+ activation_fn=activation_fn,
121
+ num_embeds_ada_norm=num_embeds_ada_norm,
122
+ attention_bias=attention_bias,
123
+ norm_type=norm_type,
124
+ norm_elementwise_affine=norm_elementwise_affine,
125
+ norm_eps=norm_eps,
126
+ )
127
+ for d in range(num_layers)
128
+ ]
129
+ )
130
+
131
+ # 3. Define temporal transformers blocks
132
+ self.temporal_transformer_blocks = nn.ModuleList(
133
+ [
134
+ BasicTransformerBlock(
135
+ inner_dim,
136
+ num_attention_heads,
137
+ attention_head_dim,
138
+ dropout=dropout,
139
+ cross_attention_dim=None,
140
+ activation_fn=activation_fn,
141
+ num_embeds_ada_norm=num_embeds_ada_norm,
142
+ attention_bias=attention_bias,
143
+ norm_type=norm_type,
144
+ norm_elementwise_affine=norm_elementwise_affine,
145
+ norm_eps=norm_eps,
146
+ )
147
+ for d in range(num_layers)
148
+ ]
149
+ )
150
+
151
+ # 4. Define output layers
152
+ self.out_channels = in_channels if out_channels is None else out_channels
153
+ self.norm_out = nn.LayerNorm(inner_dim, elementwise_affine=False, eps=1e-6)
154
+ self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
155
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * self.out_channels)
156
+
157
+ # 5. Latte other blocks.
158
+ self.adaln_single = AdaLayerNormSingle(inner_dim, use_additional_conditions=False)
159
+ self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
160
+
161
+ # define temporal positional embedding
162
+ temp_pos_embed = get_1d_sincos_pos_embed_from_grid(
163
+ inner_dim, torch.arange(0, video_length).unsqueeze(1), output_type="pt"
164
+ ) # 1152 hidden size
165
+ self.register_buffer("temp_pos_embed", temp_pos_embed.float().unsqueeze(0), persistent=False)
166
+
167
+ self.gradient_checkpointing = False
168
+
169
+ def forward(
170
+ self,
171
+ hidden_states: torch.Tensor,
172
+ timestep: Optional[torch.LongTensor] = None,
173
+ encoder_hidden_states: Optional[torch.Tensor] = None,
174
+ encoder_attention_mask: Optional[torch.Tensor] = None,
175
+ enable_temporal_attentions: bool = True,
176
+ return_dict: bool = True,
177
+ ):
178
+ """
179
+ The [`LatteTransformer3DModel`] forward method.
180
+
181
+ Args:
182
+ hidden_states shape `(batch size, channel, num_frame, height, width)`:
183
+ Input `hidden_states`.
184
+ timestep ( `torch.LongTensor`, *optional*):
185
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
186
+ encoder_hidden_states ( `torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
187
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
188
+ self-attention.
189
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
190
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
191
+
192
+ * Mask `(batcheight, sequence_length)` True = keep, False = discard.
193
+ * Bias `(batcheight, 1, sequence_length)` 0 = keep, -10000 = discard.
194
+
195
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
196
+ above. This bias will be added to the cross-attention scores.
197
+ enable_temporal_attentions:
198
+ (`bool`, *optional*, defaults to `True`): Whether to enable temporal attentions.
199
+ return_dict (`bool`, *optional*, defaults to `True`):
200
+ Whether or not to return a [`~models.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
201
+ tuple.
202
+
203
+ Returns:
204
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
205
+ `tuple` where the first element is the sample tensor.
206
+ """
207
+
208
+ # Reshape hidden states
209
+ batch_size, channels, num_frame, height, width = hidden_states.shape
210
+ # batch_size channels num_frame height width -> (batch_size * num_frame) channels height width
211
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).reshape(-1, channels, height, width)
212
+
213
+ # Input
214
+ height, width = (
215
+ hidden_states.shape[-2] // self.config.patch_size,
216
+ hidden_states.shape[-1] // self.config.patch_size,
217
+ )
218
+ num_patches = height * width
219
+
220
+ hidden_states = self.pos_embed(hidden_states) # alrady add positional embeddings
221
+
222
+ added_cond_kwargs = {"resolution": None, "aspect_ratio": None}
223
+ timestep, embedded_timestep = self.adaln_single(
224
+ timestep, added_cond_kwargs=added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
225
+ )
226
+
227
+ # Prepare text embeddings for spatial block
228
+ # batch_size num_tokens hidden_size -> (batch_size * num_frame) num_tokens hidden_size
229
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states) # 3 120 1152
230
+ encoder_hidden_states_spatial = encoder_hidden_states.repeat_interleave(
231
+ num_frame, dim=0, output_size=encoder_hidden_states.shape[0] * num_frame
232
+ ).view(-1, encoder_hidden_states.shape[-2], encoder_hidden_states.shape[-1])
233
+
234
+ # Prepare timesteps for spatial and temporal block
235
+ timestep_spatial = timestep.repeat_interleave(
236
+ num_frame, dim=0, output_size=timestep.shape[0] * num_frame
237
+ ).view(-1, timestep.shape[-1])
238
+ timestep_temp = timestep.repeat_interleave(
239
+ num_patches, dim=0, output_size=timestep.shape[0] * num_patches
240
+ ).view(-1, timestep.shape[-1])
241
+
242
+ # Spatial and temporal transformer blocks
243
+ for i, (spatial_block, temp_block) in enumerate(
244
+ zip(self.transformer_blocks, self.temporal_transformer_blocks)
245
+ ):
246
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
247
+ hidden_states = self._gradient_checkpointing_func(
248
+ spatial_block,
249
+ hidden_states,
250
+ None, # attention_mask
251
+ encoder_hidden_states_spatial,
252
+ encoder_attention_mask,
253
+ timestep_spatial,
254
+ None, # cross_attention_kwargs
255
+ None, # class_labels
256
+ )
257
+ else:
258
+ hidden_states = spatial_block(
259
+ hidden_states,
260
+ None, # attention_mask
261
+ encoder_hidden_states_spatial,
262
+ encoder_attention_mask,
263
+ timestep_spatial,
264
+ None, # cross_attention_kwargs
265
+ None, # class_labels
266
+ )
267
+
268
+ if enable_temporal_attentions:
269
+ # (batch_size * num_frame) num_tokens hidden_size -> (batch_size * num_tokens) num_frame hidden_size
270
+ hidden_states = hidden_states.reshape(
271
+ batch_size, -1, hidden_states.shape[-2], hidden_states.shape[-1]
272
+ ).permute(0, 2, 1, 3)
273
+ hidden_states = hidden_states.reshape(-1, hidden_states.shape[-2], hidden_states.shape[-1])
274
+
275
+ if i == 0 and num_frame > 1:
276
+ hidden_states = hidden_states + self.temp_pos_embed.to(hidden_states.dtype)
277
+
278
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
279
+ hidden_states = self._gradient_checkpointing_func(
280
+ temp_block,
281
+ hidden_states,
282
+ None, # attention_mask
283
+ None, # encoder_hidden_states
284
+ None, # encoder_attention_mask
285
+ timestep_temp,
286
+ None, # cross_attention_kwargs
287
+ None, # class_labels
288
+ )
289
+ else:
290
+ hidden_states = temp_block(
291
+ hidden_states,
292
+ None, # attention_mask
293
+ None, # encoder_hidden_states
294
+ None, # encoder_attention_mask
295
+ timestep_temp,
296
+ None, # cross_attention_kwargs
297
+ None, # class_labels
298
+ )
299
+
300
+ # (batch_size * num_tokens) num_frame hidden_size -> (batch_size * num_frame) num_tokens hidden_size
301
+ hidden_states = hidden_states.reshape(
302
+ batch_size, -1, hidden_states.shape[-2], hidden_states.shape[-1]
303
+ ).permute(0, 2, 1, 3)
304
+ hidden_states = hidden_states.reshape(-1, hidden_states.shape[-2], hidden_states.shape[-1])
305
+
306
+ embedded_timestep = embedded_timestep.repeat_interleave(
307
+ num_frame, dim=0, output_size=embedded_timestep.shape[0] * num_frame
308
+ ).view(-1, embedded_timestep.shape[-1])
309
+ shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
310
+ hidden_states = self.norm_out(hidden_states)
311
+ # Modulation
312
+ hidden_states = hidden_states * (1 + scale) + shift
313
+ hidden_states = self.proj_out(hidden_states)
314
+
315
+ # unpatchify
316
+ if self.adaln_single is None:
317
+ height = width = int(hidden_states.shape[1] ** 0.5)
318
+ hidden_states = hidden_states.reshape(
319
+ shape=(-1, height, width, self.config.patch_size, self.config.patch_size, self.out_channels)
320
+ )
321
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
322
+ output = hidden_states.reshape(
323
+ shape=(-1, self.out_channels, height * self.config.patch_size, width * self.config.patch_size)
324
+ )
325
+ output = output.reshape(batch_size, -1, output.shape[-3], output.shape[-2], output.shape[-1]).permute(
326
+ 0, 2, 1, 3, 4
327
+ )
328
+
329
+ if not return_dict:
330
+ return (output,)
331
+
332
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/lumina_nextdit2d.py ADDED
@@ -0,0 +1,342 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Alpha-VLLM Authors and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Dict, Optional
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+
20
+ from ...configuration_utils import ConfigMixin, register_to_config
21
+ from ...utils import logging
22
+ from ..attention import LuminaFeedForward
23
+ from ..attention_processor import Attention, LuminaAttnProcessor2_0
24
+ from ..embeddings import (
25
+ LuminaCombinedTimestepCaptionEmbedding,
26
+ LuminaPatchEmbed,
27
+ )
28
+ from ..modeling_outputs import Transformer2DModelOutput
29
+ from ..modeling_utils import ModelMixin
30
+ from ..normalization import LuminaLayerNormContinuous, LuminaRMSNormZero, RMSNorm
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+
36
+ class LuminaNextDiTBlock(nn.Module):
37
+ """
38
+ A LuminaNextDiTBlock for LuminaNextDiT2DModel.
39
+
40
+ Parameters:
41
+ dim (`int`): Embedding dimension of the input features.
42
+ num_attention_heads (`int`): Number of attention heads.
43
+ num_kv_heads (`int`):
44
+ Number of attention heads in key and value features (if using GQA), or set to None for the same as query.
45
+ multiple_of (`int`): The number of multiple of ffn layer.
46
+ ffn_dim_multiplier (`float`): The multipier factor of ffn layer dimension.
47
+ norm_eps (`float`): The eps for norm layer.
48
+ qk_norm (`bool`): normalization for query and key.
49
+ cross_attention_dim (`int`): Cross attention embedding dimension of the input text prompt hidden_states.
50
+ norm_elementwise_affine (`bool`, *optional*, defaults to True),
51
+ """
52
+
53
+ def __init__(
54
+ self,
55
+ dim: int,
56
+ num_attention_heads: int,
57
+ num_kv_heads: int,
58
+ multiple_of: int,
59
+ ffn_dim_multiplier: float,
60
+ norm_eps: float,
61
+ qk_norm: bool,
62
+ cross_attention_dim: int,
63
+ norm_elementwise_affine: bool = True,
64
+ ) -> None:
65
+ super().__init__()
66
+ self.head_dim = dim // num_attention_heads
67
+
68
+ self.gate = nn.Parameter(torch.zeros([num_attention_heads]))
69
+
70
+ # Self-attention
71
+ self.attn1 = Attention(
72
+ query_dim=dim,
73
+ cross_attention_dim=None,
74
+ dim_head=dim // num_attention_heads,
75
+ qk_norm="layer_norm_across_heads" if qk_norm else None,
76
+ heads=num_attention_heads,
77
+ kv_heads=num_kv_heads,
78
+ eps=1e-5,
79
+ bias=False,
80
+ out_bias=False,
81
+ processor=LuminaAttnProcessor2_0(),
82
+ )
83
+ self.attn1.to_out = nn.Identity()
84
+
85
+ # Cross-attention
86
+ self.attn2 = Attention(
87
+ query_dim=dim,
88
+ cross_attention_dim=cross_attention_dim,
89
+ dim_head=dim // num_attention_heads,
90
+ qk_norm="layer_norm_across_heads" if qk_norm else None,
91
+ heads=num_attention_heads,
92
+ kv_heads=num_kv_heads,
93
+ eps=1e-5,
94
+ bias=False,
95
+ out_bias=False,
96
+ processor=LuminaAttnProcessor2_0(),
97
+ )
98
+
99
+ self.feed_forward = LuminaFeedForward(
100
+ dim=dim,
101
+ inner_dim=int(4 * 2 * dim / 3),
102
+ multiple_of=multiple_of,
103
+ ffn_dim_multiplier=ffn_dim_multiplier,
104
+ )
105
+
106
+ self.norm1 = LuminaRMSNormZero(
107
+ embedding_dim=dim,
108
+ norm_eps=norm_eps,
109
+ norm_elementwise_affine=norm_elementwise_affine,
110
+ )
111
+ self.ffn_norm1 = RMSNorm(dim, eps=norm_eps, elementwise_affine=norm_elementwise_affine)
112
+
113
+ self.norm2 = RMSNorm(dim, eps=norm_eps, elementwise_affine=norm_elementwise_affine)
114
+ self.ffn_norm2 = RMSNorm(dim, eps=norm_eps, elementwise_affine=norm_elementwise_affine)
115
+
116
+ self.norm1_context = RMSNorm(cross_attention_dim, eps=norm_eps, elementwise_affine=norm_elementwise_affine)
117
+
118
+ def forward(
119
+ self,
120
+ hidden_states: torch.Tensor,
121
+ attention_mask: torch.Tensor,
122
+ image_rotary_emb: torch.Tensor,
123
+ encoder_hidden_states: torch.Tensor,
124
+ encoder_mask: torch.Tensor,
125
+ temb: torch.Tensor,
126
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
127
+ ):
128
+ """
129
+ Perform a forward pass through the LuminaNextDiTBlock.
130
+
131
+ Parameters:
132
+ hidden_states (`torch.Tensor`): The input of hidden_states for LuminaNextDiTBlock.
133
+ attention_mask (`torch.Tensor): The input of hidden_states corresponse attention mask.
134
+ image_rotary_emb (`torch.Tensor`): Precomputed cosine and sine frequencies.
135
+ encoder_hidden_states: (`torch.Tensor`): The hidden_states of text prompt are processed by Gemma encoder.
136
+ encoder_mask (`torch.Tensor`): The hidden_states of text prompt attention mask.
137
+ temb (`torch.Tensor`): Timestep embedding with text prompt embedding.
138
+ cross_attention_kwargs (`Dict[str, Any]`): kwargs for cross attention.
139
+ """
140
+ residual = hidden_states
141
+
142
+ # Self-attention
143
+ norm_hidden_states, gate_msa, scale_mlp, gate_mlp = self.norm1(hidden_states, temb)
144
+ self_attn_output = self.attn1(
145
+ hidden_states=norm_hidden_states,
146
+ encoder_hidden_states=norm_hidden_states,
147
+ attention_mask=attention_mask,
148
+ query_rotary_emb=image_rotary_emb,
149
+ key_rotary_emb=image_rotary_emb,
150
+ **cross_attention_kwargs,
151
+ )
152
+
153
+ # Cross-attention
154
+ norm_encoder_hidden_states = self.norm1_context(encoder_hidden_states)
155
+ cross_attn_output = self.attn2(
156
+ hidden_states=norm_hidden_states,
157
+ encoder_hidden_states=norm_encoder_hidden_states,
158
+ attention_mask=encoder_mask,
159
+ query_rotary_emb=image_rotary_emb,
160
+ key_rotary_emb=None,
161
+ **cross_attention_kwargs,
162
+ )
163
+ cross_attn_output = cross_attn_output * self.gate.tanh().view(1, 1, -1, 1)
164
+ mixed_attn_output = self_attn_output + cross_attn_output
165
+ mixed_attn_output = mixed_attn_output.flatten(-2)
166
+ # linear proj
167
+ hidden_states = self.attn2.to_out[0](mixed_attn_output)
168
+
169
+ hidden_states = residual + gate_msa.unsqueeze(1).tanh() * self.norm2(hidden_states)
170
+
171
+ mlp_output = self.feed_forward(self.ffn_norm1(hidden_states) * (1 + scale_mlp.unsqueeze(1)))
172
+
173
+ hidden_states = hidden_states + gate_mlp.unsqueeze(1).tanh() * self.ffn_norm2(mlp_output)
174
+
175
+ return hidden_states
176
+
177
+
178
+ class LuminaNextDiT2DModel(ModelMixin, ConfigMixin):
179
+ """
180
+ LuminaNextDiT: Diffusion model with a Transformer backbone.
181
+
182
+ Inherit ModelMixin and ConfigMixin to be compatible with the sampler StableDiffusionPipeline of diffusers.
183
+
184
+ Parameters:
185
+ sample_size (`int`): The width of the latent images. This is fixed during training since
186
+ it is used to learn a number of position embeddings.
187
+ patch_size (`int`, *optional*, (`int`, *optional*, defaults to 2):
188
+ The size of each patch in the image. This parameter defines the resolution of patches fed into the model.
189
+ in_channels (`int`, *optional*, defaults to 4):
190
+ The number of input channels for the model. Typically, this matches the number of channels in the input
191
+ images.
192
+ hidden_size (`int`, *optional*, defaults to 4096):
193
+ The dimensionality of the hidden layers in the model. This parameter determines the width of the model's
194
+ hidden representations.
195
+ num_layers (`int`, *optional*, default to 32):
196
+ The number of layers in the model. This defines the depth of the neural network.
197
+ num_attention_heads (`int`, *optional*, defaults to 32):
198
+ The number of attention heads in each attention layer. This parameter specifies how many separate attention
199
+ mechanisms are used.
200
+ num_kv_heads (`int`, *optional*, defaults to 8):
201
+ The number of key-value heads in the attention mechanism, if different from the number of attention heads.
202
+ If None, it defaults to num_attention_heads.
203
+ multiple_of (`int`, *optional*, defaults to 256):
204
+ A factor that the hidden size should be a multiple of. This can help optimize certain hardware
205
+ configurations.
206
+ ffn_dim_multiplier (`float`, *optional*):
207
+ A multiplier for the dimensionality of the feed-forward network. If None, it uses a default value based on
208
+ the model configuration.
209
+ norm_eps (`float`, *optional*, defaults to 1e-5):
210
+ A small value added to the denominator for numerical stability in normalization layers.
211
+ learn_sigma (`bool`, *optional*, defaults to True):
212
+ Whether the model should learn the sigma parameter, which might be related to uncertainty or variance in
213
+ predictions.
214
+ qk_norm (`bool`, *optional*, defaults to True):
215
+ Indicates if the queries and keys in the attention mechanism should be normalized.
216
+ cross_attention_dim (`int`, *optional*, defaults to 2048):
217
+ The dimensionality of the text embeddings. This parameter defines the size of the text representations used
218
+ in the model.
219
+ scaling_factor (`float`, *optional*, defaults to 1.0):
220
+ A scaling factor applied to certain parameters or layers in the model. This can be used for adjusting the
221
+ overall scale of the model's operations.
222
+ """
223
+
224
+ _skip_layerwise_casting_patterns = ["patch_embedder", "norm", "ffn_norm"]
225
+
226
+ @register_to_config
227
+ def __init__(
228
+ self,
229
+ sample_size: int = 128,
230
+ patch_size: Optional[int] = 2,
231
+ in_channels: Optional[int] = 4,
232
+ hidden_size: Optional[int] = 2304,
233
+ num_layers: Optional[int] = 32,
234
+ num_attention_heads: Optional[int] = 32,
235
+ num_kv_heads: Optional[int] = None,
236
+ multiple_of: Optional[int] = 256,
237
+ ffn_dim_multiplier: Optional[float] = None,
238
+ norm_eps: Optional[float] = 1e-5,
239
+ learn_sigma: Optional[bool] = True,
240
+ qk_norm: Optional[bool] = True,
241
+ cross_attention_dim: Optional[int] = 2048,
242
+ scaling_factor: Optional[float] = 1.0,
243
+ ) -> None:
244
+ super().__init__()
245
+ self.sample_size = sample_size
246
+ self.patch_size = patch_size
247
+ self.in_channels = in_channels
248
+ self.out_channels = in_channels * 2 if learn_sigma else in_channels
249
+ self.hidden_size = hidden_size
250
+ self.num_attention_heads = num_attention_heads
251
+ self.head_dim = hidden_size // num_attention_heads
252
+ self.scaling_factor = scaling_factor
253
+
254
+ self.patch_embedder = LuminaPatchEmbed(
255
+ patch_size=patch_size, in_channels=in_channels, embed_dim=hidden_size, bias=True
256
+ )
257
+
258
+ self.pad_token = nn.Parameter(torch.empty(hidden_size))
259
+
260
+ self.time_caption_embed = LuminaCombinedTimestepCaptionEmbedding(
261
+ hidden_size=min(hidden_size, 1024), cross_attention_dim=cross_attention_dim
262
+ )
263
+
264
+ self.layers = nn.ModuleList(
265
+ [
266
+ LuminaNextDiTBlock(
267
+ hidden_size,
268
+ num_attention_heads,
269
+ num_kv_heads,
270
+ multiple_of,
271
+ ffn_dim_multiplier,
272
+ norm_eps,
273
+ qk_norm,
274
+ cross_attention_dim,
275
+ )
276
+ for _ in range(num_layers)
277
+ ]
278
+ )
279
+ self.norm_out = LuminaLayerNormContinuous(
280
+ embedding_dim=hidden_size,
281
+ conditioning_embedding_dim=min(hidden_size, 1024),
282
+ elementwise_affine=False,
283
+ eps=1e-6,
284
+ bias=True,
285
+ out_dim=patch_size * patch_size * self.out_channels,
286
+ )
287
+ # self.final_layer = LuminaFinalLayer(hidden_size, patch_size, self.out_channels)
288
+
289
+ assert (hidden_size // num_attention_heads) % 4 == 0, "2d rope needs head dim to be divisible by 4"
290
+
291
+ def forward(
292
+ self,
293
+ hidden_states: torch.Tensor,
294
+ timestep: torch.Tensor,
295
+ encoder_hidden_states: torch.Tensor,
296
+ encoder_mask: torch.Tensor,
297
+ image_rotary_emb: torch.Tensor,
298
+ cross_attention_kwargs: Dict[str, Any] = None,
299
+ return_dict=True,
300
+ ) -> torch.Tensor:
301
+ """
302
+ Forward pass of LuminaNextDiT.
303
+
304
+ Parameters:
305
+ hidden_states (torch.Tensor): Input tensor of shape (N, C, H, W).
306
+ timestep (torch.Tensor): Tensor of diffusion timesteps of shape (N,).
307
+ encoder_hidden_states (torch.Tensor): Tensor of caption features of shape (N, D).
308
+ encoder_mask (torch.Tensor): Tensor of caption masks of shape (N, L).
309
+ """
310
+ hidden_states, mask, img_size, image_rotary_emb = self.patch_embedder(hidden_states, image_rotary_emb)
311
+ image_rotary_emb = image_rotary_emb.to(hidden_states.device)
312
+
313
+ temb = self.time_caption_embed(timestep, encoder_hidden_states, encoder_mask)
314
+
315
+ encoder_mask = encoder_mask.bool()
316
+ for layer in self.layers:
317
+ hidden_states = layer(
318
+ hidden_states,
319
+ mask,
320
+ image_rotary_emb,
321
+ encoder_hidden_states,
322
+ encoder_mask,
323
+ temb=temb,
324
+ cross_attention_kwargs=cross_attention_kwargs,
325
+ )
326
+
327
+ hidden_states = self.norm_out(hidden_states, temb)
328
+
329
+ # unpatchify
330
+ height_tokens = width_tokens = self.patch_size
331
+ height, width = img_size[0]
332
+ batch_size = hidden_states.size(0)
333
+ sequence_length = (height // height_tokens) * (width // width_tokens)
334
+ hidden_states = hidden_states[:, :sequence_length].view(
335
+ batch_size, height // height_tokens, width // width_tokens, height_tokens, width_tokens, self.out_channels
336
+ )
337
+ output = hidden_states.permute(0, 5, 1, 3, 2, 4).flatten(4, 5).flatten(2, 3)
338
+
339
+ if not return_dict:
340
+ return (output,)
341
+
342
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/pixart_transformer_2d.py ADDED
@@ -0,0 +1,430 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Dict, Optional, Union
15
+
16
+ import torch
17
+ from torch import nn
18
+
19
+ from ...configuration_utils import ConfigMixin, register_to_config
20
+ from ...utils import logging
21
+ from ..attention import BasicTransformerBlock
22
+ from ..attention_processor import Attention, AttentionProcessor, AttnProcessor, FusedAttnProcessor2_0
23
+ from ..embeddings import PatchEmbed, PixArtAlphaTextProjection
24
+ from ..modeling_outputs import Transformer2DModelOutput
25
+ from ..modeling_utils import ModelMixin
26
+ from ..normalization import AdaLayerNormSingle
27
+
28
+
29
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
30
+
31
+
32
+ class PixArtTransformer2DModel(ModelMixin, ConfigMixin):
33
+ r"""
34
+ A 2D Transformer model as introduced in PixArt family of models (https://arxiv.org/abs/2310.00426,
35
+ https://arxiv.org/abs/2403.04692).
36
+
37
+ Parameters:
38
+ num_attention_heads (int, optional, defaults to 16): The number of heads to use for multi-head attention.
39
+ attention_head_dim (int, optional, defaults to 72): The number of channels in each head.
40
+ in_channels (int, defaults to 4): The number of channels in the input.
41
+ out_channels (int, optional):
42
+ The number of channels in the output. Specify this parameter if the output channel number differs from the
43
+ input.
44
+ num_layers (int, optional, defaults to 28): The number of layers of Transformer blocks to use.
45
+ dropout (float, optional, defaults to 0.0): The dropout probability to use within the Transformer blocks.
46
+ norm_num_groups (int, optional, defaults to 32):
47
+ Number of groups for group normalization within Transformer blocks.
48
+ cross_attention_dim (int, optional):
49
+ The dimensionality for cross-attention layers, typically matching the encoder's hidden dimension.
50
+ attention_bias (bool, optional, defaults to True):
51
+ Configure if the Transformer blocks' attention should contain a bias parameter.
52
+ sample_size (int, defaults to 128):
53
+ The width of the latent images. This parameter is fixed during training.
54
+ patch_size (int, defaults to 2):
55
+ Size of the patches the model processes, relevant for architectures working on non-sequential data.
56
+ activation_fn (str, optional, defaults to "gelu-approximate"):
57
+ Activation function to use in feed-forward networks within Transformer blocks.
58
+ num_embeds_ada_norm (int, optional, defaults to 1000):
59
+ Number of embeddings for AdaLayerNorm, fixed during training and affects the maximum denoising steps during
60
+ inference.
61
+ upcast_attention (bool, optional, defaults to False):
62
+ If true, upcasts the attention mechanism dimensions for potentially improved performance.
63
+ norm_type (str, optional, defaults to "ada_norm_zero"):
64
+ Specifies the type of normalization used, can be 'ada_norm_zero'.
65
+ norm_elementwise_affine (bool, optional, defaults to False):
66
+ If true, enables element-wise affine parameters in the normalization layers.
67
+ norm_eps (float, optional, defaults to 1e-6):
68
+ A small constant added to the denominator in normalization layers to prevent division by zero.
69
+ interpolation_scale (int, optional): Scale factor to use during interpolating the position embeddings.
70
+ use_additional_conditions (bool, optional): If we're using additional conditions as inputs.
71
+ attention_type (str, optional, defaults to "default"): Kind of attention mechanism to be used.
72
+ caption_channels (int, optional, defaults to None):
73
+ Number of channels to use for projecting the caption embeddings.
74
+ use_linear_projection (bool, optional, defaults to False):
75
+ Deprecated argument. Will be removed in a future version.
76
+ num_vector_embeds (bool, optional, defaults to False):
77
+ Deprecated argument. Will be removed in a future version.
78
+ """
79
+
80
+ _supports_gradient_checkpointing = True
81
+ _no_split_modules = ["BasicTransformerBlock", "PatchEmbed"]
82
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm", "adaln_single"]
83
+
84
+ @register_to_config
85
+ def __init__(
86
+ self,
87
+ num_attention_heads: int = 16,
88
+ attention_head_dim: int = 72,
89
+ in_channels: int = 4,
90
+ out_channels: Optional[int] = 8,
91
+ num_layers: int = 28,
92
+ dropout: float = 0.0,
93
+ norm_num_groups: int = 32,
94
+ cross_attention_dim: Optional[int] = 1152,
95
+ attention_bias: bool = True,
96
+ sample_size: int = 128,
97
+ patch_size: int = 2,
98
+ activation_fn: str = "gelu-approximate",
99
+ num_embeds_ada_norm: Optional[int] = 1000,
100
+ upcast_attention: bool = False,
101
+ norm_type: str = "ada_norm_single",
102
+ norm_elementwise_affine: bool = False,
103
+ norm_eps: float = 1e-6,
104
+ interpolation_scale: Optional[int] = None,
105
+ use_additional_conditions: Optional[bool] = None,
106
+ caption_channels: Optional[int] = None,
107
+ attention_type: Optional[str] = "default",
108
+ ):
109
+ super().__init__()
110
+
111
+ # Validate inputs.
112
+ if norm_type != "ada_norm_single":
113
+ raise NotImplementedError(
114
+ f"Forward pass is not implemented when `patch_size` is not None and `norm_type` is '{norm_type}'."
115
+ )
116
+ elif norm_type == "ada_norm_single" and num_embeds_ada_norm is None:
117
+ raise ValueError(
118
+ f"When using a `patch_size` and this `norm_type` ({norm_type}), `num_embeds_ada_norm` cannot be None."
119
+ )
120
+
121
+ # Set some common variables used across the board.
122
+ self.attention_head_dim = attention_head_dim
123
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
124
+ self.out_channels = in_channels if out_channels is None else out_channels
125
+ if use_additional_conditions is None:
126
+ if sample_size == 128:
127
+ use_additional_conditions = True
128
+ else:
129
+ use_additional_conditions = False
130
+ self.use_additional_conditions = use_additional_conditions
131
+
132
+ self.gradient_checkpointing = False
133
+
134
+ # 2. Initialize the position embedding and transformer blocks.
135
+ self.height = self.config.sample_size
136
+ self.width = self.config.sample_size
137
+
138
+ interpolation_scale = (
139
+ self.config.interpolation_scale
140
+ if self.config.interpolation_scale is not None
141
+ else max(self.config.sample_size // 64, 1)
142
+ )
143
+ self.pos_embed = PatchEmbed(
144
+ height=self.config.sample_size,
145
+ width=self.config.sample_size,
146
+ patch_size=self.config.patch_size,
147
+ in_channels=self.config.in_channels,
148
+ embed_dim=self.inner_dim,
149
+ interpolation_scale=interpolation_scale,
150
+ )
151
+
152
+ self.transformer_blocks = nn.ModuleList(
153
+ [
154
+ BasicTransformerBlock(
155
+ self.inner_dim,
156
+ self.config.num_attention_heads,
157
+ self.config.attention_head_dim,
158
+ dropout=self.config.dropout,
159
+ cross_attention_dim=self.config.cross_attention_dim,
160
+ activation_fn=self.config.activation_fn,
161
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
162
+ attention_bias=self.config.attention_bias,
163
+ upcast_attention=self.config.upcast_attention,
164
+ norm_type=norm_type,
165
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
166
+ norm_eps=self.config.norm_eps,
167
+ attention_type=self.config.attention_type,
168
+ )
169
+ for _ in range(self.config.num_layers)
170
+ ]
171
+ )
172
+
173
+ # 3. Output blocks.
174
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
175
+ self.scale_shift_table = nn.Parameter(torch.randn(2, self.inner_dim) / self.inner_dim**0.5)
176
+ self.proj_out = nn.Linear(self.inner_dim, self.config.patch_size * self.config.patch_size * self.out_channels)
177
+
178
+ self.adaln_single = AdaLayerNormSingle(
179
+ self.inner_dim, use_additional_conditions=self.use_additional_conditions
180
+ )
181
+ self.caption_projection = None
182
+ if self.config.caption_channels is not None:
183
+ self.caption_projection = PixArtAlphaTextProjection(
184
+ in_features=self.config.caption_channels, hidden_size=self.inner_dim
185
+ )
186
+
187
+ @property
188
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
189
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
190
+ r"""
191
+ Returns:
192
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
193
+ indexed by its weight name.
194
+ """
195
+ # set recursively
196
+ processors = {}
197
+
198
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
199
+ if hasattr(module, "get_processor"):
200
+ processors[f"{name}.processor"] = module.get_processor()
201
+
202
+ for sub_name, child in module.named_children():
203
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
204
+
205
+ return processors
206
+
207
+ for name, module in self.named_children():
208
+ fn_recursive_add_processors(name, module, processors)
209
+
210
+ return processors
211
+
212
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
213
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
214
+ r"""
215
+ Sets the attention processor to use to compute attention.
216
+
217
+ Parameters:
218
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
219
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
220
+ for **all** `Attention` layers.
221
+
222
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
223
+ processor. This is strongly recommended when setting trainable attention processors.
224
+
225
+ """
226
+ count = len(self.attn_processors.keys())
227
+
228
+ if isinstance(processor, dict) and len(processor) != count:
229
+ raise ValueError(
230
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
231
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
232
+ )
233
+
234
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
235
+ if hasattr(module, "set_processor"):
236
+ if not isinstance(processor, dict):
237
+ module.set_processor(processor)
238
+ else:
239
+ module.set_processor(processor.pop(f"{name}.processor"))
240
+
241
+ for sub_name, child in module.named_children():
242
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
243
+
244
+ for name, module in self.named_children():
245
+ fn_recursive_attn_processor(name, module, processor)
246
+
247
+ def set_default_attn_processor(self):
248
+ """
249
+ Disables custom attention processors and sets the default attention implementation.
250
+
251
+ Safe to just use `AttnProcessor()` as PixArt doesn't have any exotic attention processors in default model.
252
+ """
253
+ self.set_attn_processor(AttnProcessor())
254
+
255
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections
256
+ def fuse_qkv_projections(self):
257
+ """
258
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
259
+ are fused. For cross-attention modules, key and value projection matrices are fused.
260
+
261
+ <Tip warning={true}>
262
+
263
+ This API is 🧪 experimental.
264
+
265
+ </Tip>
266
+ """
267
+ self.original_attn_processors = None
268
+
269
+ for _, attn_processor in self.attn_processors.items():
270
+ if "Added" in str(attn_processor.__class__.__name__):
271
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
272
+
273
+ self.original_attn_processors = self.attn_processors
274
+
275
+ for module in self.modules():
276
+ if isinstance(module, Attention):
277
+ module.fuse_projections(fuse=True)
278
+
279
+ self.set_attn_processor(FusedAttnProcessor2_0())
280
+
281
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
282
+ def unfuse_qkv_projections(self):
283
+ """Disables the fused QKV projection if enabled.
284
+
285
+ <Tip warning={true}>
286
+
287
+ This API is 🧪 experimental.
288
+
289
+ </Tip>
290
+
291
+ """
292
+ if self.original_attn_processors is not None:
293
+ self.set_attn_processor(self.original_attn_processors)
294
+
295
+ def forward(
296
+ self,
297
+ hidden_states: torch.Tensor,
298
+ encoder_hidden_states: Optional[torch.Tensor] = None,
299
+ timestep: Optional[torch.LongTensor] = None,
300
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
301
+ cross_attention_kwargs: Dict[str, Any] = None,
302
+ attention_mask: Optional[torch.Tensor] = None,
303
+ encoder_attention_mask: Optional[torch.Tensor] = None,
304
+ return_dict: bool = True,
305
+ ):
306
+ """
307
+ The [`PixArtTransformer2DModel`] forward method.
308
+
309
+ Args:
310
+ hidden_states (`torch.FloatTensor` of shape `(batch size, channel, height, width)`):
311
+ Input `hidden_states`.
312
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
313
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
314
+ self-attention.
315
+ timestep (`torch.LongTensor`, *optional*):
316
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
317
+ added_cond_kwargs: (`Dict[str, Any]`, *optional*): Additional conditions to be used as inputs.
318
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
319
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
320
+ `self.processor` in
321
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
322
+ attention_mask ( `torch.Tensor`, *optional*):
323
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
324
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
325
+ negative values to the attention scores corresponding to "discard" tokens.
326
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
327
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
328
+
329
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
330
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
331
+
332
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
333
+ above. This bias will be added to the cross-attention scores.
334
+ return_dict (`bool`, *optional*, defaults to `True`):
335
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
336
+ tuple.
337
+
338
+ Returns:
339
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
340
+ `tuple` where the first element is the sample tensor.
341
+ """
342
+ if self.use_additional_conditions and added_cond_kwargs is None:
343
+ raise ValueError("`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`.")
344
+
345
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
346
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
347
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
348
+ # expects mask of shape:
349
+ # [batch, key_tokens]
350
+ # adds singleton query_tokens dimension:
351
+ # [batch, 1, key_tokens]
352
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
353
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
354
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
355
+ if attention_mask is not None and attention_mask.ndim == 2:
356
+ # assume that mask is expressed as:
357
+ # (1 = keep, 0 = discard)
358
+ # convert mask into a bias that can be added to attention scores:
359
+ # (keep = +0, discard = -10000.0)
360
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
361
+ attention_mask = attention_mask.unsqueeze(1)
362
+
363
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
364
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
365
+ encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
366
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
367
+
368
+ # 1. Input
369
+ batch_size = hidden_states.shape[0]
370
+ height, width = (
371
+ hidden_states.shape[-2] // self.config.patch_size,
372
+ hidden_states.shape[-1] // self.config.patch_size,
373
+ )
374
+ hidden_states = self.pos_embed(hidden_states)
375
+
376
+ timestep, embedded_timestep = self.adaln_single(
377
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
378
+ )
379
+
380
+ if self.caption_projection is not None:
381
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
382
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
383
+
384
+ # 2. Blocks
385
+ for block in self.transformer_blocks:
386
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
387
+ hidden_states = self._gradient_checkpointing_func(
388
+ block,
389
+ hidden_states,
390
+ attention_mask,
391
+ encoder_hidden_states,
392
+ encoder_attention_mask,
393
+ timestep,
394
+ cross_attention_kwargs,
395
+ None,
396
+ )
397
+ else:
398
+ hidden_states = block(
399
+ hidden_states,
400
+ attention_mask=attention_mask,
401
+ encoder_hidden_states=encoder_hidden_states,
402
+ encoder_attention_mask=encoder_attention_mask,
403
+ timestep=timestep,
404
+ cross_attention_kwargs=cross_attention_kwargs,
405
+ class_labels=None,
406
+ )
407
+
408
+ # 3. Output
409
+ shift, scale = (
410
+ self.scale_shift_table[None] + embedded_timestep[:, None].to(self.scale_shift_table.device)
411
+ ).chunk(2, dim=1)
412
+ hidden_states = self.norm_out(hidden_states)
413
+ # Modulation
414
+ hidden_states = hidden_states * (1 + scale.to(hidden_states.device)) + shift.to(hidden_states.device)
415
+ hidden_states = self.proj_out(hidden_states)
416
+ hidden_states = hidden_states.squeeze(1)
417
+
418
+ # unpatchify
419
+ hidden_states = hidden_states.reshape(
420
+ shape=(-1, height, width, self.config.patch_size, self.config.patch_size, self.out_channels)
421
+ )
422
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
423
+ output = hidden_states.reshape(
424
+ shape=(-1, self.out_channels, height * self.config.patch_size, width * self.config.patch_size)
425
+ )
426
+
427
+ if not return_dict:
428
+ return (output,)
429
+
430
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/prior_transformer.py ADDED
@@ -0,0 +1,384 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import Dict, Optional, Union
3
+
4
+ import torch
5
+ import torch.nn.functional as F
6
+ from torch import nn
7
+
8
+ from ...configuration_utils import ConfigMixin, register_to_config
9
+ from ...loaders import PeftAdapterMixin, UNet2DConditionLoadersMixin
10
+ from ...utils import BaseOutput
11
+ from ..attention import BasicTransformerBlock
12
+ from ..attention_processor import (
13
+ ADDED_KV_ATTENTION_PROCESSORS,
14
+ CROSS_ATTENTION_PROCESSORS,
15
+ AttentionProcessor,
16
+ AttnAddedKVProcessor,
17
+ AttnProcessor,
18
+ )
19
+ from ..embeddings import TimestepEmbedding, Timesteps
20
+ from ..modeling_utils import ModelMixin
21
+
22
+
23
+ @dataclass
24
+ class PriorTransformerOutput(BaseOutput):
25
+ """
26
+ The output of [`PriorTransformer`].
27
+
28
+ Args:
29
+ predicted_image_embedding (`torch.Tensor` of shape `(batch_size, embedding_dim)`):
30
+ The predicted CLIP image embedding conditioned on the CLIP text embedding input.
31
+ """
32
+
33
+ predicted_image_embedding: torch.Tensor
34
+
35
+
36
+ class PriorTransformer(ModelMixin, ConfigMixin, UNet2DConditionLoadersMixin, PeftAdapterMixin):
37
+ """
38
+ A Prior Transformer model.
39
+
40
+ Parameters:
41
+ num_attention_heads (`int`, *optional*, defaults to 32): The number of heads to use for multi-head attention.
42
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
43
+ num_layers (`int`, *optional*, defaults to 20): The number of layers of Transformer blocks to use.
44
+ embedding_dim (`int`, *optional*, defaults to 768): The dimension of the model input `hidden_states`
45
+ num_embeddings (`int`, *optional*, defaults to 77):
46
+ The number of embeddings of the model input `hidden_states`
47
+ additional_embeddings (`int`, *optional*, defaults to 4): The number of additional tokens appended to the
48
+ projected `hidden_states`. The actual length of the used `hidden_states` is `num_embeddings +
49
+ additional_embeddings`.
50
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
51
+ time_embed_act_fn (`str`, *optional*, defaults to 'silu'):
52
+ The activation function to use to create timestep embeddings.
53
+ norm_in_type (`str`, *optional*, defaults to None): The normalization layer to apply on hidden states before
54
+ passing to Transformer blocks. Set it to `None` if normalization is not needed.
55
+ embedding_proj_norm_type (`str`, *optional*, defaults to None):
56
+ The normalization layer to apply on the input `proj_embedding`. Set it to `None` if normalization is not
57
+ needed.
58
+ encoder_hid_proj_type (`str`, *optional*, defaults to `linear`):
59
+ The projection layer to apply on the input `encoder_hidden_states`. Set it to `None` if
60
+ `encoder_hidden_states` is `None`.
61
+ added_emb_type (`str`, *optional*, defaults to `prd`): Additional embeddings to condition the model.
62
+ Choose from `prd` or `None`. if choose `prd`, it will prepend a token indicating the (quantized) dot
63
+ product between the text embedding and image embedding as proposed in the unclip paper
64
+ https://arxiv.org/abs/2204.06125 If it is `None`, no additional embeddings will be prepended.
65
+ time_embed_dim (`int, *optional*, defaults to None): The dimension of timestep embeddings.
66
+ If None, will be set to `num_attention_heads * attention_head_dim`
67
+ embedding_proj_dim (`int`, *optional*, default to None):
68
+ The dimension of `proj_embedding`. If None, will be set to `embedding_dim`.
69
+ clip_embed_dim (`int`, *optional*, default to None):
70
+ The dimension of the output. If None, will be set to `embedding_dim`.
71
+ """
72
+
73
+ @register_to_config
74
+ def __init__(
75
+ self,
76
+ num_attention_heads: int = 32,
77
+ attention_head_dim: int = 64,
78
+ num_layers: int = 20,
79
+ embedding_dim: int = 768,
80
+ num_embeddings=77,
81
+ additional_embeddings=4,
82
+ dropout: float = 0.0,
83
+ time_embed_act_fn: str = "silu",
84
+ norm_in_type: Optional[str] = None, # layer
85
+ embedding_proj_norm_type: Optional[str] = None, # layer
86
+ encoder_hid_proj_type: Optional[str] = "linear", # linear
87
+ added_emb_type: Optional[str] = "prd", # prd
88
+ time_embed_dim: Optional[int] = None,
89
+ embedding_proj_dim: Optional[int] = None,
90
+ clip_embed_dim: Optional[int] = None,
91
+ ):
92
+ super().__init__()
93
+ self.num_attention_heads = num_attention_heads
94
+ self.attention_head_dim = attention_head_dim
95
+ inner_dim = num_attention_heads * attention_head_dim
96
+ self.additional_embeddings = additional_embeddings
97
+
98
+ time_embed_dim = time_embed_dim or inner_dim
99
+ embedding_proj_dim = embedding_proj_dim or embedding_dim
100
+ clip_embed_dim = clip_embed_dim or embedding_dim
101
+
102
+ self.time_proj = Timesteps(inner_dim, True, 0)
103
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, out_dim=inner_dim, act_fn=time_embed_act_fn)
104
+
105
+ self.proj_in = nn.Linear(embedding_dim, inner_dim)
106
+
107
+ if embedding_proj_norm_type is None:
108
+ self.embedding_proj_norm = None
109
+ elif embedding_proj_norm_type == "layer":
110
+ self.embedding_proj_norm = nn.LayerNorm(embedding_proj_dim)
111
+ else:
112
+ raise ValueError(f"unsupported embedding_proj_norm_type: {embedding_proj_norm_type}")
113
+
114
+ self.embedding_proj = nn.Linear(embedding_proj_dim, inner_dim)
115
+
116
+ if encoder_hid_proj_type is None:
117
+ self.encoder_hidden_states_proj = None
118
+ elif encoder_hid_proj_type == "linear":
119
+ self.encoder_hidden_states_proj = nn.Linear(embedding_dim, inner_dim)
120
+ else:
121
+ raise ValueError(f"unsupported encoder_hid_proj_type: {encoder_hid_proj_type}")
122
+
123
+ self.positional_embedding = nn.Parameter(torch.zeros(1, num_embeddings + additional_embeddings, inner_dim))
124
+
125
+ if added_emb_type == "prd":
126
+ self.prd_embedding = nn.Parameter(torch.zeros(1, 1, inner_dim))
127
+ elif added_emb_type is None:
128
+ self.prd_embedding = None
129
+ else:
130
+ raise ValueError(
131
+ f"`added_emb_type`: {added_emb_type} is not supported. Make sure to choose one of `'prd'` or `None`."
132
+ )
133
+
134
+ self.transformer_blocks = nn.ModuleList(
135
+ [
136
+ BasicTransformerBlock(
137
+ inner_dim,
138
+ num_attention_heads,
139
+ attention_head_dim,
140
+ dropout=dropout,
141
+ activation_fn="gelu",
142
+ attention_bias=True,
143
+ )
144
+ for d in range(num_layers)
145
+ ]
146
+ )
147
+
148
+ if norm_in_type == "layer":
149
+ self.norm_in = nn.LayerNorm(inner_dim)
150
+ elif norm_in_type is None:
151
+ self.norm_in = None
152
+ else:
153
+ raise ValueError(f"Unsupported norm_in_type: {norm_in_type}.")
154
+
155
+ self.norm_out = nn.LayerNorm(inner_dim)
156
+
157
+ self.proj_to_clip_embeddings = nn.Linear(inner_dim, clip_embed_dim)
158
+
159
+ causal_attention_mask = torch.full(
160
+ [num_embeddings + additional_embeddings, num_embeddings + additional_embeddings], -10000.0
161
+ )
162
+ causal_attention_mask.triu_(1)
163
+ causal_attention_mask = causal_attention_mask[None, ...]
164
+ self.register_buffer("causal_attention_mask", causal_attention_mask, persistent=False)
165
+
166
+ self.clip_mean = nn.Parameter(torch.zeros(1, clip_embed_dim))
167
+ self.clip_std = nn.Parameter(torch.zeros(1, clip_embed_dim))
168
+
169
+ @property
170
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
171
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
172
+ r"""
173
+ Returns:
174
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
175
+ indexed by its weight name.
176
+ """
177
+ # set recursively
178
+ processors = {}
179
+
180
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
181
+ if hasattr(module, "get_processor"):
182
+ processors[f"{name}.processor"] = module.get_processor()
183
+
184
+ for sub_name, child in module.named_children():
185
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
186
+
187
+ return processors
188
+
189
+ for name, module in self.named_children():
190
+ fn_recursive_add_processors(name, module, processors)
191
+
192
+ return processors
193
+
194
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
195
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
196
+ r"""
197
+ Sets the attention processor to use to compute attention.
198
+
199
+ Parameters:
200
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
201
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
202
+ for **all** `Attention` layers.
203
+
204
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
205
+ processor. This is strongly recommended when setting trainable attention processors.
206
+
207
+ """
208
+ count = len(self.attn_processors.keys())
209
+
210
+ if isinstance(processor, dict) and len(processor) != count:
211
+ raise ValueError(
212
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
213
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
214
+ )
215
+
216
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
217
+ if hasattr(module, "set_processor"):
218
+ if not isinstance(processor, dict):
219
+ module.set_processor(processor)
220
+ else:
221
+ module.set_processor(processor.pop(f"{name}.processor"))
222
+
223
+ for sub_name, child in module.named_children():
224
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
225
+
226
+ for name, module in self.named_children():
227
+ fn_recursive_attn_processor(name, module, processor)
228
+
229
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_default_attn_processor
230
+ def set_default_attn_processor(self):
231
+ """
232
+ Disables custom attention processors and sets the default attention implementation.
233
+ """
234
+ if all(proc.__class__ in ADDED_KV_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
235
+ processor = AttnAddedKVProcessor()
236
+ elif all(proc.__class__ in CROSS_ATTENTION_PROCESSORS for proc in self.attn_processors.values()):
237
+ processor = AttnProcessor()
238
+ else:
239
+ raise ValueError(
240
+ f"Cannot call `set_default_attn_processor` when attention processors are of type {next(iter(self.attn_processors.values()))}"
241
+ )
242
+
243
+ self.set_attn_processor(processor)
244
+
245
+ def forward(
246
+ self,
247
+ hidden_states,
248
+ timestep: Union[torch.Tensor, float, int],
249
+ proj_embedding: torch.Tensor,
250
+ encoder_hidden_states: Optional[torch.Tensor] = None,
251
+ attention_mask: Optional[torch.BoolTensor] = None,
252
+ return_dict: bool = True,
253
+ ):
254
+ """
255
+ The [`PriorTransformer`] forward method.
256
+
257
+ Args:
258
+ hidden_states (`torch.Tensor` of shape `(batch_size, embedding_dim)`):
259
+ The currently predicted image embeddings.
260
+ timestep (`torch.LongTensor`):
261
+ Current denoising step.
262
+ proj_embedding (`torch.Tensor` of shape `(batch_size, embedding_dim)`):
263
+ Projected embedding vector the denoising process is conditioned on.
264
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, num_embeddings, embedding_dim)`):
265
+ Hidden states of the text embeddings the denoising process is conditioned on.
266
+ attention_mask (`torch.BoolTensor` of shape `(batch_size, num_embeddings)`):
267
+ Text mask for the text embeddings.
268
+ return_dict (`bool`, *optional*, defaults to `True`):
269
+ Whether or not to return a [`~models.transformers.prior_transformer.PriorTransformerOutput`] instead of
270
+ a plain tuple.
271
+
272
+ Returns:
273
+ [`~models.transformers.prior_transformer.PriorTransformerOutput`] or `tuple`:
274
+ If return_dict is True, a [`~models.transformers.prior_transformer.PriorTransformerOutput`] is
275
+ returned, otherwise a tuple is returned where the first element is the sample tensor.
276
+ """
277
+ batch_size = hidden_states.shape[0]
278
+
279
+ timesteps = timestep
280
+ if not torch.is_tensor(timesteps):
281
+ timesteps = torch.tensor([timesteps], dtype=torch.long, device=hidden_states.device)
282
+ elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
283
+ timesteps = timesteps[None].to(hidden_states.device)
284
+
285
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
286
+ timesteps = timesteps * torch.ones(batch_size, dtype=timesteps.dtype, device=timesteps.device)
287
+
288
+ timesteps_projected = self.time_proj(timesteps)
289
+
290
+ # timesteps does not contain any weights and will always return f32 tensors
291
+ # but time_embedding might be fp16, so we need to cast here.
292
+ timesteps_projected = timesteps_projected.to(dtype=self.dtype)
293
+ time_embeddings = self.time_embedding(timesteps_projected)
294
+
295
+ if self.embedding_proj_norm is not None:
296
+ proj_embedding = self.embedding_proj_norm(proj_embedding)
297
+
298
+ proj_embeddings = self.embedding_proj(proj_embedding)
299
+ if self.encoder_hidden_states_proj is not None and encoder_hidden_states is not None:
300
+ encoder_hidden_states = self.encoder_hidden_states_proj(encoder_hidden_states)
301
+ elif self.encoder_hidden_states_proj is not None and encoder_hidden_states is None:
302
+ raise ValueError("`encoder_hidden_states_proj` requires `encoder_hidden_states` to be set")
303
+
304
+ hidden_states = self.proj_in(hidden_states)
305
+
306
+ positional_embeddings = self.positional_embedding.to(hidden_states.dtype)
307
+
308
+ additional_embeds = []
309
+ additional_embeddings_len = 0
310
+
311
+ if encoder_hidden_states is not None:
312
+ additional_embeds.append(encoder_hidden_states)
313
+ additional_embeddings_len += encoder_hidden_states.shape[1]
314
+
315
+ if len(proj_embeddings.shape) == 2:
316
+ proj_embeddings = proj_embeddings[:, None, :]
317
+
318
+ if len(hidden_states.shape) == 2:
319
+ hidden_states = hidden_states[:, None, :]
320
+
321
+ additional_embeds = additional_embeds + [
322
+ proj_embeddings,
323
+ time_embeddings[:, None, :],
324
+ hidden_states,
325
+ ]
326
+
327
+ if self.prd_embedding is not None:
328
+ prd_embedding = self.prd_embedding.to(hidden_states.dtype).expand(batch_size, -1, -1)
329
+ additional_embeds.append(prd_embedding)
330
+
331
+ hidden_states = torch.cat(
332
+ additional_embeds,
333
+ dim=1,
334
+ )
335
+
336
+ # Allow positional_embedding to not include the `addtional_embeddings` and instead pad it with zeros for these additional tokens
337
+ additional_embeddings_len = additional_embeddings_len + proj_embeddings.shape[1] + 1
338
+ if positional_embeddings.shape[1] < hidden_states.shape[1]:
339
+ positional_embeddings = F.pad(
340
+ positional_embeddings,
341
+ (
342
+ 0,
343
+ 0,
344
+ additional_embeddings_len,
345
+ self.prd_embedding.shape[1] if self.prd_embedding is not None else 0,
346
+ ),
347
+ value=0.0,
348
+ )
349
+
350
+ hidden_states = hidden_states + positional_embeddings
351
+
352
+ if attention_mask is not None:
353
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
354
+ attention_mask = F.pad(attention_mask, (0, self.additional_embeddings), value=0.0)
355
+ attention_mask = (attention_mask[:, None, :] + self.causal_attention_mask).to(hidden_states.dtype)
356
+ attention_mask = attention_mask.repeat_interleave(
357
+ self.config.num_attention_heads,
358
+ dim=0,
359
+ output_size=attention_mask.shape[0] * self.config.num_attention_heads,
360
+ )
361
+
362
+ if self.norm_in is not None:
363
+ hidden_states = self.norm_in(hidden_states)
364
+
365
+ for block in self.transformer_blocks:
366
+ hidden_states = block(hidden_states, attention_mask=attention_mask)
367
+
368
+ hidden_states = self.norm_out(hidden_states)
369
+
370
+ if self.prd_embedding is not None:
371
+ hidden_states = hidden_states[:, -1]
372
+ else:
373
+ hidden_states = hidden_states[:, additional_embeddings_len:]
374
+
375
+ predicted_image_embedding = self.proj_to_clip_embeddings(hidden_states)
376
+
377
+ if not return_dict:
378
+ return (predicted_image_embedding,)
379
+
380
+ return PriorTransformerOutput(predicted_image_embedding=predicted_image_embedding)
381
+
382
+ def post_process_latents(self, prior_latents):
383
+ prior_latents = (prior_latents * self.clip_std) + self.clip_mean
384
+ return prior_latents
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/sana_transformer.py ADDED
@@ -0,0 +1,597 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Dict, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn.functional as F
19
+ from torch import nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...loaders import FromOriginalModelMixin, PeftAdapterMixin
23
+ from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
24
+ from ..attention_processor import (
25
+ Attention,
26
+ AttentionProcessor,
27
+ SanaLinearAttnProcessor2_0,
28
+ )
29
+ from ..embeddings import PatchEmbed, PixArtAlphaTextProjection, TimestepEmbedding, Timesteps
30
+ from ..modeling_outputs import Transformer2DModelOutput
31
+ from ..modeling_utils import ModelMixin
32
+ from ..normalization import AdaLayerNormSingle, RMSNorm
33
+
34
+
35
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
36
+
37
+
38
+ class GLUMBConv(nn.Module):
39
+ def __init__(
40
+ self,
41
+ in_channels: int,
42
+ out_channels: int,
43
+ expand_ratio: float = 4,
44
+ norm_type: Optional[str] = None,
45
+ residual_connection: bool = True,
46
+ ) -> None:
47
+ super().__init__()
48
+
49
+ hidden_channels = int(expand_ratio * in_channels)
50
+ self.norm_type = norm_type
51
+ self.residual_connection = residual_connection
52
+
53
+ self.nonlinearity = nn.SiLU()
54
+ self.conv_inverted = nn.Conv2d(in_channels, hidden_channels * 2, 1, 1, 0)
55
+ self.conv_depth = nn.Conv2d(hidden_channels * 2, hidden_channels * 2, 3, 1, 1, groups=hidden_channels * 2)
56
+ self.conv_point = nn.Conv2d(hidden_channels, out_channels, 1, 1, 0, bias=False)
57
+
58
+ self.norm = None
59
+ if norm_type == "rms_norm":
60
+ self.norm = RMSNorm(out_channels, eps=1e-5, elementwise_affine=True, bias=True)
61
+
62
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
63
+ if self.residual_connection:
64
+ residual = hidden_states
65
+
66
+ hidden_states = self.conv_inverted(hidden_states)
67
+ hidden_states = self.nonlinearity(hidden_states)
68
+
69
+ hidden_states = self.conv_depth(hidden_states)
70
+ hidden_states, gate = torch.chunk(hidden_states, 2, dim=1)
71
+ hidden_states = hidden_states * self.nonlinearity(gate)
72
+
73
+ hidden_states = self.conv_point(hidden_states)
74
+
75
+ if self.norm_type == "rms_norm":
76
+ # move channel to the last dimension so we apply RMSnorm across channel dimension
77
+ hidden_states = self.norm(hidden_states.movedim(1, -1)).movedim(-1, 1)
78
+
79
+ if self.residual_connection:
80
+ hidden_states = hidden_states + residual
81
+
82
+ return hidden_states
83
+
84
+
85
+ class SanaModulatedNorm(nn.Module):
86
+ def __init__(self, dim: int, elementwise_affine: bool = False, eps: float = 1e-6):
87
+ super().__init__()
88
+ self.norm = nn.LayerNorm(dim, elementwise_affine=elementwise_affine, eps=eps)
89
+
90
+ def forward(
91
+ self, hidden_states: torch.Tensor, temb: torch.Tensor, scale_shift_table: torch.Tensor
92
+ ) -> torch.Tensor:
93
+ hidden_states = self.norm(hidden_states)
94
+ shift, scale = (scale_shift_table[None] + temb[:, None].to(scale_shift_table.device)).chunk(2, dim=1)
95
+ hidden_states = hidden_states * (1 + scale) + shift
96
+ return hidden_states
97
+
98
+
99
+ class SanaCombinedTimestepGuidanceEmbeddings(nn.Module):
100
+ def __init__(self, embedding_dim):
101
+ super().__init__()
102
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
103
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
104
+
105
+ self.guidance_condition_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
106
+ self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
107
+
108
+ self.silu = nn.SiLU()
109
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=True)
110
+
111
+ def forward(self, timestep: torch.Tensor, guidance: torch.Tensor = None, hidden_dtype: torch.dtype = None):
112
+ timesteps_proj = self.time_proj(timestep)
113
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=hidden_dtype)) # (N, D)
114
+
115
+ guidance_proj = self.guidance_condition_proj(guidance)
116
+ guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=hidden_dtype))
117
+ conditioning = timesteps_emb + guidance_emb
118
+
119
+ return self.linear(self.silu(conditioning)), conditioning
120
+
121
+
122
+ class SanaAttnProcessor2_0:
123
+ r"""
124
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
125
+ """
126
+
127
+ def __init__(self):
128
+ if not hasattr(F, "scaled_dot_product_attention"):
129
+ raise ImportError("SanaAttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
130
+
131
+ def __call__(
132
+ self,
133
+ attn: Attention,
134
+ hidden_states: torch.Tensor,
135
+ encoder_hidden_states: Optional[torch.Tensor] = None,
136
+ attention_mask: Optional[torch.Tensor] = None,
137
+ ) -> torch.Tensor:
138
+ batch_size, sequence_length, _ = (
139
+ hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
140
+ )
141
+
142
+ if attention_mask is not None:
143
+ attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
144
+ # scaled_dot_product_attention expects attention_mask shape to be
145
+ # (batch, heads, source_length, target_length)
146
+ attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
147
+
148
+ query = attn.to_q(hidden_states)
149
+
150
+ if encoder_hidden_states is None:
151
+ encoder_hidden_states = hidden_states
152
+
153
+ key = attn.to_k(encoder_hidden_states)
154
+ value = attn.to_v(encoder_hidden_states)
155
+
156
+ if attn.norm_q is not None:
157
+ query = attn.norm_q(query)
158
+ if attn.norm_k is not None:
159
+ key = attn.norm_k(key)
160
+
161
+ inner_dim = key.shape[-1]
162
+ head_dim = inner_dim // attn.heads
163
+
164
+ query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
165
+
166
+ key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
167
+ value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
168
+
169
+ # the output of sdp = (batch, num_heads, seq_len, head_dim)
170
+ # TODO: add support for attn.scale when we move to Torch 2.1
171
+ hidden_states = F.scaled_dot_product_attention(
172
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
173
+ )
174
+
175
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
176
+ hidden_states = hidden_states.to(query.dtype)
177
+
178
+ # linear proj
179
+ hidden_states = attn.to_out[0](hidden_states)
180
+ # dropout
181
+ hidden_states = attn.to_out[1](hidden_states)
182
+
183
+ hidden_states = hidden_states / attn.rescale_output_factor
184
+
185
+ return hidden_states
186
+
187
+
188
+ class SanaTransformerBlock(nn.Module):
189
+ r"""
190
+ Transformer block introduced in [Sana](https://huggingface.co/papers/2410.10629).
191
+ """
192
+
193
+ def __init__(
194
+ self,
195
+ dim: int = 2240,
196
+ num_attention_heads: int = 70,
197
+ attention_head_dim: int = 32,
198
+ dropout: float = 0.0,
199
+ num_cross_attention_heads: Optional[int] = 20,
200
+ cross_attention_head_dim: Optional[int] = 112,
201
+ cross_attention_dim: Optional[int] = 2240,
202
+ attention_bias: bool = True,
203
+ norm_elementwise_affine: bool = False,
204
+ norm_eps: float = 1e-6,
205
+ attention_out_bias: bool = True,
206
+ mlp_ratio: float = 2.5,
207
+ qk_norm: Optional[str] = None,
208
+ ) -> None:
209
+ super().__init__()
210
+
211
+ # 1. Self Attention
212
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=False, eps=norm_eps)
213
+ self.attn1 = Attention(
214
+ query_dim=dim,
215
+ heads=num_attention_heads,
216
+ dim_head=attention_head_dim,
217
+ kv_heads=num_attention_heads if qk_norm is not None else None,
218
+ qk_norm=qk_norm,
219
+ dropout=dropout,
220
+ bias=attention_bias,
221
+ cross_attention_dim=None,
222
+ processor=SanaLinearAttnProcessor2_0(),
223
+ )
224
+
225
+ # 2. Cross Attention
226
+ if cross_attention_dim is not None:
227
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
228
+ self.attn2 = Attention(
229
+ query_dim=dim,
230
+ qk_norm=qk_norm,
231
+ kv_heads=num_cross_attention_heads if qk_norm is not None else None,
232
+ cross_attention_dim=cross_attention_dim,
233
+ heads=num_cross_attention_heads,
234
+ dim_head=cross_attention_head_dim,
235
+ dropout=dropout,
236
+ bias=True,
237
+ out_bias=attention_out_bias,
238
+ processor=SanaAttnProcessor2_0(),
239
+ )
240
+
241
+ # 3. Feed-forward
242
+ self.ff = GLUMBConv(dim, dim, mlp_ratio, norm_type=None, residual_connection=False)
243
+
244
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
245
+
246
+ def forward(
247
+ self,
248
+ hidden_states: torch.Tensor,
249
+ attention_mask: Optional[torch.Tensor] = None,
250
+ encoder_hidden_states: Optional[torch.Tensor] = None,
251
+ encoder_attention_mask: Optional[torch.Tensor] = None,
252
+ timestep: Optional[torch.LongTensor] = None,
253
+ height: int = None,
254
+ width: int = None,
255
+ ) -> torch.Tensor:
256
+ batch_size = hidden_states.shape[0]
257
+
258
+ # 1. Modulation
259
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
260
+ self.scale_shift_table[None] + timestep.reshape(batch_size, 6, -1)
261
+ ).chunk(6, dim=1)
262
+
263
+ # 2. Self Attention
264
+ norm_hidden_states = self.norm1(hidden_states)
265
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
266
+ norm_hidden_states = norm_hidden_states.to(hidden_states.dtype)
267
+
268
+ attn_output = self.attn1(norm_hidden_states)
269
+ hidden_states = hidden_states + gate_msa * attn_output
270
+
271
+ # 3. Cross Attention
272
+ if self.attn2 is not None:
273
+ attn_output = self.attn2(
274
+ hidden_states,
275
+ encoder_hidden_states=encoder_hidden_states,
276
+ attention_mask=encoder_attention_mask,
277
+ )
278
+ hidden_states = attn_output + hidden_states
279
+
280
+ # 4. Feed-forward
281
+ norm_hidden_states = self.norm2(hidden_states)
282
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
283
+
284
+ norm_hidden_states = norm_hidden_states.unflatten(1, (height, width)).permute(0, 3, 1, 2)
285
+ ff_output = self.ff(norm_hidden_states)
286
+ ff_output = ff_output.flatten(2, 3).permute(0, 2, 1)
287
+ hidden_states = hidden_states + gate_mlp * ff_output
288
+
289
+ return hidden_states
290
+
291
+
292
+ class SanaTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin):
293
+ r"""
294
+ A 2D Transformer model introduced in [Sana](https://huggingface.co/papers/2410.10629) family of models.
295
+
296
+ Args:
297
+ in_channels (`int`, defaults to `32`):
298
+ The number of channels in the input.
299
+ out_channels (`int`, *optional*, defaults to `32`):
300
+ The number of channels in the output.
301
+ num_attention_heads (`int`, defaults to `70`):
302
+ The number of heads to use for multi-head attention.
303
+ attention_head_dim (`int`, defaults to `32`):
304
+ The number of channels in each head.
305
+ num_layers (`int`, defaults to `20`):
306
+ The number of layers of Transformer blocks to use.
307
+ num_cross_attention_heads (`int`, *optional*, defaults to `20`):
308
+ The number of heads to use for cross-attention.
309
+ cross_attention_head_dim (`int`, *optional*, defaults to `112`):
310
+ The number of channels in each head for cross-attention.
311
+ cross_attention_dim (`int`, *optional*, defaults to `2240`):
312
+ The number of channels in the cross-attention output.
313
+ caption_channels (`int`, defaults to `2304`):
314
+ The number of channels in the caption embeddings.
315
+ mlp_ratio (`float`, defaults to `2.5`):
316
+ The expansion ratio to use in the GLUMBConv layer.
317
+ dropout (`float`, defaults to `0.0`):
318
+ The dropout probability.
319
+ attention_bias (`bool`, defaults to `False`):
320
+ Whether to use bias in the attention layer.
321
+ sample_size (`int`, defaults to `32`):
322
+ The base size of the input latent.
323
+ patch_size (`int`, defaults to `1`):
324
+ The size of the patches to use in the patch embedding layer.
325
+ norm_elementwise_affine (`bool`, defaults to `False`):
326
+ Whether to use elementwise affinity in the normalization layer.
327
+ norm_eps (`float`, defaults to `1e-6`):
328
+ The epsilon value for the normalization layer.
329
+ qk_norm (`str`, *optional*, defaults to `None`):
330
+ The normalization to use for the query and key.
331
+ timestep_scale (`float`, defaults to `1.0`):
332
+ The scale to use for the timesteps.
333
+ """
334
+
335
+ _supports_gradient_checkpointing = True
336
+ _no_split_modules = ["SanaTransformerBlock", "PatchEmbed", "SanaModulatedNorm"]
337
+ _skip_layerwise_casting_patterns = ["patch_embed", "norm"]
338
+
339
+ @register_to_config
340
+ def __init__(
341
+ self,
342
+ in_channels: int = 32,
343
+ out_channels: Optional[int] = 32,
344
+ num_attention_heads: int = 70,
345
+ attention_head_dim: int = 32,
346
+ num_layers: int = 20,
347
+ num_cross_attention_heads: Optional[int] = 20,
348
+ cross_attention_head_dim: Optional[int] = 112,
349
+ cross_attention_dim: Optional[int] = 2240,
350
+ caption_channels: int = 2304,
351
+ mlp_ratio: float = 2.5,
352
+ dropout: float = 0.0,
353
+ attention_bias: bool = False,
354
+ sample_size: int = 32,
355
+ patch_size: int = 1,
356
+ norm_elementwise_affine: bool = False,
357
+ norm_eps: float = 1e-6,
358
+ interpolation_scale: Optional[int] = None,
359
+ guidance_embeds: bool = False,
360
+ guidance_embeds_scale: float = 0.1,
361
+ qk_norm: Optional[str] = None,
362
+ timestep_scale: float = 1.0,
363
+ ) -> None:
364
+ super().__init__()
365
+
366
+ out_channels = out_channels or in_channels
367
+ inner_dim = num_attention_heads * attention_head_dim
368
+
369
+ # 1. Patch Embedding
370
+ self.patch_embed = PatchEmbed(
371
+ height=sample_size,
372
+ width=sample_size,
373
+ patch_size=patch_size,
374
+ in_channels=in_channels,
375
+ embed_dim=inner_dim,
376
+ interpolation_scale=interpolation_scale,
377
+ pos_embed_type="sincos" if interpolation_scale is not None else None,
378
+ )
379
+
380
+ # 2. Additional condition embeddings
381
+ if guidance_embeds:
382
+ self.time_embed = SanaCombinedTimestepGuidanceEmbeddings(inner_dim)
383
+ else:
384
+ self.time_embed = AdaLayerNormSingle(inner_dim)
385
+
386
+ self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=inner_dim)
387
+ self.caption_norm = RMSNorm(inner_dim, eps=1e-5, elementwise_affine=True)
388
+
389
+ # 3. Transformer blocks
390
+ self.transformer_blocks = nn.ModuleList(
391
+ [
392
+ SanaTransformerBlock(
393
+ inner_dim,
394
+ num_attention_heads,
395
+ attention_head_dim,
396
+ dropout=dropout,
397
+ num_cross_attention_heads=num_cross_attention_heads,
398
+ cross_attention_head_dim=cross_attention_head_dim,
399
+ cross_attention_dim=cross_attention_dim,
400
+ attention_bias=attention_bias,
401
+ norm_elementwise_affine=norm_elementwise_affine,
402
+ norm_eps=norm_eps,
403
+ mlp_ratio=mlp_ratio,
404
+ qk_norm=qk_norm,
405
+ )
406
+ for _ in range(num_layers)
407
+ ]
408
+ )
409
+
410
+ # 4. Output blocks
411
+ self.scale_shift_table = nn.Parameter(torch.randn(2, inner_dim) / inner_dim**0.5)
412
+ self.norm_out = SanaModulatedNorm(inner_dim, elementwise_affine=False, eps=1e-6)
413
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels)
414
+
415
+ self.gradient_checkpointing = False
416
+
417
+ @property
418
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
419
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
420
+ r"""
421
+ Returns:
422
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
423
+ indexed by its weight name.
424
+ """
425
+ # set recursively
426
+ processors = {}
427
+
428
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
429
+ if hasattr(module, "get_processor"):
430
+ processors[f"{name}.processor"] = module.get_processor()
431
+
432
+ for sub_name, child in module.named_children():
433
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
434
+
435
+ return processors
436
+
437
+ for name, module in self.named_children():
438
+ fn_recursive_add_processors(name, module, processors)
439
+
440
+ return processors
441
+
442
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
443
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
444
+ r"""
445
+ Sets the attention processor to use to compute attention.
446
+
447
+ Parameters:
448
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
449
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
450
+ for **all** `Attention` layers.
451
+
452
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
453
+ processor. This is strongly recommended when setting trainable attention processors.
454
+
455
+ """
456
+ count = len(self.attn_processors.keys())
457
+
458
+ if isinstance(processor, dict) and len(processor) != count:
459
+ raise ValueError(
460
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
461
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
462
+ )
463
+
464
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
465
+ if hasattr(module, "set_processor"):
466
+ if not isinstance(processor, dict):
467
+ module.set_processor(processor)
468
+ else:
469
+ module.set_processor(processor.pop(f"{name}.processor"))
470
+
471
+ for sub_name, child in module.named_children():
472
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
473
+
474
+ for name, module in self.named_children():
475
+ fn_recursive_attn_processor(name, module, processor)
476
+
477
+ def forward(
478
+ self,
479
+ hidden_states: torch.Tensor,
480
+ encoder_hidden_states: torch.Tensor,
481
+ timestep: torch.Tensor,
482
+ guidance: Optional[torch.Tensor] = None,
483
+ encoder_attention_mask: Optional[torch.Tensor] = None,
484
+ attention_mask: Optional[torch.Tensor] = None,
485
+ attention_kwargs: Optional[Dict[str, Any]] = None,
486
+ controlnet_block_samples: Optional[Tuple[torch.Tensor]] = None,
487
+ return_dict: bool = True,
488
+ ) -> Union[Tuple[torch.Tensor, ...], Transformer2DModelOutput]:
489
+ if attention_kwargs is not None:
490
+ attention_kwargs = attention_kwargs.copy()
491
+ lora_scale = attention_kwargs.pop("scale", 1.0)
492
+ else:
493
+ lora_scale = 1.0
494
+
495
+ if USE_PEFT_BACKEND:
496
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
497
+ scale_lora_layers(self, lora_scale)
498
+ else:
499
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
500
+ logger.warning(
501
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
502
+ )
503
+
504
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
505
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
506
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
507
+ # expects mask of shape:
508
+ # [batch, key_tokens]
509
+ # adds singleton query_tokens dimension:
510
+ # [batch, 1, key_tokens]
511
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
512
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
513
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
514
+ if attention_mask is not None and attention_mask.ndim == 2:
515
+ # assume that mask is expressed as:
516
+ # (1 = keep, 0 = discard)
517
+ # convert mask into a bias that can be added to attention scores:
518
+ # (keep = +0, discard = -10000.0)
519
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
520
+ attention_mask = attention_mask.unsqueeze(1)
521
+
522
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
523
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
524
+ encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
525
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
526
+
527
+ # 1. Input
528
+ batch_size, num_channels, height, width = hidden_states.shape
529
+ p = self.config.patch_size
530
+ post_patch_height, post_patch_width = height // p, width // p
531
+
532
+ hidden_states = self.patch_embed(hidden_states)
533
+
534
+ if guidance is not None:
535
+ timestep, embedded_timestep = self.time_embed(
536
+ timestep, guidance=guidance, hidden_dtype=hidden_states.dtype
537
+ )
538
+ else:
539
+ timestep, embedded_timestep = self.time_embed(
540
+ timestep, batch_size=batch_size, hidden_dtype=hidden_states.dtype
541
+ )
542
+
543
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
544
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
545
+
546
+ encoder_hidden_states = self.caption_norm(encoder_hidden_states)
547
+
548
+ # 2. Transformer blocks
549
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
550
+ for index_block, block in enumerate(self.transformer_blocks):
551
+ hidden_states = self._gradient_checkpointing_func(
552
+ block,
553
+ hidden_states,
554
+ attention_mask,
555
+ encoder_hidden_states,
556
+ encoder_attention_mask,
557
+ timestep,
558
+ post_patch_height,
559
+ post_patch_width,
560
+ )
561
+ if controlnet_block_samples is not None and 0 < index_block <= len(controlnet_block_samples):
562
+ hidden_states = hidden_states + controlnet_block_samples[index_block - 1]
563
+
564
+ else:
565
+ for index_block, block in enumerate(self.transformer_blocks):
566
+ hidden_states = block(
567
+ hidden_states,
568
+ attention_mask,
569
+ encoder_hidden_states,
570
+ encoder_attention_mask,
571
+ timestep,
572
+ post_patch_height,
573
+ post_patch_width,
574
+ )
575
+ if controlnet_block_samples is not None and 0 < index_block <= len(controlnet_block_samples):
576
+ hidden_states = hidden_states + controlnet_block_samples[index_block - 1]
577
+
578
+ # 3. Normalization
579
+ hidden_states = self.norm_out(hidden_states, embedded_timestep, self.scale_shift_table)
580
+
581
+ hidden_states = self.proj_out(hidden_states)
582
+
583
+ # 5. Unpatchify
584
+ hidden_states = hidden_states.reshape(
585
+ batch_size, post_patch_height, post_patch_width, self.config.patch_size, self.config.patch_size, -1
586
+ )
587
+ hidden_states = hidden_states.permute(0, 5, 1, 3, 2, 4)
588
+ output = hidden_states.reshape(batch_size, -1, post_patch_height * p, post_patch_width * p)
589
+
590
+ if USE_PEFT_BACKEND:
591
+ # remove `lora_scale` from each PEFT layer
592
+ unscale_lora_layers(self, lora_scale)
593
+
594
+ if not return_dict:
595
+ return (output,)
596
+
597
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/stable_audio_transformer.py ADDED
@@ -0,0 +1,443 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Stability AI and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Dict, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+ import torch.utils.checkpoint
22
+
23
+ from ...configuration_utils import ConfigMixin, register_to_config
24
+ from ...models.attention import FeedForward
25
+ from ...models.attention_processor import (
26
+ Attention,
27
+ AttentionProcessor,
28
+ StableAudioAttnProcessor2_0,
29
+ )
30
+ from ...models.modeling_utils import ModelMixin
31
+ from ...models.transformers.transformer_2d import Transformer2DModelOutput
32
+ from ...utils import logging
33
+ from ...utils.torch_utils import maybe_allow_in_graph
34
+
35
+
36
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
37
+
38
+
39
+ class StableAudioGaussianFourierProjection(nn.Module):
40
+ """Gaussian Fourier embeddings for noise levels."""
41
+
42
+ # Copied from diffusers.models.embeddings.GaussianFourierProjection.__init__
43
+ def __init__(
44
+ self, embedding_size: int = 256, scale: float = 1.0, set_W_to_weight=True, log=True, flip_sin_to_cos=False
45
+ ):
46
+ super().__init__()
47
+ self.weight = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
48
+ self.log = log
49
+ self.flip_sin_to_cos = flip_sin_to_cos
50
+
51
+ if set_W_to_weight:
52
+ # to delete later
53
+ del self.weight
54
+ self.W = nn.Parameter(torch.randn(embedding_size) * scale, requires_grad=False)
55
+ self.weight = self.W
56
+ del self.W
57
+
58
+ def forward(self, x):
59
+ if self.log:
60
+ x = torch.log(x)
61
+
62
+ x_proj = 2 * np.pi * x[:, None] @ self.weight[None, :]
63
+
64
+ if self.flip_sin_to_cos:
65
+ out = torch.cat([torch.cos(x_proj), torch.sin(x_proj)], dim=-1)
66
+ else:
67
+ out = torch.cat([torch.sin(x_proj), torch.cos(x_proj)], dim=-1)
68
+ return out
69
+
70
+
71
+ @maybe_allow_in_graph
72
+ class StableAudioDiTBlock(nn.Module):
73
+ r"""
74
+ Transformer block used in Stable Audio model (https://github.com/Stability-AI/stable-audio-tools). Allow skip
75
+ connection and QKNorm
76
+
77
+ Parameters:
78
+ dim (`int`): The number of channels in the input and output.
79
+ num_attention_heads (`int`): The number of heads to use for the query states.
80
+ num_key_value_attention_heads (`int`): The number of heads to use for the key and value states.
81
+ attention_head_dim (`int`): The number of channels in each head.
82
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
83
+ cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
84
+ upcast_attention (`bool`, *optional*):
85
+ Whether to upcast the attention computation to float32. This is useful for mixed precision training.
86
+ """
87
+
88
+ def __init__(
89
+ self,
90
+ dim: int,
91
+ num_attention_heads: int,
92
+ num_key_value_attention_heads: int,
93
+ attention_head_dim: int,
94
+ dropout=0.0,
95
+ cross_attention_dim: Optional[int] = None,
96
+ upcast_attention: bool = False,
97
+ norm_eps: float = 1e-5,
98
+ ff_inner_dim: Optional[int] = None,
99
+ ):
100
+ super().__init__()
101
+ # Define 3 blocks. Each block has its own normalization layer.
102
+ # 1. Self-Attn
103
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=True, eps=norm_eps)
104
+ self.attn1 = Attention(
105
+ query_dim=dim,
106
+ heads=num_attention_heads,
107
+ dim_head=attention_head_dim,
108
+ dropout=dropout,
109
+ bias=False,
110
+ upcast_attention=upcast_attention,
111
+ out_bias=False,
112
+ processor=StableAudioAttnProcessor2_0(),
113
+ )
114
+
115
+ # 2. Cross-Attn
116
+ self.norm2 = nn.LayerNorm(dim, norm_eps, True)
117
+
118
+ self.attn2 = Attention(
119
+ query_dim=dim,
120
+ cross_attention_dim=cross_attention_dim,
121
+ heads=num_attention_heads,
122
+ dim_head=attention_head_dim,
123
+ kv_heads=num_key_value_attention_heads,
124
+ dropout=dropout,
125
+ bias=False,
126
+ upcast_attention=upcast_attention,
127
+ out_bias=False,
128
+ processor=StableAudioAttnProcessor2_0(),
129
+ ) # is self-attn if encoder_hidden_states is none
130
+
131
+ # 3. Feed-forward
132
+ self.norm3 = nn.LayerNorm(dim, norm_eps, True)
133
+ self.ff = FeedForward(
134
+ dim,
135
+ dropout=dropout,
136
+ activation_fn="swiglu",
137
+ final_dropout=False,
138
+ inner_dim=ff_inner_dim,
139
+ bias=True,
140
+ )
141
+
142
+ # let chunk size default to None
143
+ self._chunk_size = None
144
+ self._chunk_dim = 0
145
+
146
+ def set_chunk_feed_forward(self, chunk_size: Optional[int], dim: int = 0):
147
+ # Sets chunk feed-forward
148
+ self._chunk_size = chunk_size
149
+ self._chunk_dim = dim
150
+
151
+ def forward(
152
+ self,
153
+ hidden_states: torch.Tensor,
154
+ attention_mask: Optional[torch.Tensor] = None,
155
+ encoder_hidden_states: Optional[torch.Tensor] = None,
156
+ encoder_attention_mask: Optional[torch.Tensor] = None,
157
+ rotary_embedding: Optional[torch.FloatTensor] = None,
158
+ ) -> torch.Tensor:
159
+ # Notice that normalization is always applied before the real computation in the following blocks.
160
+ # 0. Self-Attention
161
+ norm_hidden_states = self.norm1(hidden_states)
162
+
163
+ attn_output = self.attn1(
164
+ norm_hidden_states,
165
+ attention_mask=attention_mask,
166
+ rotary_emb=rotary_embedding,
167
+ )
168
+
169
+ hidden_states = attn_output + hidden_states
170
+
171
+ # 2. Cross-Attention
172
+ norm_hidden_states = self.norm2(hidden_states)
173
+
174
+ attn_output = self.attn2(
175
+ norm_hidden_states,
176
+ encoder_hidden_states=encoder_hidden_states,
177
+ attention_mask=encoder_attention_mask,
178
+ )
179
+ hidden_states = attn_output + hidden_states
180
+
181
+ # 3. Feed-forward
182
+ norm_hidden_states = self.norm3(hidden_states)
183
+ ff_output = self.ff(norm_hidden_states)
184
+
185
+ hidden_states = ff_output + hidden_states
186
+
187
+ return hidden_states
188
+
189
+
190
+ class StableAudioDiTModel(ModelMixin, ConfigMixin):
191
+ """
192
+ The Diffusion Transformer model introduced in Stable Audio.
193
+
194
+ Reference: https://github.com/Stability-AI/stable-audio-tools
195
+
196
+ Parameters:
197
+ sample_size ( `int`, *optional*, defaults to 1024): The size of the input sample.
198
+ in_channels (`int`, *optional*, defaults to 64): The number of channels in the input.
199
+ num_layers (`int`, *optional*, defaults to 24): The number of layers of Transformer blocks to use.
200
+ attention_head_dim (`int`, *optional*, defaults to 64): The number of channels in each head.
201
+ num_attention_heads (`int`, *optional*, defaults to 24): The number of heads to use for the query states.
202
+ num_key_value_attention_heads (`int`, *optional*, defaults to 12):
203
+ The number of heads to use for the key and value states.
204
+ out_channels (`int`, defaults to 64): Number of output channels.
205
+ cross_attention_dim ( `int`, *optional*, defaults to 768): Dimension of the cross-attention projection.
206
+ time_proj_dim ( `int`, *optional*, defaults to 256): Dimension of the timestep inner projection.
207
+ global_states_input_dim ( `int`, *optional*, defaults to 1536):
208
+ Input dimension of the global hidden states projection.
209
+ cross_attention_input_dim ( `int`, *optional*, defaults to 768):
210
+ Input dimension of the cross-attention projection
211
+ """
212
+
213
+ _supports_gradient_checkpointing = True
214
+ _skip_layerwise_casting_patterns = ["preprocess_conv", "postprocess_conv", "^proj_in$", "^proj_out$", "norm"]
215
+
216
+ @register_to_config
217
+ def __init__(
218
+ self,
219
+ sample_size: int = 1024,
220
+ in_channels: int = 64,
221
+ num_layers: int = 24,
222
+ attention_head_dim: int = 64,
223
+ num_attention_heads: int = 24,
224
+ num_key_value_attention_heads: int = 12,
225
+ out_channels: int = 64,
226
+ cross_attention_dim: int = 768,
227
+ time_proj_dim: int = 256,
228
+ global_states_input_dim: int = 1536,
229
+ cross_attention_input_dim: int = 768,
230
+ ):
231
+ super().__init__()
232
+ self.sample_size = sample_size
233
+ self.out_channels = out_channels
234
+ self.inner_dim = num_attention_heads * attention_head_dim
235
+
236
+ self.time_proj = StableAudioGaussianFourierProjection(
237
+ embedding_size=time_proj_dim // 2,
238
+ flip_sin_to_cos=True,
239
+ log=False,
240
+ set_W_to_weight=False,
241
+ )
242
+
243
+ self.timestep_proj = nn.Sequential(
244
+ nn.Linear(time_proj_dim, self.inner_dim, bias=True),
245
+ nn.SiLU(),
246
+ nn.Linear(self.inner_dim, self.inner_dim, bias=True),
247
+ )
248
+
249
+ self.global_proj = nn.Sequential(
250
+ nn.Linear(global_states_input_dim, self.inner_dim, bias=False),
251
+ nn.SiLU(),
252
+ nn.Linear(self.inner_dim, self.inner_dim, bias=False),
253
+ )
254
+
255
+ self.cross_attention_proj = nn.Sequential(
256
+ nn.Linear(cross_attention_input_dim, cross_attention_dim, bias=False),
257
+ nn.SiLU(),
258
+ nn.Linear(cross_attention_dim, cross_attention_dim, bias=False),
259
+ )
260
+
261
+ self.preprocess_conv = nn.Conv1d(in_channels, in_channels, 1, bias=False)
262
+ self.proj_in = nn.Linear(in_channels, self.inner_dim, bias=False)
263
+
264
+ self.transformer_blocks = nn.ModuleList(
265
+ [
266
+ StableAudioDiTBlock(
267
+ dim=self.inner_dim,
268
+ num_attention_heads=num_attention_heads,
269
+ num_key_value_attention_heads=num_key_value_attention_heads,
270
+ attention_head_dim=attention_head_dim,
271
+ cross_attention_dim=cross_attention_dim,
272
+ )
273
+ for i in range(num_layers)
274
+ ]
275
+ )
276
+
277
+ self.proj_out = nn.Linear(self.inner_dim, self.out_channels, bias=False)
278
+ self.postprocess_conv = nn.Conv1d(self.out_channels, self.out_channels, 1, bias=False)
279
+
280
+ self.gradient_checkpointing = False
281
+
282
+ @property
283
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
284
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
285
+ r"""
286
+ Returns:
287
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
288
+ indexed by its weight name.
289
+ """
290
+ # set recursively
291
+ processors = {}
292
+
293
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
294
+ if hasattr(module, "get_processor"):
295
+ processors[f"{name}.processor"] = module.get_processor()
296
+
297
+ for sub_name, child in module.named_children():
298
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
299
+
300
+ return processors
301
+
302
+ for name, module in self.named_children():
303
+ fn_recursive_add_processors(name, module, processors)
304
+
305
+ return processors
306
+
307
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
308
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
309
+ r"""
310
+ Sets the attention processor to use to compute attention.
311
+
312
+ Parameters:
313
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
314
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
315
+ for **all** `Attention` layers.
316
+
317
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
318
+ processor. This is strongly recommended when setting trainable attention processors.
319
+
320
+ """
321
+ count = len(self.attn_processors.keys())
322
+
323
+ if isinstance(processor, dict) and len(processor) != count:
324
+ raise ValueError(
325
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
326
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
327
+ )
328
+
329
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
330
+ if hasattr(module, "set_processor"):
331
+ if not isinstance(processor, dict):
332
+ module.set_processor(processor)
333
+ else:
334
+ module.set_processor(processor.pop(f"{name}.processor"))
335
+
336
+ for sub_name, child in module.named_children():
337
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
338
+
339
+ for name, module in self.named_children():
340
+ fn_recursive_attn_processor(name, module, processor)
341
+
342
+ # Copied from diffusers.models.transformers.hunyuan_transformer_2d.HunyuanDiT2DModel.set_default_attn_processor with Hunyuan->StableAudio
343
+ def set_default_attn_processor(self):
344
+ """
345
+ Disables custom attention processors and sets the default attention implementation.
346
+ """
347
+ self.set_attn_processor(StableAudioAttnProcessor2_0())
348
+
349
+ def forward(
350
+ self,
351
+ hidden_states: torch.FloatTensor,
352
+ timestep: torch.LongTensor = None,
353
+ encoder_hidden_states: torch.FloatTensor = None,
354
+ global_hidden_states: torch.FloatTensor = None,
355
+ rotary_embedding: torch.FloatTensor = None,
356
+ return_dict: bool = True,
357
+ attention_mask: Optional[torch.LongTensor] = None,
358
+ encoder_attention_mask: Optional[torch.LongTensor] = None,
359
+ ) -> Union[torch.FloatTensor, Transformer2DModelOutput]:
360
+ """
361
+ The [`StableAudioDiTModel`] forward method.
362
+
363
+ Args:
364
+ hidden_states (`torch.FloatTensor` of shape `(batch size, in_channels, sequence_len)`):
365
+ Input `hidden_states`.
366
+ timestep ( `torch.LongTensor`):
367
+ Used to indicate denoising step.
368
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch size, encoder_sequence_len, cross_attention_input_dim)`):
369
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
370
+ global_hidden_states (`torch.FloatTensor` of shape `(batch size, global_sequence_len, global_states_input_dim)`):
371
+ Global embeddings that will be prepended to the hidden states.
372
+ rotary_embedding (`torch.Tensor`):
373
+ The rotary embeddings to apply on query and key tensors during attention calculation.
374
+ return_dict (`bool`, *optional*, defaults to `True`):
375
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
376
+ tuple.
377
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_len)`, *optional*):
378
+ Mask to avoid performing attention on padding token indices, formed by concatenating the attention
379
+ masks
380
+ for the two text encoders together. Mask values selected in `[0, 1]`:
381
+
382
+ - 1 for tokens that are **not masked**,
383
+ - 0 for tokens that are **masked**.
384
+ encoder_attention_mask (`torch.Tensor` of shape `(batch_size, sequence_len)`, *optional*):
385
+ Mask to avoid performing attention on padding token cross-attention indices, formed by concatenating
386
+ the attention masks
387
+ for the two text encoders together. Mask values selected in `[0, 1]`:
388
+
389
+ - 1 for tokens that are **not masked**,
390
+ - 0 for tokens that are **masked**.
391
+ Returns:
392
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
393
+ `tuple` where the first element is the sample tensor.
394
+ """
395
+ cross_attention_hidden_states = self.cross_attention_proj(encoder_hidden_states)
396
+ global_hidden_states = self.global_proj(global_hidden_states)
397
+ time_hidden_states = self.timestep_proj(self.time_proj(timestep.to(self.dtype)))
398
+
399
+ global_hidden_states = global_hidden_states + time_hidden_states.unsqueeze(1)
400
+
401
+ hidden_states = self.preprocess_conv(hidden_states) + hidden_states
402
+ # (batch_size, dim, sequence_length) -> (batch_size, sequence_length, dim)
403
+ hidden_states = hidden_states.transpose(1, 2)
404
+
405
+ hidden_states = self.proj_in(hidden_states)
406
+
407
+ # prepend global states to hidden states
408
+ hidden_states = torch.cat([global_hidden_states, hidden_states], dim=-2)
409
+ if attention_mask is not None:
410
+ prepend_mask = torch.ones((hidden_states.shape[0], 1), device=hidden_states.device, dtype=torch.bool)
411
+ attention_mask = torch.cat([prepend_mask, attention_mask], dim=-1)
412
+
413
+ for block in self.transformer_blocks:
414
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
415
+ hidden_states = self._gradient_checkpointing_func(
416
+ block,
417
+ hidden_states,
418
+ attention_mask,
419
+ cross_attention_hidden_states,
420
+ encoder_attention_mask,
421
+ rotary_embedding,
422
+ )
423
+
424
+ else:
425
+ hidden_states = block(
426
+ hidden_states=hidden_states,
427
+ attention_mask=attention_mask,
428
+ encoder_hidden_states=cross_attention_hidden_states,
429
+ encoder_attention_mask=encoder_attention_mask,
430
+ rotary_embedding=rotary_embedding,
431
+ )
432
+
433
+ hidden_states = self.proj_out(hidden_states)
434
+
435
+ # (batch_size, sequence_length, dim) -> (batch_size, dim, sequence_length)
436
+ # remove prepend length that has been added by global hidden states
437
+ hidden_states = hidden_states.transpose(1, 2)[:, :, 1:]
438
+ hidden_states = self.postprocess_conv(hidden_states) + hidden_states
439
+
440
+ if not return_dict:
441
+ return (hidden_states,)
442
+
443
+ return Transformer2DModelOutput(sample=hidden_states)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/t5_film_transformer.py ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ import math
15
+ from typing import Optional, Tuple
16
+
17
+ import torch
18
+ from torch import nn
19
+
20
+ from ...configuration_utils import ConfigMixin, register_to_config
21
+ from ..attention_processor import Attention
22
+ from ..embeddings import get_timestep_embedding
23
+ from ..modeling_utils import ModelMixin
24
+
25
+
26
+ class T5FilmDecoder(ModelMixin, ConfigMixin):
27
+ r"""
28
+ T5 style decoder with FiLM conditioning.
29
+
30
+ Args:
31
+ input_dims (`int`, *optional*, defaults to `128`):
32
+ The number of input dimensions.
33
+ targets_length (`int`, *optional*, defaults to `256`):
34
+ The length of the targets.
35
+ d_model (`int`, *optional*, defaults to `768`):
36
+ Size of the input hidden states.
37
+ num_layers (`int`, *optional*, defaults to `12`):
38
+ The number of `DecoderLayer`'s to use.
39
+ num_heads (`int`, *optional*, defaults to `12`):
40
+ The number of attention heads to use.
41
+ d_kv (`int`, *optional*, defaults to `64`):
42
+ Size of the key-value projection vectors.
43
+ d_ff (`int`, *optional*, defaults to `2048`):
44
+ The number of dimensions in the intermediate feed-forward layer of `DecoderLayer`'s.
45
+ dropout_rate (`float`, *optional*, defaults to `0.1`):
46
+ Dropout probability.
47
+ """
48
+
49
+ @register_to_config
50
+ def __init__(
51
+ self,
52
+ input_dims: int = 128,
53
+ targets_length: int = 256,
54
+ max_decoder_noise_time: float = 2000.0,
55
+ d_model: int = 768,
56
+ num_layers: int = 12,
57
+ num_heads: int = 12,
58
+ d_kv: int = 64,
59
+ d_ff: int = 2048,
60
+ dropout_rate: float = 0.1,
61
+ ):
62
+ super().__init__()
63
+
64
+ self.conditioning_emb = nn.Sequential(
65
+ nn.Linear(d_model, d_model * 4, bias=False),
66
+ nn.SiLU(),
67
+ nn.Linear(d_model * 4, d_model * 4, bias=False),
68
+ nn.SiLU(),
69
+ )
70
+
71
+ self.position_encoding = nn.Embedding(targets_length, d_model)
72
+ self.position_encoding.weight.requires_grad = False
73
+
74
+ self.continuous_inputs_projection = nn.Linear(input_dims, d_model, bias=False)
75
+
76
+ self.dropout = nn.Dropout(p=dropout_rate)
77
+
78
+ self.decoders = nn.ModuleList()
79
+ for lyr_num in range(num_layers):
80
+ # FiLM conditional T5 decoder
81
+ lyr = DecoderLayer(d_model=d_model, d_kv=d_kv, num_heads=num_heads, d_ff=d_ff, dropout_rate=dropout_rate)
82
+ self.decoders.append(lyr)
83
+
84
+ self.decoder_norm = T5LayerNorm(d_model)
85
+
86
+ self.post_dropout = nn.Dropout(p=dropout_rate)
87
+ self.spec_out = nn.Linear(d_model, input_dims, bias=False)
88
+
89
+ def encoder_decoder_mask(self, query_input: torch.Tensor, key_input: torch.Tensor) -> torch.Tensor:
90
+ mask = torch.mul(query_input.unsqueeze(-1), key_input.unsqueeze(-2))
91
+ return mask.unsqueeze(-3)
92
+
93
+ def forward(self, encodings_and_masks, decoder_input_tokens, decoder_noise_time):
94
+ batch, _, _ = decoder_input_tokens.shape
95
+ assert decoder_noise_time.shape == (batch,)
96
+
97
+ # decoder_noise_time is in [0, 1), so rescale to expected timing range.
98
+ time_steps = get_timestep_embedding(
99
+ decoder_noise_time * self.config.max_decoder_noise_time,
100
+ embedding_dim=self.config.d_model,
101
+ max_period=self.config.max_decoder_noise_time,
102
+ ).to(dtype=self.dtype)
103
+
104
+ conditioning_emb = self.conditioning_emb(time_steps).unsqueeze(1)
105
+
106
+ assert conditioning_emb.shape == (batch, 1, self.config.d_model * 4)
107
+
108
+ seq_length = decoder_input_tokens.shape[1]
109
+
110
+ # If we want to use relative positions for audio context, we can just offset
111
+ # this sequence by the length of encodings_and_masks.
112
+ decoder_positions = torch.broadcast_to(
113
+ torch.arange(seq_length, device=decoder_input_tokens.device),
114
+ (batch, seq_length),
115
+ )
116
+
117
+ position_encodings = self.position_encoding(decoder_positions)
118
+
119
+ inputs = self.continuous_inputs_projection(decoder_input_tokens)
120
+ inputs += position_encodings
121
+ y = self.dropout(inputs)
122
+
123
+ # decoder: No padding present.
124
+ decoder_mask = torch.ones(
125
+ decoder_input_tokens.shape[:2], device=decoder_input_tokens.device, dtype=inputs.dtype
126
+ )
127
+
128
+ # Translate encoding masks to encoder-decoder masks.
129
+ encodings_and_encdec_masks = [(x, self.encoder_decoder_mask(decoder_mask, y)) for x, y in encodings_and_masks]
130
+
131
+ # cross attend style: concat encodings
132
+ encoded = torch.cat([x[0] for x in encodings_and_encdec_masks], dim=1)
133
+ encoder_decoder_mask = torch.cat([x[1] for x in encodings_and_encdec_masks], dim=-1)
134
+
135
+ for lyr in self.decoders:
136
+ y = lyr(
137
+ y,
138
+ conditioning_emb=conditioning_emb,
139
+ encoder_hidden_states=encoded,
140
+ encoder_attention_mask=encoder_decoder_mask,
141
+ )[0]
142
+
143
+ y = self.decoder_norm(y)
144
+ y = self.post_dropout(y)
145
+
146
+ spec_out = self.spec_out(y)
147
+ return spec_out
148
+
149
+
150
+ class DecoderLayer(nn.Module):
151
+ r"""
152
+ T5 decoder layer.
153
+
154
+ Args:
155
+ d_model (`int`):
156
+ Size of the input hidden states.
157
+ d_kv (`int`):
158
+ Size of the key-value projection vectors.
159
+ num_heads (`int`):
160
+ Number of attention heads.
161
+ d_ff (`int`):
162
+ Size of the intermediate feed-forward layer.
163
+ dropout_rate (`float`):
164
+ Dropout probability.
165
+ layer_norm_epsilon (`float`, *optional*, defaults to `1e-6`):
166
+ A small value used for numerical stability to avoid dividing by zero.
167
+ """
168
+
169
+ def __init__(
170
+ self, d_model: int, d_kv: int, num_heads: int, d_ff: int, dropout_rate: float, layer_norm_epsilon: float = 1e-6
171
+ ):
172
+ super().__init__()
173
+ self.layer = nn.ModuleList()
174
+
175
+ # cond self attention: layer 0
176
+ self.layer.append(
177
+ T5LayerSelfAttentionCond(d_model=d_model, d_kv=d_kv, num_heads=num_heads, dropout_rate=dropout_rate)
178
+ )
179
+
180
+ # cross attention: layer 1
181
+ self.layer.append(
182
+ T5LayerCrossAttention(
183
+ d_model=d_model,
184
+ d_kv=d_kv,
185
+ num_heads=num_heads,
186
+ dropout_rate=dropout_rate,
187
+ layer_norm_epsilon=layer_norm_epsilon,
188
+ )
189
+ )
190
+
191
+ # Film Cond MLP + dropout: last layer
192
+ self.layer.append(
193
+ T5LayerFFCond(d_model=d_model, d_ff=d_ff, dropout_rate=dropout_rate, layer_norm_epsilon=layer_norm_epsilon)
194
+ )
195
+
196
+ def forward(
197
+ self,
198
+ hidden_states: torch.Tensor,
199
+ conditioning_emb: Optional[torch.Tensor] = None,
200
+ attention_mask: Optional[torch.Tensor] = None,
201
+ encoder_hidden_states: Optional[torch.Tensor] = None,
202
+ encoder_attention_mask: Optional[torch.Tensor] = None,
203
+ encoder_decoder_position_bias=None,
204
+ ) -> Tuple[torch.Tensor]:
205
+ hidden_states = self.layer[0](
206
+ hidden_states,
207
+ conditioning_emb=conditioning_emb,
208
+ attention_mask=attention_mask,
209
+ )
210
+
211
+ if encoder_hidden_states is not None:
212
+ encoder_extended_attention_mask = torch.where(encoder_attention_mask > 0, 0, -1e10).to(
213
+ encoder_hidden_states.dtype
214
+ )
215
+
216
+ hidden_states = self.layer[1](
217
+ hidden_states,
218
+ key_value_states=encoder_hidden_states,
219
+ attention_mask=encoder_extended_attention_mask,
220
+ )
221
+
222
+ # Apply Film Conditional Feed Forward layer
223
+ hidden_states = self.layer[-1](hidden_states, conditioning_emb)
224
+
225
+ return (hidden_states,)
226
+
227
+
228
+ class T5LayerSelfAttentionCond(nn.Module):
229
+ r"""
230
+ T5 style self-attention layer with conditioning.
231
+
232
+ Args:
233
+ d_model (`int`):
234
+ Size of the input hidden states.
235
+ d_kv (`int`):
236
+ Size of the key-value projection vectors.
237
+ num_heads (`int`):
238
+ Number of attention heads.
239
+ dropout_rate (`float`):
240
+ Dropout probability.
241
+ """
242
+
243
+ def __init__(self, d_model: int, d_kv: int, num_heads: int, dropout_rate: float):
244
+ super().__init__()
245
+ self.layer_norm = T5LayerNorm(d_model)
246
+ self.FiLMLayer = T5FiLMLayer(in_features=d_model * 4, out_features=d_model)
247
+ self.attention = Attention(query_dim=d_model, heads=num_heads, dim_head=d_kv, out_bias=False, scale_qk=False)
248
+ self.dropout = nn.Dropout(dropout_rate)
249
+
250
+ def forward(
251
+ self,
252
+ hidden_states: torch.Tensor,
253
+ conditioning_emb: Optional[torch.Tensor] = None,
254
+ attention_mask: Optional[torch.Tensor] = None,
255
+ ) -> torch.Tensor:
256
+ # pre_self_attention_layer_norm
257
+ normed_hidden_states = self.layer_norm(hidden_states)
258
+
259
+ if conditioning_emb is not None:
260
+ normed_hidden_states = self.FiLMLayer(normed_hidden_states, conditioning_emb)
261
+
262
+ # Self-attention block
263
+ attention_output = self.attention(normed_hidden_states)
264
+
265
+ hidden_states = hidden_states + self.dropout(attention_output)
266
+
267
+ return hidden_states
268
+
269
+
270
+ class T5LayerCrossAttention(nn.Module):
271
+ r"""
272
+ T5 style cross-attention layer.
273
+
274
+ Args:
275
+ d_model (`int`):
276
+ Size of the input hidden states.
277
+ d_kv (`int`):
278
+ Size of the key-value projection vectors.
279
+ num_heads (`int`):
280
+ Number of attention heads.
281
+ dropout_rate (`float`):
282
+ Dropout probability.
283
+ layer_norm_epsilon (`float`):
284
+ A small value used for numerical stability to avoid dividing by zero.
285
+ """
286
+
287
+ def __init__(self, d_model: int, d_kv: int, num_heads: int, dropout_rate: float, layer_norm_epsilon: float):
288
+ super().__init__()
289
+ self.attention = Attention(query_dim=d_model, heads=num_heads, dim_head=d_kv, out_bias=False, scale_qk=False)
290
+ self.layer_norm = T5LayerNorm(d_model, eps=layer_norm_epsilon)
291
+ self.dropout = nn.Dropout(dropout_rate)
292
+
293
+ def forward(
294
+ self,
295
+ hidden_states: torch.Tensor,
296
+ key_value_states: Optional[torch.Tensor] = None,
297
+ attention_mask: Optional[torch.Tensor] = None,
298
+ ) -> torch.Tensor:
299
+ normed_hidden_states = self.layer_norm(hidden_states)
300
+ attention_output = self.attention(
301
+ normed_hidden_states,
302
+ encoder_hidden_states=key_value_states,
303
+ attention_mask=attention_mask.squeeze(1),
304
+ )
305
+ layer_output = hidden_states + self.dropout(attention_output)
306
+ return layer_output
307
+
308
+
309
+ class T5LayerFFCond(nn.Module):
310
+ r"""
311
+ T5 style feed-forward conditional layer.
312
+
313
+ Args:
314
+ d_model (`int`):
315
+ Size of the input hidden states.
316
+ d_ff (`int`):
317
+ Size of the intermediate feed-forward layer.
318
+ dropout_rate (`float`):
319
+ Dropout probability.
320
+ layer_norm_epsilon (`float`):
321
+ A small value used for numerical stability to avoid dividing by zero.
322
+ """
323
+
324
+ def __init__(self, d_model: int, d_ff: int, dropout_rate: float, layer_norm_epsilon: float):
325
+ super().__init__()
326
+ self.DenseReluDense = T5DenseGatedActDense(d_model=d_model, d_ff=d_ff, dropout_rate=dropout_rate)
327
+ self.film = T5FiLMLayer(in_features=d_model * 4, out_features=d_model)
328
+ self.layer_norm = T5LayerNorm(d_model, eps=layer_norm_epsilon)
329
+ self.dropout = nn.Dropout(dropout_rate)
330
+
331
+ def forward(self, hidden_states: torch.Tensor, conditioning_emb: Optional[torch.Tensor] = None) -> torch.Tensor:
332
+ forwarded_states = self.layer_norm(hidden_states)
333
+ if conditioning_emb is not None:
334
+ forwarded_states = self.film(forwarded_states, conditioning_emb)
335
+
336
+ forwarded_states = self.DenseReluDense(forwarded_states)
337
+ hidden_states = hidden_states + self.dropout(forwarded_states)
338
+ return hidden_states
339
+
340
+
341
+ class T5DenseGatedActDense(nn.Module):
342
+ r"""
343
+ T5 style feed-forward layer with gated activations and dropout.
344
+
345
+ Args:
346
+ d_model (`int`):
347
+ Size of the input hidden states.
348
+ d_ff (`int`):
349
+ Size of the intermediate feed-forward layer.
350
+ dropout_rate (`float`):
351
+ Dropout probability.
352
+ """
353
+
354
+ def __init__(self, d_model: int, d_ff: int, dropout_rate: float):
355
+ super().__init__()
356
+ self.wi_0 = nn.Linear(d_model, d_ff, bias=False)
357
+ self.wi_1 = nn.Linear(d_model, d_ff, bias=False)
358
+ self.wo = nn.Linear(d_ff, d_model, bias=False)
359
+ self.dropout = nn.Dropout(dropout_rate)
360
+ self.act = NewGELUActivation()
361
+
362
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
363
+ hidden_gelu = self.act(self.wi_0(hidden_states))
364
+ hidden_linear = self.wi_1(hidden_states)
365
+ hidden_states = hidden_gelu * hidden_linear
366
+ hidden_states = self.dropout(hidden_states)
367
+
368
+ hidden_states = self.wo(hidden_states)
369
+ return hidden_states
370
+
371
+
372
+ class T5LayerNorm(nn.Module):
373
+ r"""
374
+ T5 style layer normalization module.
375
+
376
+ Args:
377
+ hidden_size (`int`):
378
+ Size of the input hidden states.
379
+ eps (`float`, `optional`, defaults to `1e-6`):
380
+ A small value used for numerical stability to avoid dividing by zero.
381
+ """
382
+
383
+ def __init__(self, hidden_size: int, eps: float = 1e-6):
384
+ """
385
+ Construct a layernorm module in the T5 style. No bias and no subtraction of mean.
386
+ """
387
+ super().__init__()
388
+ self.weight = nn.Parameter(torch.ones(hidden_size))
389
+ self.variance_epsilon = eps
390
+
391
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
392
+ # T5 uses a layer_norm which only scales and doesn't shift, which is also known as Root Mean
393
+ # Square Layer Normalization https://arxiv.org/abs/1910.07467 thus variance is calculated
394
+ # w/o mean and there is no bias. Additionally we want to make sure that the accumulation for
395
+ # half-precision inputs is done in fp32
396
+
397
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
398
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
399
+
400
+ # convert into half-precision if necessary
401
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
402
+ hidden_states = hidden_states.to(self.weight.dtype)
403
+
404
+ return self.weight * hidden_states
405
+
406
+
407
+ class NewGELUActivation(nn.Module):
408
+ """
409
+ Implementation of the GELU activation function currently in Google BERT repo (identical to OpenAI GPT). Also see
410
+ the Gaussian Error Linear Units paper: https://arxiv.org/abs/1606.08415
411
+ """
412
+
413
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
414
+ return 0.5 * input * (1.0 + torch.tanh(math.sqrt(2.0 / math.pi) * (input + 0.044715 * torch.pow(input, 3.0))))
415
+
416
+
417
+ class T5FiLMLayer(nn.Module):
418
+ """
419
+ T5 style FiLM Layer.
420
+
421
+ Args:
422
+ in_features (`int`):
423
+ Number of input features.
424
+ out_features (`int`):
425
+ Number of output features.
426
+ """
427
+
428
+ def __init__(self, in_features: int, out_features: int):
429
+ super().__init__()
430
+ self.scale_bias = nn.Linear(in_features, out_features * 2, bias=False)
431
+
432
+ def forward(self, x: torch.Tensor, conditioning_emb: torch.Tensor) -> torch.Tensor:
433
+ emb = self.scale_bias(conditioning_emb)
434
+ scale, shift = torch.chunk(emb, 2, -1)
435
+ x = x * (1 + scale) + shift
436
+ return x
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_2d.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+ from typing import Any, Dict, Optional
15
+
16
+ import torch
17
+ import torch.nn.functional as F
18
+ from torch import nn
19
+
20
+ from ...configuration_utils import LegacyConfigMixin, register_to_config
21
+ from ...utils import deprecate, logging
22
+ from ..attention import BasicTransformerBlock
23
+ from ..embeddings import ImagePositionalEmbeddings, PatchEmbed, PixArtAlphaTextProjection
24
+ from ..modeling_outputs import Transformer2DModelOutput
25
+ from ..modeling_utils import LegacyModelMixin
26
+ from ..normalization import AdaLayerNormSingle
27
+
28
+
29
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
30
+
31
+
32
+ class Transformer2DModelOutput(Transformer2DModelOutput):
33
+ def __init__(self, *args, **kwargs):
34
+ deprecation_message = "Importing `Transformer2DModelOutput` from `diffusers.models.transformer_2d` is deprecated and this will be removed in a future version. Please use `from diffusers.models.modeling_outputs import Transformer2DModelOutput`, instead."
35
+ deprecate("Transformer2DModelOutput", "1.0.0", deprecation_message)
36
+ super().__init__(*args, **kwargs)
37
+
38
+
39
+ class Transformer2DModel(LegacyModelMixin, LegacyConfigMixin):
40
+ """
41
+ A 2D Transformer model for image-like data.
42
+
43
+ Parameters:
44
+ num_attention_heads (`int`, *optional*, defaults to 16): The number of heads to use for multi-head attention.
45
+ attention_head_dim (`int`, *optional*, defaults to 88): The number of channels in each head.
46
+ in_channels (`int`, *optional*):
47
+ The number of channels in the input and output (specify if the input is **continuous**).
48
+ num_layers (`int`, *optional*, defaults to 1): The number of layers of Transformer blocks to use.
49
+ dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
50
+ cross_attention_dim (`int`, *optional*): The number of `encoder_hidden_states` dimensions to use.
51
+ sample_size (`int`, *optional*): The width of the latent images (specify if the input is **discrete**).
52
+ This is fixed during training since it is used to learn a number of position embeddings.
53
+ num_vector_embeds (`int`, *optional*):
54
+ The number of classes of the vector embeddings of the latent pixels (specify if the input is **discrete**).
55
+ Includes the class for the masked latent pixel.
56
+ activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to use in feed-forward.
57
+ num_embeds_ada_norm ( `int`, *optional*):
58
+ The number of diffusion steps used during training. Pass if at least one of the norm_layers is
59
+ `AdaLayerNorm`. This is fixed during training since it is used to learn a number of embeddings that are
60
+ added to the hidden states.
61
+
62
+ During inference, you can denoise for up to but not more steps than `num_embeds_ada_norm`.
63
+ attention_bias (`bool`, *optional*):
64
+ Configure if the `TransformerBlocks` attention should contain a bias parameter.
65
+ """
66
+
67
+ _supports_gradient_checkpointing = True
68
+ _no_split_modules = ["BasicTransformerBlock"]
69
+ _skip_layerwise_casting_patterns = ["latent_image_embedding", "norm"]
70
+
71
+ @register_to_config
72
+ def __init__(
73
+ self,
74
+ num_attention_heads: int = 16,
75
+ attention_head_dim: int = 88,
76
+ in_channels: Optional[int] = None,
77
+ out_channels: Optional[int] = None,
78
+ num_layers: int = 1,
79
+ dropout: float = 0.0,
80
+ norm_num_groups: int = 32,
81
+ cross_attention_dim: Optional[int] = None,
82
+ attention_bias: bool = False,
83
+ sample_size: Optional[int] = None,
84
+ num_vector_embeds: Optional[int] = None,
85
+ patch_size: Optional[int] = None,
86
+ activation_fn: str = "geglu",
87
+ num_embeds_ada_norm: Optional[int] = None,
88
+ use_linear_projection: bool = False,
89
+ only_cross_attention: bool = False,
90
+ double_self_attention: bool = False,
91
+ upcast_attention: bool = False,
92
+ norm_type: str = "layer_norm", # 'layer_norm', 'ada_norm', 'ada_norm_zero', 'ada_norm_single', 'ada_norm_continuous', 'layer_norm_i2vgen'
93
+ norm_elementwise_affine: bool = True,
94
+ norm_eps: float = 1e-5,
95
+ attention_type: str = "default",
96
+ caption_channels: int = None,
97
+ interpolation_scale: float = None,
98
+ use_additional_conditions: Optional[bool] = None,
99
+ ):
100
+ super().__init__()
101
+
102
+ # Validate inputs.
103
+ if patch_size is not None:
104
+ if norm_type not in ["ada_norm", "ada_norm_zero", "ada_norm_single"]:
105
+ raise NotImplementedError(
106
+ f"Forward pass is not implemented when `patch_size` is not None and `norm_type` is '{norm_type}'."
107
+ )
108
+ elif norm_type in ["ada_norm", "ada_norm_zero"] and num_embeds_ada_norm is None:
109
+ raise ValueError(
110
+ f"When using a `patch_size` and this `norm_type` ({norm_type}), `num_embeds_ada_norm` cannot be None."
111
+ )
112
+
113
+ # 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)`
114
+ # Define whether input is continuous or discrete depending on configuration
115
+ self.is_input_continuous = (in_channels is not None) and (patch_size is None)
116
+ self.is_input_vectorized = num_vector_embeds is not None
117
+ self.is_input_patches = in_channels is not None and patch_size is not None
118
+
119
+ if self.is_input_continuous and self.is_input_vectorized:
120
+ raise ValueError(
121
+ f"Cannot define both `in_channels`: {in_channels} and `num_vector_embeds`: {num_vector_embeds}. Make"
122
+ " sure that either `in_channels` or `num_vector_embeds` is None."
123
+ )
124
+ elif self.is_input_vectorized and self.is_input_patches:
125
+ raise ValueError(
126
+ f"Cannot define both `num_vector_embeds`: {num_vector_embeds} and `patch_size`: {patch_size}. Make"
127
+ " sure that either `num_vector_embeds` or `num_patches` is None."
128
+ )
129
+ elif not self.is_input_continuous and not self.is_input_vectorized and not self.is_input_patches:
130
+ raise ValueError(
131
+ f"Has to define `in_channels`: {in_channels}, `num_vector_embeds`: {num_vector_embeds}, or patch_size:"
132
+ f" {patch_size}. Make sure that `in_channels`, `num_vector_embeds` or `num_patches` is not None."
133
+ )
134
+
135
+ if norm_type == "layer_norm" and num_embeds_ada_norm is not None:
136
+ deprecation_message = (
137
+ f"The configuration file of this model: {self.__class__} is outdated. `norm_type` is either not set or"
138
+ " incorrectly set to `'layer_norm'`. Make sure to set `norm_type` to `'ada_norm'` in the config."
139
+ " Please make sure to update the config accordingly as leaving `norm_type` might led to incorrect"
140
+ " results in future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it"
141
+ " would be very nice if you could open a Pull request for the `transformer/config.json` file"
142
+ )
143
+ deprecate("norm_type!=num_embeds_ada_norm", "1.0.0", deprecation_message, standard_warn=False)
144
+ norm_type = "ada_norm"
145
+
146
+ # Set some common variables used across the board.
147
+ self.use_linear_projection = use_linear_projection
148
+ self.interpolation_scale = interpolation_scale
149
+ self.caption_channels = caption_channels
150
+ self.num_attention_heads = num_attention_heads
151
+ self.attention_head_dim = attention_head_dim
152
+ self.inner_dim = self.config.num_attention_heads * self.config.attention_head_dim
153
+ self.in_channels = in_channels
154
+ self.out_channels = in_channels if out_channels is None else out_channels
155
+ self.gradient_checkpointing = False
156
+
157
+ if use_additional_conditions is None:
158
+ if norm_type == "ada_norm_single" and sample_size == 128:
159
+ use_additional_conditions = True
160
+ else:
161
+ use_additional_conditions = False
162
+ self.use_additional_conditions = use_additional_conditions
163
+
164
+ # 2. Initialize the right blocks.
165
+ # These functions follow a common structure:
166
+ # a. Initialize the input blocks. b. Initialize the transformer blocks.
167
+ # c. Initialize the output blocks and other projection blocks when necessary.
168
+ if self.is_input_continuous:
169
+ self._init_continuous_input(norm_type=norm_type)
170
+ elif self.is_input_vectorized:
171
+ self._init_vectorized_inputs(norm_type=norm_type)
172
+ elif self.is_input_patches:
173
+ self._init_patched_inputs(norm_type=norm_type)
174
+
175
+ def _init_continuous_input(self, norm_type):
176
+ self.norm = torch.nn.GroupNorm(
177
+ num_groups=self.config.norm_num_groups, num_channels=self.in_channels, eps=1e-6, affine=True
178
+ )
179
+ if self.use_linear_projection:
180
+ self.proj_in = torch.nn.Linear(self.in_channels, self.inner_dim)
181
+ else:
182
+ self.proj_in = torch.nn.Conv2d(self.in_channels, self.inner_dim, kernel_size=1, stride=1, padding=0)
183
+
184
+ self.transformer_blocks = nn.ModuleList(
185
+ [
186
+ BasicTransformerBlock(
187
+ self.inner_dim,
188
+ self.config.num_attention_heads,
189
+ self.config.attention_head_dim,
190
+ dropout=self.config.dropout,
191
+ cross_attention_dim=self.config.cross_attention_dim,
192
+ activation_fn=self.config.activation_fn,
193
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
194
+ attention_bias=self.config.attention_bias,
195
+ only_cross_attention=self.config.only_cross_attention,
196
+ double_self_attention=self.config.double_self_attention,
197
+ upcast_attention=self.config.upcast_attention,
198
+ norm_type=norm_type,
199
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
200
+ norm_eps=self.config.norm_eps,
201
+ attention_type=self.config.attention_type,
202
+ )
203
+ for _ in range(self.config.num_layers)
204
+ ]
205
+ )
206
+
207
+ if self.use_linear_projection:
208
+ self.proj_out = torch.nn.Linear(self.inner_dim, self.out_channels)
209
+ else:
210
+ self.proj_out = torch.nn.Conv2d(self.inner_dim, self.out_channels, kernel_size=1, stride=1, padding=0)
211
+
212
+ def _init_vectorized_inputs(self, norm_type):
213
+ assert self.config.sample_size is not None, "Transformer2DModel over discrete input must provide sample_size"
214
+ assert self.config.num_vector_embeds is not None, (
215
+ "Transformer2DModel over discrete input must provide num_embed"
216
+ )
217
+
218
+ self.height = self.config.sample_size
219
+ self.width = self.config.sample_size
220
+ self.num_latent_pixels = self.height * self.width
221
+
222
+ self.latent_image_embedding = ImagePositionalEmbeddings(
223
+ num_embed=self.config.num_vector_embeds, embed_dim=self.inner_dim, height=self.height, width=self.width
224
+ )
225
+
226
+ self.transformer_blocks = nn.ModuleList(
227
+ [
228
+ BasicTransformerBlock(
229
+ self.inner_dim,
230
+ self.config.num_attention_heads,
231
+ self.config.attention_head_dim,
232
+ dropout=self.config.dropout,
233
+ cross_attention_dim=self.config.cross_attention_dim,
234
+ activation_fn=self.config.activation_fn,
235
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
236
+ attention_bias=self.config.attention_bias,
237
+ only_cross_attention=self.config.only_cross_attention,
238
+ double_self_attention=self.config.double_self_attention,
239
+ upcast_attention=self.config.upcast_attention,
240
+ norm_type=norm_type,
241
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
242
+ norm_eps=self.config.norm_eps,
243
+ attention_type=self.config.attention_type,
244
+ )
245
+ for _ in range(self.config.num_layers)
246
+ ]
247
+ )
248
+
249
+ self.norm_out = nn.LayerNorm(self.inner_dim)
250
+ self.out = nn.Linear(self.inner_dim, self.config.num_vector_embeds - 1)
251
+
252
+ def _init_patched_inputs(self, norm_type):
253
+ assert self.config.sample_size is not None, "Transformer2DModel over patched input must provide sample_size"
254
+
255
+ self.height = self.config.sample_size
256
+ self.width = self.config.sample_size
257
+
258
+ self.patch_size = self.config.patch_size
259
+ interpolation_scale = (
260
+ self.config.interpolation_scale
261
+ if self.config.interpolation_scale is not None
262
+ else max(self.config.sample_size // 64, 1)
263
+ )
264
+ self.pos_embed = PatchEmbed(
265
+ height=self.config.sample_size,
266
+ width=self.config.sample_size,
267
+ patch_size=self.config.patch_size,
268
+ in_channels=self.in_channels,
269
+ embed_dim=self.inner_dim,
270
+ interpolation_scale=interpolation_scale,
271
+ )
272
+
273
+ self.transformer_blocks = nn.ModuleList(
274
+ [
275
+ BasicTransformerBlock(
276
+ self.inner_dim,
277
+ self.config.num_attention_heads,
278
+ self.config.attention_head_dim,
279
+ dropout=self.config.dropout,
280
+ cross_attention_dim=self.config.cross_attention_dim,
281
+ activation_fn=self.config.activation_fn,
282
+ num_embeds_ada_norm=self.config.num_embeds_ada_norm,
283
+ attention_bias=self.config.attention_bias,
284
+ only_cross_attention=self.config.only_cross_attention,
285
+ double_self_attention=self.config.double_self_attention,
286
+ upcast_attention=self.config.upcast_attention,
287
+ norm_type=norm_type,
288
+ norm_elementwise_affine=self.config.norm_elementwise_affine,
289
+ norm_eps=self.config.norm_eps,
290
+ attention_type=self.config.attention_type,
291
+ )
292
+ for _ in range(self.config.num_layers)
293
+ ]
294
+ )
295
+
296
+ if self.config.norm_type != "ada_norm_single":
297
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
298
+ self.proj_out_1 = nn.Linear(self.inner_dim, 2 * self.inner_dim)
299
+ self.proj_out_2 = nn.Linear(
300
+ self.inner_dim, self.config.patch_size * self.config.patch_size * self.out_channels
301
+ )
302
+ elif self.config.norm_type == "ada_norm_single":
303
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
304
+ self.scale_shift_table = nn.Parameter(torch.randn(2, self.inner_dim) / self.inner_dim**0.5)
305
+ self.proj_out = nn.Linear(
306
+ self.inner_dim, self.config.patch_size * self.config.patch_size * self.out_channels
307
+ )
308
+
309
+ # PixArt-Alpha blocks.
310
+ self.adaln_single = None
311
+ if self.config.norm_type == "ada_norm_single":
312
+ # TODO(Sayak, PVP) clean this, for now we use sample size to determine whether to use
313
+ # additional conditions until we find better name
314
+ self.adaln_single = AdaLayerNormSingle(
315
+ self.inner_dim, use_additional_conditions=self.use_additional_conditions
316
+ )
317
+
318
+ self.caption_projection = None
319
+ if self.caption_channels is not None:
320
+ self.caption_projection = PixArtAlphaTextProjection(
321
+ in_features=self.caption_channels, hidden_size=self.inner_dim
322
+ )
323
+
324
+ def forward(
325
+ self,
326
+ hidden_states: torch.Tensor,
327
+ encoder_hidden_states: Optional[torch.Tensor] = None,
328
+ timestep: Optional[torch.LongTensor] = None,
329
+ added_cond_kwargs: Dict[str, torch.Tensor] = None,
330
+ class_labels: Optional[torch.LongTensor] = None,
331
+ cross_attention_kwargs: Dict[str, Any] = None,
332
+ attention_mask: Optional[torch.Tensor] = None,
333
+ encoder_attention_mask: Optional[torch.Tensor] = None,
334
+ return_dict: bool = True,
335
+ ):
336
+ """
337
+ The [`Transformer2DModel`] forward method.
338
+
339
+ Args:
340
+ hidden_states (`torch.LongTensor` of shape `(batch size, num latent pixels)` if discrete, `torch.Tensor` of shape `(batch size, channel, height, width)` if continuous):
341
+ Input `hidden_states`.
342
+ encoder_hidden_states ( `torch.Tensor` of shape `(batch size, sequence len, embed dims)`, *optional*):
343
+ Conditional embeddings for cross attention layer. If not given, cross-attention defaults to
344
+ self-attention.
345
+ timestep ( `torch.LongTensor`, *optional*):
346
+ Used to indicate denoising step. Optional timestep to be applied as an embedding in `AdaLayerNorm`.
347
+ class_labels ( `torch.LongTensor` of shape `(batch size, num classes)`, *optional*):
348
+ Used to indicate class labels conditioning. Optional class labels to be applied as an embedding in
349
+ `AdaLayerZeroNorm`.
350
+ cross_attention_kwargs ( `Dict[str, Any]`, *optional*):
351
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
352
+ `self.processor` in
353
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
354
+ attention_mask ( `torch.Tensor`, *optional*):
355
+ An attention mask of shape `(batch, key_tokens)` is applied to `encoder_hidden_states`. If `1` the mask
356
+ is kept, otherwise if `0` it is discarded. Mask will be converted into a bias, which adds large
357
+ negative values to the attention scores corresponding to "discard" tokens.
358
+ encoder_attention_mask ( `torch.Tensor`, *optional*):
359
+ Cross-attention mask applied to `encoder_hidden_states`. Two formats supported:
360
+
361
+ * Mask `(batch, sequence_length)` True = keep, False = discard.
362
+ * Bias `(batch, 1, sequence_length)` 0 = keep, -10000 = discard.
363
+
364
+ If `ndim == 2`: will be interpreted as a mask, then converted into a bias consistent with the format
365
+ above. This bias will be added to the cross-attention scores.
366
+ return_dict (`bool`, *optional*, defaults to `True`):
367
+ Whether or not to return a [`~models.unets.unet_2d_condition.UNet2DConditionOutput`] instead of a plain
368
+ tuple.
369
+
370
+ Returns:
371
+ If `return_dict` is True, an [`~models.transformers.transformer_2d.Transformer2DModelOutput`] is returned,
372
+ otherwise a `tuple` where the first element is the sample tensor.
373
+ """
374
+ if cross_attention_kwargs is not None:
375
+ if cross_attention_kwargs.get("scale", None) is not None:
376
+ logger.warning("Passing `scale` to `cross_attention_kwargs` is deprecated. `scale` will be ignored.")
377
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
378
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
379
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
380
+ # expects mask of shape:
381
+ # [batch, key_tokens]
382
+ # adds singleton query_tokens dimension:
383
+ # [batch, 1, key_tokens]
384
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
385
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
386
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn)
387
+ if attention_mask is not None and attention_mask.ndim == 2:
388
+ # assume that mask is expressed as:
389
+ # (1 = keep, 0 = discard)
390
+ # convert mask into a bias that can be added to attention scores:
391
+ # (keep = +0, discard = -10000.0)
392
+ attention_mask = (1 - attention_mask.to(hidden_states.dtype)) * -10000.0
393
+ attention_mask = attention_mask.unsqueeze(1)
394
+
395
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
396
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
397
+ encoder_attention_mask = (1 - encoder_attention_mask.to(hidden_states.dtype)) * -10000.0
398
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
399
+
400
+ # 1. Input
401
+ if self.is_input_continuous:
402
+ batch_size, _, height, width = hidden_states.shape
403
+ residual = hidden_states
404
+ hidden_states, inner_dim = self._operate_on_continuous_inputs(hidden_states)
405
+ elif self.is_input_vectorized:
406
+ hidden_states = self.latent_image_embedding(hidden_states)
407
+ elif self.is_input_patches:
408
+ height, width = hidden_states.shape[-2] // self.patch_size, hidden_states.shape[-1] // self.patch_size
409
+ hidden_states, encoder_hidden_states, timestep, embedded_timestep = self._operate_on_patched_inputs(
410
+ hidden_states, encoder_hidden_states, timestep, added_cond_kwargs
411
+ )
412
+
413
+ # 2. Blocks
414
+ for block in self.transformer_blocks:
415
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
416
+ hidden_states = self._gradient_checkpointing_func(
417
+ block,
418
+ hidden_states,
419
+ attention_mask,
420
+ encoder_hidden_states,
421
+ encoder_attention_mask,
422
+ timestep,
423
+ cross_attention_kwargs,
424
+ class_labels,
425
+ )
426
+ else:
427
+ hidden_states = block(
428
+ hidden_states,
429
+ attention_mask=attention_mask,
430
+ encoder_hidden_states=encoder_hidden_states,
431
+ encoder_attention_mask=encoder_attention_mask,
432
+ timestep=timestep,
433
+ cross_attention_kwargs=cross_attention_kwargs,
434
+ class_labels=class_labels,
435
+ )
436
+
437
+ # 3. Output
438
+ if self.is_input_continuous:
439
+ output = self._get_output_for_continuous_inputs(
440
+ hidden_states=hidden_states,
441
+ residual=residual,
442
+ batch_size=batch_size,
443
+ height=height,
444
+ width=width,
445
+ inner_dim=inner_dim,
446
+ )
447
+ elif self.is_input_vectorized:
448
+ output = self._get_output_for_vectorized_inputs(hidden_states)
449
+ elif self.is_input_patches:
450
+ output = self._get_output_for_patched_inputs(
451
+ hidden_states=hidden_states,
452
+ timestep=timestep,
453
+ class_labels=class_labels,
454
+ embedded_timestep=embedded_timestep,
455
+ height=height,
456
+ width=width,
457
+ )
458
+
459
+ if not return_dict:
460
+ return (output,)
461
+
462
+ return Transformer2DModelOutput(sample=output)
463
+
464
+ def _operate_on_continuous_inputs(self, hidden_states):
465
+ batch, _, height, width = hidden_states.shape
466
+ hidden_states = self.norm(hidden_states)
467
+
468
+ if not self.use_linear_projection:
469
+ hidden_states = self.proj_in(hidden_states)
470
+ inner_dim = hidden_states.shape[1]
471
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
472
+ else:
473
+ inner_dim = hidden_states.shape[1]
474
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)
475
+ hidden_states = self.proj_in(hidden_states)
476
+
477
+ return hidden_states, inner_dim
478
+
479
+ def _operate_on_patched_inputs(self, hidden_states, encoder_hidden_states, timestep, added_cond_kwargs):
480
+ batch_size = hidden_states.shape[0]
481
+ hidden_states = self.pos_embed(hidden_states)
482
+ embedded_timestep = None
483
+
484
+ if self.adaln_single is not None:
485
+ if self.use_additional_conditions and added_cond_kwargs is None:
486
+ raise ValueError(
487
+ "`added_cond_kwargs` cannot be None when using additional conditions for `adaln_single`."
488
+ )
489
+ timestep, embedded_timestep = self.adaln_single(
490
+ timestep, added_cond_kwargs, batch_size=batch_size, hidden_dtype=hidden_states.dtype
491
+ )
492
+
493
+ if self.caption_projection is not None:
494
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
495
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, hidden_states.shape[-1])
496
+
497
+ return hidden_states, encoder_hidden_states, timestep, embedded_timestep
498
+
499
+ def _get_output_for_continuous_inputs(self, hidden_states, residual, batch_size, height, width, inner_dim):
500
+ if not self.use_linear_projection:
501
+ hidden_states = (
502
+ hidden_states.reshape(batch_size, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
503
+ )
504
+ hidden_states = self.proj_out(hidden_states)
505
+ else:
506
+ hidden_states = self.proj_out(hidden_states)
507
+ hidden_states = (
508
+ hidden_states.reshape(batch_size, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()
509
+ )
510
+
511
+ output = hidden_states + residual
512
+ return output
513
+
514
+ def _get_output_for_vectorized_inputs(self, hidden_states):
515
+ hidden_states = self.norm_out(hidden_states)
516
+ logits = self.out(hidden_states)
517
+ # (batch, self.num_vector_embeds - 1, self.num_latent_pixels)
518
+ logits = logits.permute(0, 2, 1)
519
+ # log(p(x_0))
520
+ output = F.log_softmax(logits.double(), dim=1).float()
521
+ return output
522
+
523
+ def _get_output_for_patched_inputs(
524
+ self, hidden_states, timestep, class_labels, embedded_timestep, height=None, width=None
525
+ ):
526
+ if self.config.norm_type != "ada_norm_single":
527
+ conditioning = self.transformer_blocks[0].norm1.emb(
528
+ timestep, class_labels, hidden_dtype=hidden_states.dtype
529
+ )
530
+ shift, scale = self.proj_out_1(F.silu(conditioning)).chunk(2, dim=1)
531
+ hidden_states = self.norm_out(hidden_states) * (1 + scale[:, None]) + shift[:, None]
532
+ hidden_states = self.proj_out_2(hidden_states)
533
+ elif self.config.norm_type == "ada_norm_single":
534
+ shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
535
+ hidden_states = self.norm_out(hidden_states)
536
+ # Modulation
537
+ hidden_states = hidden_states * (1 + scale) + shift
538
+ hidden_states = self.proj_out(hidden_states)
539
+ hidden_states = hidden_states.squeeze(1)
540
+
541
+ # unpatchify
542
+ if self.adaln_single is None:
543
+ height = width = int(hidden_states.shape[1] ** 0.5)
544
+ hidden_states = hidden_states.reshape(
545
+ shape=(-1, height, width, self.patch_size, self.patch_size, self.out_channels)
546
+ )
547
+ hidden_states = torch.einsum("nhwpqc->nchpwq", hidden_states)
548
+ output = hidden_states.reshape(
549
+ shape=(-1, self.out_channels, height * self.patch_size, width * self.patch_size)
550
+ )
551
+ return output
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_allegro.py ADDED
@@ -0,0 +1,414 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The RhymesAI and The HuggingFace Team.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import Optional, Tuple
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+ import torch.nn.functional as F
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...utils import logging
24
+ from ...utils.torch_utils import maybe_allow_in_graph
25
+ from ..attention import FeedForward
26
+ from ..attention_processor import AllegroAttnProcessor2_0, Attention
27
+ from ..cache_utils import CacheMixin
28
+ from ..embeddings import PatchEmbed, PixArtAlphaTextProjection
29
+ from ..modeling_outputs import Transformer2DModelOutput
30
+ from ..modeling_utils import ModelMixin
31
+ from ..normalization import AdaLayerNormSingle
32
+
33
+
34
+ logger = logging.get_logger(__name__)
35
+
36
+
37
+ @maybe_allow_in_graph
38
+ class AllegroTransformerBlock(nn.Module):
39
+ r"""
40
+ Transformer block used in [Allegro](https://github.com/rhymes-ai/Allegro) model.
41
+
42
+ Args:
43
+ dim (`int`):
44
+ The number of channels in the input and output.
45
+ num_attention_heads (`int`):
46
+ The number of heads to use for multi-head attention.
47
+ attention_head_dim (`int`):
48
+ The number of channels in each head.
49
+ dropout (`float`, defaults to `0.0`):
50
+ The dropout probability to use.
51
+ cross_attention_dim (`int`, defaults to `2304`):
52
+ The dimension of the cross attention features.
53
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
54
+ Activation function to be used in feed-forward.
55
+ attention_bias (`bool`, defaults to `False`):
56
+ Whether or not to use bias in attention projection layers.
57
+ only_cross_attention (`bool`, defaults to `False`):
58
+ norm_elementwise_affine (`bool`, defaults to `True`):
59
+ Whether to use learnable elementwise affine parameters for normalization.
60
+ norm_eps (`float`, defaults to `1e-5`):
61
+ Epsilon value for normalization layers.
62
+ final_dropout (`bool` defaults to `False`):
63
+ Whether to apply a final dropout after the last feed-forward layer.
64
+ """
65
+
66
+ def __init__(
67
+ self,
68
+ dim: int,
69
+ num_attention_heads: int,
70
+ attention_head_dim: int,
71
+ dropout=0.0,
72
+ cross_attention_dim: Optional[int] = None,
73
+ activation_fn: str = "geglu",
74
+ attention_bias: bool = False,
75
+ norm_elementwise_affine: bool = True,
76
+ norm_eps: float = 1e-5,
77
+ ):
78
+ super().__init__()
79
+
80
+ # 1. Self Attention
81
+ self.norm1 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
82
+
83
+ self.attn1 = Attention(
84
+ query_dim=dim,
85
+ heads=num_attention_heads,
86
+ dim_head=attention_head_dim,
87
+ dropout=dropout,
88
+ bias=attention_bias,
89
+ cross_attention_dim=None,
90
+ processor=AllegroAttnProcessor2_0(),
91
+ )
92
+
93
+ # 2. Cross Attention
94
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
95
+ self.attn2 = Attention(
96
+ query_dim=dim,
97
+ cross_attention_dim=cross_attention_dim,
98
+ heads=num_attention_heads,
99
+ dim_head=attention_head_dim,
100
+ dropout=dropout,
101
+ bias=attention_bias,
102
+ processor=AllegroAttnProcessor2_0(),
103
+ )
104
+
105
+ # 3. Feed Forward
106
+ self.norm3 = nn.LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
107
+
108
+ self.ff = FeedForward(
109
+ dim,
110
+ dropout=dropout,
111
+ activation_fn=activation_fn,
112
+ )
113
+
114
+ # 4. Scale-shift
115
+ self.scale_shift_table = nn.Parameter(torch.randn(6, dim) / dim**0.5)
116
+
117
+ def forward(
118
+ self,
119
+ hidden_states: torch.Tensor,
120
+ encoder_hidden_states: Optional[torch.Tensor] = None,
121
+ temb: Optional[torch.LongTensor] = None,
122
+ attention_mask: Optional[torch.Tensor] = None,
123
+ encoder_attention_mask: Optional[torch.Tensor] = None,
124
+ image_rotary_emb=None,
125
+ ) -> torch.Tensor:
126
+ # 0. Self-Attention
127
+ batch_size = hidden_states.shape[0]
128
+
129
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = (
130
+ self.scale_shift_table[None] + temb.reshape(batch_size, 6, -1)
131
+ ).chunk(6, dim=1)
132
+ norm_hidden_states = self.norm1(hidden_states)
133
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa) + shift_msa
134
+ norm_hidden_states = norm_hidden_states.squeeze(1)
135
+
136
+ attn_output = self.attn1(
137
+ norm_hidden_states,
138
+ encoder_hidden_states=None,
139
+ attention_mask=attention_mask,
140
+ image_rotary_emb=image_rotary_emb,
141
+ )
142
+ attn_output = gate_msa * attn_output
143
+
144
+ hidden_states = attn_output + hidden_states
145
+ if hidden_states.ndim == 4:
146
+ hidden_states = hidden_states.squeeze(1)
147
+
148
+ # 1. Cross-Attention
149
+ if self.attn2 is not None:
150
+ norm_hidden_states = hidden_states
151
+
152
+ attn_output = self.attn2(
153
+ norm_hidden_states,
154
+ encoder_hidden_states=encoder_hidden_states,
155
+ attention_mask=encoder_attention_mask,
156
+ image_rotary_emb=None,
157
+ )
158
+ hidden_states = attn_output + hidden_states
159
+
160
+ # 2. Feed-forward
161
+ norm_hidden_states = self.norm2(hidden_states)
162
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp) + shift_mlp
163
+
164
+ ff_output = self.ff(norm_hidden_states)
165
+ ff_output = gate_mlp * ff_output
166
+
167
+ hidden_states = ff_output + hidden_states
168
+
169
+ # TODO(aryan): maybe following line is not required
170
+ if hidden_states.ndim == 4:
171
+ hidden_states = hidden_states.squeeze(1)
172
+
173
+ return hidden_states
174
+
175
+
176
+ class AllegroTransformer3DModel(ModelMixin, ConfigMixin, CacheMixin):
177
+ _supports_gradient_checkpointing = True
178
+
179
+ """
180
+ A 3D Transformer model for video-like data.
181
+
182
+ Args:
183
+ patch_size (`int`, defaults to `2`):
184
+ The size of spatial patches to use in the patch embedding layer.
185
+ patch_size_t (`int`, defaults to `1`):
186
+ The size of temporal patches to use in the patch embedding layer.
187
+ num_attention_heads (`int`, defaults to `24`):
188
+ The number of heads to use for multi-head attention.
189
+ attention_head_dim (`int`, defaults to `96`):
190
+ The number of channels in each head.
191
+ in_channels (`int`, defaults to `4`):
192
+ The number of channels in the input.
193
+ out_channels (`int`, *optional*, defaults to `4`):
194
+ The number of channels in the output.
195
+ num_layers (`int`, defaults to `32`):
196
+ The number of layers of Transformer blocks to use.
197
+ dropout (`float`, defaults to `0.0`):
198
+ The dropout probability to use.
199
+ cross_attention_dim (`int`, defaults to `2304`):
200
+ The dimension of the cross attention features.
201
+ attention_bias (`bool`, defaults to `True`):
202
+ Whether or not to use bias in the attention projection layers.
203
+ sample_height (`int`, defaults to `90`):
204
+ The height of the input latents.
205
+ sample_width (`int`, defaults to `160`):
206
+ The width of the input latents.
207
+ sample_frames (`int`, defaults to `22`):
208
+ The number of frames in the input latents.
209
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
210
+ Activation function to use in feed-forward.
211
+ norm_elementwise_affine (`bool`, defaults to `False`):
212
+ Whether or not to use elementwise affine in normalization layers.
213
+ norm_eps (`float`, defaults to `1e-6`):
214
+ The epsilon value to use in normalization layers.
215
+ caption_channels (`int`, defaults to `4096`):
216
+ Number of channels to use for projecting the caption embeddings.
217
+ interpolation_scale_h (`float`, defaults to `2.0`):
218
+ Scaling factor to apply in 3D positional embeddings across height dimension.
219
+ interpolation_scale_w (`float`, defaults to `2.0`):
220
+ Scaling factor to apply in 3D positional embeddings across width dimension.
221
+ interpolation_scale_t (`float`, defaults to `2.2`):
222
+ Scaling factor to apply in 3D positional embeddings across time dimension.
223
+ """
224
+
225
+ _supports_gradient_checkpointing = True
226
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm", "adaln_single"]
227
+
228
+ @register_to_config
229
+ def __init__(
230
+ self,
231
+ patch_size: int = 2,
232
+ patch_size_t: int = 1,
233
+ num_attention_heads: int = 24,
234
+ attention_head_dim: int = 96,
235
+ in_channels: int = 4,
236
+ out_channels: int = 4,
237
+ num_layers: int = 32,
238
+ dropout: float = 0.0,
239
+ cross_attention_dim: int = 2304,
240
+ attention_bias: bool = True,
241
+ sample_height: int = 90,
242
+ sample_width: int = 160,
243
+ sample_frames: int = 22,
244
+ activation_fn: str = "gelu-approximate",
245
+ norm_elementwise_affine: bool = False,
246
+ norm_eps: float = 1e-6,
247
+ caption_channels: int = 4096,
248
+ interpolation_scale_h: float = 2.0,
249
+ interpolation_scale_w: float = 2.0,
250
+ interpolation_scale_t: float = 2.2,
251
+ ):
252
+ super().__init__()
253
+
254
+ self.inner_dim = num_attention_heads * attention_head_dim
255
+
256
+ interpolation_scale_t = (
257
+ interpolation_scale_t
258
+ if interpolation_scale_t is not None
259
+ else ((sample_frames - 1) // 16 + 1)
260
+ if sample_frames % 2 == 1
261
+ else sample_frames // 16
262
+ )
263
+ interpolation_scale_h = interpolation_scale_h if interpolation_scale_h is not None else sample_height / 30
264
+ interpolation_scale_w = interpolation_scale_w if interpolation_scale_w is not None else sample_width / 40
265
+
266
+ # 1. Patch embedding
267
+ self.pos_embed = PatchEmbed(
268
+ height=sample_height,
269
+ width=sample_width,
270
+ patch_size=patch_size,
271
+ in_channels=in_channels,
272
+ embed_dim=self.inner_dim,
273
+ pos_embed_type=None,
274
+ )
275
+
276
+ # 2. Transformer blocks
277
+ self.transformer_blocks = nn.ModuleList(
278
+ [
279
+ AllegroTransformerBlock(
280
+ self.inner_dim,
281
+ num_attention_heads,
282
+ attention_head_dim,
283
+ dropout=dropout,
284
+ cross_attention_dim=cross_attention_dim,
285
+ activation_fn=activation_fn,
286
+ attention_bias=attention_bias,
287
+ norm_elementwise_affine=norm_elementwise_affine,
288
+ norm_eps=norm_eps,
289
+ )
290
+ for _ in range(num_layers)
291
+ ]
292
+ )
293
+
294
+ # 3. Output projection & norm
295
+ self.norm_out = nn.LayerNorm(self.inner_dim, elementwise_affine=False, eps=1e-6)
296
+ self.scale_shift_table = nn.Parameter(torch.randn(2, self.inner_dim) / self.inner_dim**0.5)
297
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * out_channels)
298
+
299
+ # 4. Timestep embeddings
300
+ self.adaln_single = AdaLayerNormSingle(self.inner_dim, use_additional_conditions=False)
301
+
302
+ # 5. Caption projection
303
+ self.caption_projection = PixArtAlphaTextProjection(in_features=caption_channels, hidden_size=self.inner_dim)
304
+
305
+ self.gradient_checkpointing = False
306
+
307
+ def forward(
308
+ self,
309
+ hidden_states: torch.Tensor,
310
+ encoder_hidden_states: torch.Tensor,
311
+ timestep: torch.LongTensor,
312
+ attention_mask: Optional[torch.Tensor] = None,
313
+ encoder_attention_mask: Optional[torch.Tensor] = None,
314
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
315
+ return_dict: bool = True,
316
+ ):
317
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
318
+ p_t = self.config.patch_size_t
319
+ p = self.config.patch_size
320
+
321
+ post_patch_num_frames = num_frames // p_t
322
+ post_patch_height = height // p
323
+ post_patch_width = width // p
324
+
325
+ # ensure attention_mask is a bias, and give it a singleton query_tokens dimension.
326
+ # we may have done this conversion already, e.g. if we came here via UNet2DConditionModel#forward.
327
+ # we can tell by counting dims; if ndim == 2: it's a mask rather than a bias.
328
+ # expects mask of shape:
329
+ # [batch, key_tokens]
330
+ # adds singleton query_tokens dimension:
331
+ # [batch, 1, key_tokens]
332
+ # this helps to broadcast it as a bias over attention scores, which will be in one of the following shapes:
333
+ # [batch, heads, query_tokens, key_tokens] (e.g. torch sdp attn)
334
+ # [batch * heads, query_tokens, key_tokens] (e.g. xformers or classic attn) attention_mask_vid, attention_mask_img = None, None
335
+ if attention_mask is not None and attention_mask.ndim == 4:
336
+ # assume that mask is expressed as:
337
+ # (1 = keep, 0 = discard)
338
+ # convert mask into a bias that can be added to attention scores:
339
+ # (keep = +0, discard = -10000.0)
340
+ # b, frame+use_image_num, h, w -> a video with images
341
+ # b, 1, h, w -> only images
342
+ attention_mask = attention_mask.to(hidden_states.dtype)
343
+ attention_mask = attention_mask[:, :num_frames] # [batch_size, num_frames, height, width]
344
+
345
+ if attention_mask.numel() > 0:
346
+ attention_mask = attention_mask.unsqueeze(1) # [batch_size, 1, num_frames, height, width]
347
+ attention_mask = F.max_pool3d(attention_mask, kernel_size=(p_t, p, p), stride=(p_t, p, p))
348
+ attention_mask = attention_mask.flatten(1).view(batch_size, 1, -1)
349
+
350
+ attention_mask = (
351
+ (1 - attention_mask.bool().to(hidden_states.dtype)) * -10000.0 if attention_mask.numel() > 0 else None
352
+ )
353
+
354
+ # convert encoder_attention_mask to a bias the same way we do for attention_mask
355
+ if encoder_attention_mask is not None and encoder_attention_mask.ndim == 2:
356
+ encoder_attention_mask = (1 - encoder_attention_mask.to(self.dtype)) * -10000.0
357
+ encoder_attention_mask = encoder_attention_mask.unsqueeze(1)
358
+
359
+ # 1. Timestep embeddings
360
+ timestep, embedded_timestep = self.adaln_single(
361
+ timestep, batch_size=batch_size, hidden_dtype=hidden_states.dtype
362
+ )
363
+
364
+ # 2. Patch embeddings
365
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).flatten(0, 1)
366
+ hidden_states = self.pos_embed(hidden_states)
367
+ hidden_states = hidden_states.unflatten(0, (batch_size, -1)).flatten(1, 2)
368
+
369
+ encoder_hidden_states = self.caption_projection(encoder_hidden_states)
370
+ encoder_hidden_states = encoder_hidden_states.view(batch_size, -1, encoder_hidden_states.shape[-1])
371
+
372
+ # 3. Transformer blocks
373
+ for i, block in enumerate(self.transformer_blocks):
374
+ # TODO(aryan): Implement gradient checkpointing
375
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
376
+ hidden_states = self._gradient_checkpointing_func(
377
+ block,
378
+ hidden_states,
379
+ encoder_hidden_states,
380
+ timestep,
381
+ attention_mask,
382
+ encoder_attention_mask,
383
+ image_rotary_emb,
384
+ )
385
+ else:
386
+ hidden_states = block(
387
+ hidden_states=hidden_states,
388
+ encoder_hidden_states=encoder_hidden_states,
389
+ temb=timestep,
390
+ attention_mask=attention_mask,
391
+ encoder_attention_mask=encoder_attention_mask,
392
+ image_rotary_emb=image_rotary_emb,
393
+ )
394
+
395
+ # 4. Output normalization & projection
396
+ shift, scale = (self.scale_shift_table[None] + embedded_timestep[:, None]).chunk(2, dim=1)
397
+ hidden_states = self.norm_out(hidden_states)
398
+
399
+ # Modulation
400
+ hidden_states = hidden_states * (1 + scale) + shift
401
+ hidden_states = self.proj_out(hidden_states)
402
+ hidden_states = hidden_states.squeeze(1)
403
+
404
+ # 5. Unpatchify
405
+ hidden_states = hidden_states.reshape(
406
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p, p, -1
407
+ )
408
+ hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
409
+ output = hidden_states.reshape(batch_size, -1, num_frames, height, width)
410
+
411
+ if not return_dict:
412
+ return (output,)
413
+
414
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_cogview3plus.py ADDED
@@ -0,0 +1,375 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The CogView team, Tsinghua University & ZhipuAI and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Dict, Union
17
+
18
+ import torch
19
+ import torch.nn as nn
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...models.attention import FeedForward
23
+ from ...models.attention_processor import (
24
+ Attention,
25
+ AttentionProcessor,
26
+ CogVideoXAttnProcessor2_0,
27
+ )
28
+ from ...models.modeling_utils import ModelMixin
29
+ from ...models.normalization import AdaLayerNormContinuous
30
+ from ...utils import logging
31
+ from ..embeddings import CogView3CombinedTimestepSizeEmbeddings, CogView3PlusPatchEmbed
32
+ from ..modeling_outputs import Transformer2DModelOutput
33
+ from ..normalization import CogView3PlusAdaLayerNormZeroTextImage
34
+
35
+
36
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
37
+
38
+
39
+ class CogView3PlusTransformerBlock(nn.Module):
40
+ r"""
41
+ Transformer block used in [CogView](https://github.com/THUDM/CogView3) model.
42
+
43
+ Args:
44
+ dim (`int`):
45
+ The number of channels in the input and output.
46
+ num_attention_heads (`int`):
47
+ The number of heads to use for multi-head attention.
48
+ attention_head_dim (`int`):
49
+ The number of channels in each head.
50
+ time_embed_dim (`int`):
51
+ The number of channels in timestep embedding.
52
+ """
53
+
54
+ def __init__(
55
+ self,
56
+ dim: int = 2560,
57
+ num_attention_heads: int = 64,
58
+ attention_head_dim: int = 40,
59
+ time_embed_dim: int = 512,
60
+ ):
61
+ super().__init__()
62
+
63
+ self.norm1 = CogView3PlusAdaLayerNormZeroTextImage(embedding_dim=time_embed_dim, dim=dim)
64
+
65
+ self.attn1 = Attention(
66
+ query_dim=dim,
67
+ heads=num_attention_heads,
68
+ dim_head=attention_head_dim,
69
+ out_dim=dim,
70
+ bias=True,
71
+ qk_norm="layer_norm",
72
+ elementwise_affine=False,
73
+ eps=1e-6,
74
+ processor=CogVideoXAttnProcessor2_0(),
75
+ )
76
+
77
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
78
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
79
+
80
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
81
+
82
+ def forward(
83
+ self,
84
+ hidden_states: torch.Tensor,
85
+ encoder_hidden_states: torch.Tensor,
86
+ emb: torch.Tensor,
87
+ ) -> torch.Tensor:
88
+ text_seq_length = encoder_hidden_states.size(1)
89
+
90
+ # norm & modulate
91
+ (
92
+ norm_hidden_states,
93
+ gate_msa,
94
+ shift_mlp,
95
+ scale_mlp,
96
+ gate_mlp,
97
+ norm_encoder_hidden_states,
98
+ c_gate_msa,
99
+ c_shift_mlp,
100
+ c_scale_mlp,
101
+ c_gate_mlp,
102
+ ) = self.norm1(hidden_states, encoder_hidden_states, emb)
103
+
104
+ # attention
105
+ attn_hidden_states, attn_encoder_hidden_states = self.attn1(
106
+ hidden_states=norm_hidden_states, encoder_hidden_states=norm_encoder_hidden_states
107
+ )
108
+
109
+ hidden_states = hidden_states + gate_msa.unsqueeze(1) * attn_hidden_states
110
+ encoder_hidden_states = encoder_hidden_states + c_gate_msa.unsqueeze(1) * attn_encoder_hidden_states
111
+
112
+ # norm & modulate
113
+ norm_hidden_states = self.norm2(hidden_states)
114
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
115
+
116
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
117
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
118
+
119
+ # feed-forward
120
+ norm_hidden_states = torch.cat([norm_encoder_hidden_states, norm_hidden_states], dim=1)
121
+ ff_output = self.ff(norm_hidden_states)
122
+
123
+ hidden_states = hidden_states + gate_mlp.unsqueeze(1) * ff_output[:, text_seq_length:]
124
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * ff_output[:, :text_seq_length]
125
+
126
+ if hidden_states.dtype == torch.float16:
127
+ hidden_states = hidden_states.clip(-65504, 65504)
128
+ if encoder_hidden_states.dtype == torch.float16:
129
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
130
+ return hidden_states, encoder_hidden_states
131
+
132
+
133
+ class CogView3PlusTransformer2DModel(ModelMixin, ConfigMixin):
134
+ r"""
135
+ The Transformer model introduced in [CogView3: Finer and Faster Text-to-Image Generation via Relay
136
+ Diffusion](https://huggingface.co/papers/2403.05121).
137
+
138
+ Args:
139
+ patch_size (`int`, defaults to `2`):
140
+ The size of the patches to use in the patch embedding layer.
141
+ in_channels (`int`, defaults to `16`):
142
+ The number of channels in the input.
143
+ num_layers (`int`, defaults to `30`):
144
+ The number of layers of Transformer blocks to use.
145
+ attention_head_dim (`int`, defaults to `40`):
146
+ The number of channels in each head.
147
+ num_attention_heads (`int`, defaults to `64`):
148
+ The number of heads to use for multi-head attention.
149
+ out_channels (`int`, defaults to `16`):
150
+ The number of channels in the output.
151
+ text_embed_dim (`int`, defaults to `4096`):
152
+ Input dimension of text embeddings from the text encoder.
153
+ time_embed_dim (`int`, defaults to `512`):
154
+ Output dimension of timestep embeddings.
155
+ condition_dim (`int`, defaults to `256`):
156
+ The embedding dimension of the input SDXL-style resolution conditions (original_size, target_size,
157
+ crop_coords).
158
+ pos_embed_max_size (`int`, defaults to `128`):
159
+ The maximum resolution of the positional embeddings, from which slices of shape `H x W` are taken and added
160
+ to input patched latents, where `H` and `W` are the latent height and width respectively. A value of 128
161
+ means that the maximum supported height and width for image generation is `128 * vae_scale_factor *
162
+ patch_size => 128 * 8 * 2 => 2048`.
163
+ sample_size (`int`, defaults to `128`):
164
+ The base resolution of input latents. If height/width is not provided during generation, this value is used
165
+ to determine the resolution as `sample_size * vae_scale_factor => 128 * 8 => 1024`
166
+ """
167
+
168
+ _supports_gradient_checkpointing = True
169
+ _skip_layerwise_casting_patterns = ["patch_embed", "norm"]
170
+ _no_split_modules = ["CogView3PlusTransformerBlock", "CogView3PlusPatchEmbed"]
171
+
172
+ @register_to_config
173
+ def __init__(
174
+ self,
175
+ patch_size: int = 2,
176
+ in_channels: int = 16,
177
+ num_layers: int = 30,
178
+ attention_head_dim: int = 40,
179
+ num_attention_heads: int = 64,
180
+ out_channels: int = 16,
181
+ text_embed_dim: int = 4096,
182
+ time_embed_dim: int = 512,
183
+ condition_dim: int = 256,
184
+ pos_embed_max_size: int = 128,
185
+ sample_size: int = 128,
186
+ ):
187
+ super().__init__()
188
+ self.out_channels = out_channels
189
+ self.inner_dim = num_attention_heads * attention_head_dim
190
+
191
+ # CogView3 uses 3 additional SDXL-like conditions - original_size, target_size, crop_coords
192
+ # Each of these are sincos embeddings of shape 2 * condition_dim
193
+ self.pooled_projection_dim = 3 * 2 * condition_dim
194
+
195
+ self.patch_embed = CogView3PlusPatchEmbed(
196
+ in_channels=in_channels,
197
+ hidden_size=self.inner_dim,
198
+ patch_size=patch_size,
199
+ text_hidden_size=text_embed_dim,
200
+ pos_embed_max_size=pos_embed_max_size,
201
+ )
202
+
203
+ self.time_condition_embed = CogView3CombinedTimestepSizeEmbeddings(
204
+ embedding_dim=time_embed_dim,
205
+ condition_dim=condition_dim,
206
+ pooled_projection_dim=self.pooled_projection_dim,
207
+ timesteps_dim=self.inner_dim,
208
+ )
209
+
210
+ self.transformer_blocks = nn.ModuleList(
211
+ [
212
+ CogView3PlusTransformerBlock(
213
+ dim=self.inner_dim,
214
+ num_attention_heads=num_attention_heads,
215
+ attention_head_dim=attention_head_dim,
216
+ time_embed_dim=time_embed_dim,
217
+ )
218
+ for _ in range(num_layers)
219
+ ]
220
+ )
221
+
222
+ self.norm_out = AdaLayerNormContinuous(
223
+ embedding_dim=self.inner_dim,
224
+ conditioning_embedding_dim=time_embed_dim,
225
+ elementwise_affine=False,
226
+ eps=1e-6,
227
+ )
228
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
229
+
230
+ self.gradient_checkpointing = False
231
+
232
+ @property
233
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
234
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
235
+ r"""
236
+ Returns:
237
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
238
+ indexed by its weight name.
239
+ """
240
+ # set recursively
241
+ processors = {}
242
+
243
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
244
+ if hasattr(module, "get_processor"):
245
+ processors[f"{name}.processor"] = module.get_processor()
246
+
247
+ for sub_name, child in module.named_children():
248
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
249
+
250
+ return processors
251
+
252
+ for name, module in self.named_children():
253
+ fn_recursive_add_processors(name, module, processors)
254
+
255
+ return processors
256
+
257
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
258
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
259
+ r"""
260
+ Sets the attention processor to use to compute attention.
261
+
262
+ Parameters:
263
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
264
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
265
+ for **all** `Attention` layers.
266
+
267
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
268
+ processor. This is strongly recommended when setting trainable attention processors.
269
+
270
+ """
271
+ count = len(self.attn_processors.keys())
272
+
273
+ if isinstance(processor, dict) and len(processor) != count:
274
+ raise ValueError(
275
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
276
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
277
+ )
278
+
279
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
280
+ if hasattr(module, "set_processor"):
281
+ if not isinstance(processor, dict):
282
+ module.set_processor(processor)
283
+ else:
284
+ module.set_processor(processor.pop(f"{name}.processor"))
285
+
286
+ for sub_name, child in module.named_children():
287
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
288
+
289
+ for name, module in self.named_children():
290
+ fn_recursive_attn_processor(name, module, processor)
291
+
292
+ def forward(
293
+ self,
294
+ hidden_states: torch.Tensor,
295
+ encoder_hidden_states: torch.Tensor,
296
+ timestep: torch.LongTensor,
297
+ original_size: torch.Tensor,
298
+ target_size: torch.Tensor,
299
+ crop_coords: torch.Tensor,
300
+ return_dict: bool = True,
301
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
302
+ """
303
+ The [`CogView3PlusTransformer2DModel`] forward method.
304
+
305
+ Args:
306
+ hidden_states (`torch.Tensor`):
307
+ Input `hidden_states` of shape `(batch size, channel, height, width)`.
308
+ encoder_hidden_states (`torch.Tensor`):
309
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) of shape
310
+ `(batch_size, sequence_len, text_embed_dim)`
311
+ timestep (`torch.LongTensor`):
312
+ Used to indicate denoising step.
313
+ original_size (`torch.Tensor`):
314
+ CogView3 uses SDXL-like micro-conditioning for original image size as explained in section 2.2 of
315
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
316
+ target_size (`torch.Tensor`):
317
+ CogView3 uses SDXL-like micro-conditioning for target image size as explained in section 2.2 of
318
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
319
+ crop_coords (`torch.Tensor`):
320
+ CogView3 uses SDXL-like micro-conditioning for crop coordinates as explained in section 2.2 of
321
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
322
+ return_dict (`bool`, *optional*, defaults to `True`):
323
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
324
+ tuple.
325
+
326
+ Returns:
327
+ `torch.Tensor` or [`~models.transformer_2d.Transformer2DModelOutput`]:
328
+ The denoised latents using provided inputs as conditioning.
329
+ """
330
+ height, width = hidden_states.shape[-2:]
331
+ text_seq_length = encoder_hidden_states.shape[1]
332
+
333
+ hidden_states = self.patch_embed(
334
+ hidden_states, encoder_hidden_states
335
+ ) # takes care of adding positional embeddings too.
336
+ emb = self.time_condition_embed(timestep, original_size, target_size, crop_coords, hidden_states.dtype)
337
+
338
+ encoder_hidden_states = hidden_states[:, :text_seq_length]
339
+ hidden_states = hidden_states[:, text_seq_length:]
340
+
341
+ for index_block, block in enumerate(self.transformer_blocks):
342
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
343
+ hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
344
+ block,
345
+ hidden_states,
346
+ encoder_hidden_states,
347
+ emb,
348
+ )
349
+ else:
350
+ hidden_states, encoder_hidden_states = block(
351
+ hidden_states=hidden_states,
352
+ encoder_hidden_states=encoder_hidden_states,
353
+ emb=emb,
354
+ )
355
+
356
+ hidden_states = self.norm_out(hidden_states, emb)
357
+ hidden_states = self.proj_out(hidden_states) # (batch_size, height*width, patch_size*patch_size*out_channels)
358
+
359
+ # unpatchify
360
+ patch_size = self.config.patch_size
361
+ height = height // patch_size
362
+ width = width // patch_size
363
+
364
+ hidden_states = hidden_states.reshape(
365
+ shape=(hidden_states.shape[0], height, width, self.out_channels, patch_size, patch_size)
366
+ )
367
+ hidden_states = torch.einsum("nhwcpq->nchpwq", hidden_states)
368
+ output = hidden_states.reshape(
369
+ shape=(hidden_states.shape[0], self.out_channels, height * patch_size, width * patch_size)
370
+ )
371
+
372
+ if not return_dict:
373
+ return (output,)
374
+
375
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_cogview4.py ADDED
@@ -0,0 +1,754 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The CogView team, Tsinghua University & ZhipuAI and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from ...configuration_utils import ConfigMixin, register_to_config
22
+ from ...loaders import PeftAdapterMixin
23
+ from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
24
+ from ..attention import FeedForward
25
+ from ..attention_processor import Attention
26
+ from ..cache_utils import CacheMixin
27
+ from ..embeddings import CogView3CombinedTimestepSizeEmbeddings
28
+ from ..modeling_outputs import Transformer2DModelOutput
29
+ from ..modeling_utils import ModelMixin
30
+ from ..normalization import AdaLayerNormContinuous
31
+
32
+
33
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
34
+
35
+
36
+ class CogView4PatchEmbed(nn.Module):
37
+ def __init__(
38
+ self,
39
+ in_channels: int = 16,
40
+ hidden_size: int = 2560,
41
+ patch_size: int = 2,
42
+ text_hidden_size: int = 4096,
43
+ ):
44
+ super().__init__()
45
+ self.patch_size = patch_size
46
+
47
+ self.proj = nn.Linear(in_channels * patch_size**2, hidden_size)
48
+ self.text_proj = nn.Linear(text_hidden_size, hidden_size)
49
+
50
+ def forward(self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor) -> torch.Tensor:
51
+ batch_size, channel, height, width = hidden_states.shape
52
+ post_patch_height = height // self.patch_size
53
+ post_patch_width = width // self.patch_size
54
+
55
+ hidden_states = hidden_states.reshape(
56
+ batch_size, channel, post_patch_height, self.patch_size, post_patch_width, self.patch_size
57
+ )
58
+ hidden_states = hidden_states.permute(0, 2, 4, 1, 3, 5).flatten(3, 5).flatten(1, 2)
59
+ hidden_states = self.proj(hidden_states)
60
+ encoder_hidden_states = self.text_proj(encoder_hidden_states)
61
+
62
+ return hidden_states, encoder_hidden_states
63
+
64
+
65
+ class CogView4AdaLayerNormZero(nn.Module):
66
+ def __init__(self, embedding_dim: int, dim: int) -> None:
67
+ super().__init__()
68
+
69
+ self.norm = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
70
+ self.norm_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
71
+ self.linear = nn.Linear(embedding_dim, 12 * dim, bias=True)
72
+
73
+ def forward(
74
+ self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
75
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
76
+ dtype = hidden_states.dtype
77
+ norm_hidden_states = self.norm(hidden_states).to(dtype=dtype)
78
+ norm_encoder_hidden_states = self.norm_context(encoder_hidden_states).to(dtype=dtype)
79
+
80
+ emb = self.linear(temb)
81
+ (
82
+ shift_msa,
83
+ c_shift_msa,
84
+ scale_msa,
85
+ c_scale_msa,
86
+ gate_msa,
87
+ c_gate_msa,
88
+ shift_mlp,
89
+ c_shift_mlp,
90
+ scale_mlp,
91
+ c_scale_mlp,
92
+ gate_mlp,
93
+ c_gate_mlp,
94
+ ) = emb.chunk(12, dim=1)
95
+
96
+ hidden_states = norm_hidden_states * (1 + scale_msa.unsqueeze(1)) + shift_msa.unsqueeze(1)
97
+ encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_msa.unsqueeze(1)) + c_shift_msa.unsqueeze(1)
98
+
99
+ return (
100
+ hidden_states,
101
+ gate_msa,
102
+ shift_mlp,
103
+ scale_mlp,
104
+ gate_mlp,
105
+ encoder_hidden_states,
106
+ c_gate_msa,
107
+ c_shift_mlp,
108
+ c_scale_mlp,
109
+ c_gate_mlp,
110
+ )
111
+
112
+
113
+ class CogView4AttnProcessor:
114
+ """
115
+ Processor for implementing scaled dot-product attention for the CogView4 model. It applies a rotary embedding on
116
+ query and key vectors, but does not include spatial normalization.
117
+
118
+ The processor supports passing an attention mask for text tokens. The attention mask should have shape (batch_size,
119
+ text_seq_length) where 1 indicates a non-padded token and 0 indicates a padded token.
120
+ """
121
+
122
+ def __init__(self):
123
+ if not hasattr(F, "scaled_dot_product_attention"):
124
+ raise ImportError("CogView4AttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
125
+
126
+ def __call__(
127
+ self,
128
+ attn: Attention,
129
+ hidden_states: torch.Tensor,
130
+ encoder_hidden_states: torch.Tensor,
131
+ attention_mask: Optional[torch.Tensor] = None,
132
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
133
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
134
+ dtype = encoder_hidden_states.dtype
135
+
136
+ batch_size, text_seq_length, embed_dim = encoder_hidden_states.shape
137
+ batch_size, image_seq_length, embed_dim = hidden_states.shape
138
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
139
+
140
+ # 1. QKV projections
141
+ query = attn.to_q(hidden_states)
142
+ key = attn.to_k(hidden_states)
143
+ value = attn.to_v(hidden_states)
144
+
145
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
146
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
147
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
148
+
149
+ # 2. QK normalization
150
+ if attn.norm_q is not None:
151
+ query = attn.norm_q(query).to(dtype=dtype)
152
+ if attn.norm_k is not None:
153
+ key = attn.norm_k(key).to(dtype=dtype)
154
+
155
+ # 3. Rotational positional embeddings applied to latent stream
156
+ if image_rotary_emb is not None:
157
+ from ..embeddings import apply_rotary_emb
158
+
159
+ query[:, :, text_seq_length:, :] = apply_rotary_emb(
160
+ query[:, :, text_seq_length:, :], image_rotary_emb, use_real_unbind_dim=-2
161
+ )
162
+ key[:, :, text_seq_length:, :] = apply_rotary_emb(
163
+ key[:, :, text_seq_length:, :], image_rotary_emb, use_real_unbind_dim=-2
164
+ )
165
+
166
+ # 4. Attention
167
+ if attention_mask is not None:
168
+ text_attn_mask = attention_mask
169
+ assert text_attn_mask.dim() == 2, "the shape of text_attn_mask should be (batch_size, text_seq_length)"
170
+ text_attn_mask = text_attn_mask.float().to(query.device)
171
+ mix_attn_mask = torch.ones((batch_size, text_seq_length + image_seq_length), device=query.device)
172
+ mix_attn_mask[:, :text_seq_length] = text_attn_mask
173
+ mix_attn_mask = mix_attn_mask.unsqueeze(2)
174
+ attn_mask_matrix = mix_attn_mask @ mix_attn_mask.transpose(1, 2)
175
+ attention_mask = (attn_mask_matrix > 0).unsqueeze(1).to(query.dtype)
176
+
177
+ hidden_states = F.scaled_dot_product_attention(
178
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
179
+ )
180
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
181
+ hidden_states = hidden_states.type_as(query)
182
+
183
+ # 5. Output projection
184
+ hidden_states = attn.to_out[0](hidden_states)
185
+ hidden_states = attn.to_out[1](hidden_states)
186
+
187
+ encoder_hidden_states, hidden_states = hidden_states.split(
188
+ [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
189
+ )
190
+ return hidden_states, encoder_hidden_states
191
+
192
+
193
+ class CogView4TrainingAttnProcessor:
194
+ """
195
+ Training Processor for implementing scaled dot-product attention for the CogView4 model. It applies a rotary
196
+ embedding on query and key vectors, but does not include spatial normalization.
197
+
198
+ This processor differs from CogView4AttnProcessor in several important ways:
199
+ 1. It supports attention masking with variable sequence lengths for multi-resolution training
200
+ 2. It unpacks and repacks sequences for efficient training with variable sequence lengths when batch_flag is
201
+ provided
202
+ """
203
+
204
+ def __init__(self):
205
+ if not hasattr(F, "scaled_dot_product_attention"):
206
+ raise ImportError("CogView4AttnProcessor requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
207
+
208
+ def __call__(
209
+ self,
210
+ attn: Attention,
211
+ hidden_states: torch.Tensor,
212
+ encoder_hidden_states: torch.Tensor,
213
+ latent_attn_mask: Optional[torch.Tensor] = None,
214
+ text_attn_mask: Optional[torch.Tensor] = None,
215
+ batch_flag: Optional[torch.Tensor] = None,
216
+ image_rotary_emb: Optional[
217
+ Union[Tuple[torch.Tensor, torch.Tensor], List[Tuple[torch.Tensor, torch.Tensor]]]
218
+ ] = None,
219
+ **kwargs,
220
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
221
+ """
222
+ Args:
223
+ attn (`Attention`):
224
+ The attention module.
225
+ hidden_states (`torch.Tensor`):
226
+ The input hidden states.
227
+ encoder_hidden_states (`torch.Tensor`):
228
+ The encoder hidden states for cross-attention.
229
+ latent_attn_mask (`torch.Tensor`, *optional*):
230
+ Mask for latent tokens where 0 indicates pad token and 1 indicates non-pad token. If None, full
231
+ attention is used for all latent tokens. Note: the shape of latent_attn_mask is (batch_size,
232
+ num_latent_tokens).
233
+ text_attn_mask (`torch.Tensor`, *optional*):
234
+ Mask for text tokens where 0 indicates pad token and 1 indicates non-pad token. If None, full attention
235
+ is used for all text tokens.
236
+ batch_flag (`torch.Tensor`, *optional*):
237
+ Values from 0 to n-1 indicating which samples belong to the same batch. Samples with the same
238
+ batch_flag are packed together. Example: [0, 1, 1, 2, 2] means sample 0 forms batch0, samples 1-2 form
239
+ batch1, and samples 3-4 form batch2. If None, no packing is used.
240
+ image_rotary_emb (`Tuple[torch.Tensor, torch.Tensor]` or `list[Tuple[torch.Tensor, torch.Tensor]]`, *optional*):
241
+ The rotary embedding for the image part of the input.
242
+ Returns:
243
+ `Tuple[torch.Tensor, torch.Tensor]`: The processed hidden states for both image and text streams.
244
+ """
245
+
246
+ # Get dimensions and device info
247
+ batch_size, text_seq_length, embed_dim = encoder_hidden_states.shape
248
+ batch_size, image_seq_length, embed_dim = hidden_states.shape
249
+ dtype = encoder_hidden_states.dtype
250
+ device = encoder_hidden_states.device
251
+ latent_hidden_states = hidden_states
252
+ # Combine text and image streams for joint processing
253
+ mixed_hidden_states = torch.cat([encoder_hidden_states, latent_hidden_states], dim=1)
254
+
255
+ # 1. Construct attention mask and maybe packing input
256
+ # Create default masks if not provided
257
+ if text_attn_mask is None:
258
+ text_attn_mask = torch.ones((batch_size, text_seq_length), dtype=torch.int32, device=device)
259
+ if latent_attn_mask is None:
260
+ latent_attn_mask = torch.ones((batch_size, image_seq_length), dtype=torch.int32, device=device)
261
+
262
+ # Validate mask shapes and types
263
+ assert text_attn_mask.dim() == 2, "the shape of text_attn_mask should be (batch_size, text_seq_length)"
264
+ assert text_attn_mask.dtype == torch.int32, "the dtype of text_attn_mask should be torch.int32"
265
+ assert latent_attn_mask.dim() == 2, "the shape of latent_attn_mask should be (batch_size, num_latent_tokens)"
266
+ assert latent_attn_mask.dtype == torch.int32, "the dtype of latent_attn_mask should be torch.int32"
267
+
268
+ # Create combined mask for text and image tokens
269
+ mixed_attn_mask = torch.ones(
270
+ (batch_size, text_seq_length + image_seq_length), dtype=torch.int32, device=device
271
+ )
272
+ mixed_attn_mask[:, :text_seq_length] = text_attn_mask
273
+ mixed_attn_mask[:, text_seq_length:] = latent_attn_mask
274
+
275
+ # Convert mask to attention matrix format (where 1 means attend, 0 means don't attend)
276
+ mixed_attn_mask_input = mixed_attn_mask.unsqueeze(2).to(dtype=dtype)
277
+ attn_mask_matrix = mixed_attn_mask_input @ mixed_attn_mask_input.transpose(1, 2)
278
+
279
+ # Handle batch packing if enabled
280
+ if batch_flag is not None:
281
+ assert batch_flag.dim() == 1
282
+ # Determine packed batch size based on batch_flag
283
+ packing_batch_size = torch.max(batch_flag).item() + 1
284
+
285
+ # Calculate actual sequence lengths for each sample based on masks
286
+ text_seq_length = torch.sum(text_attn_mask, dim=1)
287
+ latent_seq_length = torch.sum(latent_attn_mask, dim=1)
288
+ mixed_seq_length = text_seq_length + latent_seq_length
289
+
290
+ # Calculate packed sequence lengths for each packed batch
291
+ mixed_seq_length_packed = [
292
+ torch.sum(mixed_attn_mask[batch_flag == batch_idx]).item() for batch_idx in range(packing_batch_size)
293
+ ]
294
+
295
+ assert len(mixed_seq_length_packed) == packing_batch_size
296
+
297
+ # Pack sequences by removing padding tokens
298
+ mixed_attn_mask_flatten = mixed_attn_mask.flatten(0, 1)
299
+ mixed_hidden_states_flatten = mixed_hidden_states.flatten(0, 1)
300
+ mixed_hidden_states_unpad = mixed_hidden_states_flatten[mixed_attn_mask_flatten == 1]
301
+ assert torch.sum(mixed_seq_length) == mixed_hidden_states_unpad.shape[0]
302
+
303
+ # Split the unpadded sequence into packed batches
304
+ mixed_hidden_states_packed = torch.split(mixed_hidden_states_unpad, mixed_seq_length_packed)
305
+
306
+ # Re-pad to create packed batches with right-side padding
307
+ mixed_hidden_states_packed_padded = torch.nn.utils.rnn.pad_sequence(
308
+ mixed_hidden_states_packed,
309
+ batch_first=True,
310
+ padding_value=0.0,
311
+ padding_side="right",
312
+ )
313
+
314
+ # Create attention mask for packed batches
315
+ l = mixed_hidden_states_packed_padded.shape[1]
316
+ attn_mask_matrix = torch.zeros(
317
+ (packing_batch_size, l, l),
318
+ dtype=dtype,
319
+ device=device,
320
+ )
321
+
322
+ # Fill attention mask with block diagonal matrices
323
+ # This ensures that tokens can only attend to other tokens within the same original sample
324
+ for idx, mask in enumerate(attn_mask_matrix):
325
+ seq_lengths = mixed_seq_length[batch_flag == idx]
326
+ offset = 0
327
+ for length in seq_lengths:
328
+ # Create a block of 1s for each sample in the packed batch
329
+ mask[offset : offset + length, offset : offset + length] = 1
330
+ offset += length
331
+
332
+ attn_mask_matrix = attn_mask_matrix.to(dtype=torch.bool)
333
+ attn_mask_matrix = attn_mask_matrix.unsqueeze(1) # Add attention head dim
334
+ attention_mask = attn_mask_matrix
335
+
336
+ # Prepare hidden states for attention computation
337
+ if batch_flag is None:
338
+ # If no packing, just combine text and image tokens
339
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
340
+ else:
341
+ # If packing, use the packed sequence
342
+ hidden_states = mixed_hidden_states_packed_padded
343
+
344
+ # 2. QKV projections - convert hidden states to query, key, value
345
+ query = attn.to_q(hidden_states)
346
+ key = attn.to_k(hidden_states)
347
+ value = attn.to_v(hidden_states)
348
+
349
+ # Reshape for multi-head attention: [batch, seq_len, heads*dim] -> [batch, heads, seq_len, dim]
350
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
351
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
352
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
353
+
354
+ # 3. QK normalization - apply layer norm to queries and keys if configured
355
+ if attn.norm_q is not None:
356
+ query = attn.norm_q(query).to(dtype=dtype)
357
+ if attn.norm_k is not None:
358
+ key = attn.norm_k(key).to(dtype=dtype)
359
+
360
+ # 4. Apply rotary positional embeddings to image tokens only
361
+ if image_rotary_emb is not None:
362
+ from ..embeddings import apply_rotary_emb
363
+
364
+ if batch_flag is None:
365
+ # Apply RoPE only to image tokens (after text tokens)
366
+ query[:, :, text_seq_length:, :] = apply_rotary_emb(
367
+ query[:, :, text_seq_length:, :], image_rotary_emb, use_real_unbind_dim=-2
368
+ )
369
+ key[:, :, text_seq_length:, :] = apply_rotary_emb(
370
+ key[:, :, text_seq_length:, :], image_rotary_emb, use_real_unbind_dim=-2
371
+ )
372
+ else:
373
+ # For packed batches, need to carefully apply RoPE to appropriate tokens
374
+ assert query.shape[0] == packing_batch_size
375
+ assert key.shape[0] == packing_batch_size
376
+ assert len(image_rotary_emb) == batch_size
377
+
378
+ rope_idx = 0
379
+ for idx in range(packing_batch_size):
380
+ offset = 0
381
+ # Get text and image sequence lengths for samples in this packed batch
382
+ text_seq_length_bi = text_seq_length[batch_flag == idx]
383
+ latent_seq_length_bi = latent_seq_length[batch_flag == idx]
384
+
385
+ # Apply RoPE to each image segment in the packed sequence
386
+ for tlen, llen in zip(text_seq_length_bi, latent_seq_length_bi):
387
+ mlen = tlen + llen
388
+ # Apply RoPE only to image tokens (after text tokens)
389
+ query[idx, :, offset + tlen : offset + mlen, :] = apply_rotary_emb(
390
+ query[idx, :, offset + tlen : offset + mlen, :],
391
+ image_rotary_emb[rope_idx],
392
+ use_real_unbind_dim=-2,
393
+ )
394
+ key[idx, :, offset + tlen : offset + mlen, :] = apply_rotary_emb(
395
+ key[idx, :, offset + tlen : offset + mlen, :],
396
+ image_rotary_emb[rope_idx],
397
+ use_real_unbind_dim=-2,
398
+ )
399
+ offset += mlen
400
+ rope_idx += 1
401
+
402
+ hidden_states = F.scaled_dot_product_attention(
403
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
404
+ )
405
+
406
+ # Reshape back: [batch, heads, seq_len, dim] -> [batch, seq_len, heads*dim]
407
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
408
+ hidden_states = hidden_states.type_as(query)
409
+
410
+ # 5. Output projection - project attention output to model dimension
411
+ hidden_states = attn.to_out[0](hidden_states)
412
+ hidden_states = attn.to_out[1](hidden_states)
413
+
414
+ # Split the output back into text and image streams
415
+ if batch_flag is None:
416
+ # Simple split for non-packed case
417
+ encoder_hidden_states, hidden_states = hidden_states.split(
418
+ [text_seq_length, hidden_states.size(1) - text_seq_length], dim=1
419
+ )
420
+ else:
421
+ # For packed case: need to unpack, split text/image, then restore to original shapes
422
+ # First, unpad the sequence based on the packed sequence lengths
423
+ hidden_states_unpad = torch.nn.utils.rnn.unpad_sequence(
424
+ hidden_states,
425
+ lengths=torch.tensor(mixed_seq_length_packed),
426
+ batch_first=True,
427
+ )
428
+ # Concatenate all unpadded sequences
429
+ hidden_states_flatten = torch.cat(hidden_states_unpad, dim=0)
430
+ # Split by original sample sequence lengths
431
+ hidden_states_unpack = torch.split(hidden_states_flatten, mixed_seq_length.tolist())
432
+ assert len(hidden_states_unpack) == batch_size
433
+
434
+ # Further split each sample's sequence into text and image parts
435
+ hidden_states_unpack = [
436
+ torch.split(h, [tlen, llen])
437
+ for h, tlen, llen in zip(hidden_states_unpack, text_seq_length, latent_seq_length)
438
+ ]
439
+ # Separate text and image sequences
440
+ encoder_hidden_states_unpad = [h[0] for h in hidden_states_unpack]
441
+ hidden_states_unpad = [h[1] for h in hidden_states_unpack]
442
+
443
+ # Update the original tensors with the processed values, respecting the attention masks
444
+ for idx in range(batch_size):
445
+ # Place unpacked text tokens back in the encoder_hidden_states tensor
446
+ encoder_hidden_states[idx][text_attn_mask[idx] == 1] = encoder_hidden_states_unpad[idx]
447
+ # Place unpacked image tokens back in the latent_hidden_states tensor
448
+ latent_hidden_states[idx][latent_attn_mask[idx] == 1] = hidden_states_unpad[idx]
449
+
450
+ # Update the output hidden states
451
+ hidden_states = latent_hidden_states
452
+
453
+ return hidden_states, encoder_hidden_states
454
+
455
+
456
+ class CogView4TransformerBlock(nn.Module):
457
+ def __init__(
458
+ self,
459
+ dim: int = 2560,
460
+ num_attention_heads: int = 64,
461
+ attention_head_dim: int = 40,
462
+ time_embed_dim: int = 512,
463
+ ) -> None:
464
+ super().__init__()
465
+
466
+ # 1. Attention
467
+ self.norm1 = CogView4AdaLayerNormZero(time_embed_dim, dim)
468
+ self.attn1 = Attention(
469
+ query_dim=dim,
470
+ heads=num_attention_heads,
471
+ dim_head=attention_head_dim,
472
+ out_dim=dim,
473
+ bias=True,
474
+ qk_norm="layer_norm",
475
+ elementwise_affine=False,
476
+ eps=1e-5,
477
+ processor=CogView4AttnProcessor(),
478
+ )
479
+
480
+ # 2. Feedforward
481
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
482
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-5)
483
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
484
+
485
+ def forward(
486
+ self,
487
+ hidden_states: torch.Tensor,
488
+ encoder_hidden_states: torch.Tensor,
489
+ temb: Optional[torch.Tensor] = None,
490
+ image_rotary_emb: Optional[
491
+ Union[Tuple[torch.Tensor, torch.Tensor], List[Tuple[torch.Tensor, torch.Tensor]]]
492
+ ] = None,
493
+ attention_mask: Optional[Dict[str, torch.Tensor]] = None,
494
+ attention_kwargs: Optional[Dict[str, Any]] = None,
495
+ ) -> torch.Tensor:
496
+ # 1. Timestep conditioning
497
+ (
498
+ norm_hidden_states,
499
+ gate_msa,
500
+ shift_mlp,
501
+ scale_mlp,
502
+ gate_mlp,
503
+ norm_encoder_hidden_states,
504
+ c_gate_msa,
505
+ c_shift_mlp,
506
+ c_scale_mlp,
507
+ c_gate_mlp,
508
+ ) = self.norm1(hidden_states, encoder_hidden_states, temb)
509
+
510
+ # 2. Attention
511
+ if attention_kwargs is None:
512
+ attention_kwargs = {}
513
+ attn_hidden_states, attn_encoder_hidden_states = self.attn1(
514
+ hidden_states=norm_hidden_states,
515
+ encoder_hidden_states=norm_encoder_hidden_states,
516
+ image_rotary_emb=image_rotary_emb,
517
+ attention_mask=attention_mask,
518
+ **attention_kwargs,
519
+ )
520
+ hidden_states = hidden_states + attn_hidden_states * gate_msa.unsqueeze(1)
521
+ encoder_hidden_states = encoder_hidden_states + attn_encoder_hidden_states * c_gate_msa.unsqueeze(1)
522
+
523
+ # 3. Feedforward
524
+ norm_hidden_states = self.norm2(hidden_states) * (1 + scale_mlp.unsqueeze(1)) + shift_mlp.unsqueeze(1)
525
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states) * (
526
+ 1 + c_scale_mlp.unsqueeze(1)
527
+ ) + c_shift_mlp.unsqueeze(1)
528
+
529
+ ff_output = self.ff(norm_hidden_states)
530
+ ff_output_context = self.ff(norm_encoder_hidden_states)
531
+ hidden_states = hidden_states + ff_output * gate_mlp.unsqueeze(1)
532
+ encoder_hidden_states = encoder_hidden_states + ff_output_context * c_gate_mlp.unsqueeze(1)
533
+
534
+ return hidden_states, encoder_hidden_states
535
+
536
+
537
+ class CogView4RotaryPosEmbed(nn.Module):
538
+ def __init__(self, dim: int, patch_size: int, rope_axes_dim: Tuple[int, int], theta: float = 10000.0) -> None:
539
+ super().__init__()
540
+
541
+ self.dim = dim
542
+ self.patch_size = patch_size
543
+ self.rope_axes_dim = rope_axes_dim
544
+ self.theta = theta
545
+
546
+ def forward(self, hidden_states: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
547
+ batch_size, num_channels, height, width = hidden_states.shape
548
+ height, width = height // self.patch_size, width // self.patch_size
549
+
550
+ dim_h, dim_w = self.dim // 2, self.dim // 2
551
+ h_inv_freq = 1.0 / (
552
+ self.theta ** (torch.arange(0, dim_h, 2, dtype=torch.float32)[: (dim_h // 2)].float() / dim_h)
553
+ )
554
+ w_inv_freq = 1.0 / (
555
+ self.theta ** (torch.arange(0, dim_w, 2, dtype=torch.float32)[: (dim_w // 2)].float() / dim_w)
556
+ )
557
+ h_seq = torch.arange(self.rope_axes_dim[0])
558
+ w_seq = torch.arange(self.rope_axes_dim[1])
559
+ freqs_h = torch.outer(h_seq, h_inv_freq)
560
+ freqs_w = torch.outer(w_seq, w_inv_freq)
561
+
562
+ h_idx = torch.arange(height, device=freqs_h.device)
563
+ w_idx = torch.arange(width, device=freqs_w.device)
564
+ inner_h_idx = h_idx * self.rope_axes_dim[0] // height
565
+ inner_w_idx = w_idx * self.rope_axes_dim[1] // width
566
+
567
+ freqs_h = freqs_h[inner_h_idx]
568
+ freqs_w = freqs_w[inner_w_idx]
569
+
570
+ # Create position matrices for height and width
571
+ # [height, 1, dim//4] and [1, width, dim//4]
572
+ freqs_h = freqs_h.unsqueeze(1)
573
+ freqs_w = freqs_w.unsqueeze(0)
574
+ # Broadcast freqs_h and freqs_w to [height, width, dim//4]
575
+ freqs_h = freqs_h.expand(height, width, -1)
576
+ freqs_w = freqs_w.expand(height, width, -1)
577
+
578
+ # Concatenate along last dimension to get [height, width, dim//2]
579
+ freqs = torch.cat([freqs_h, freqs_w], dim=-1)
580
+ freqs = torch.cat([freqs, freqs], dim=-1) # [height, width, dim]
581
+ freqs = freqs.reshape(height * width, -1)
582
+ return (freqs.cos(), freqs.sin())
583
+
584
+
585
+ class CogView4Transformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, CacheMixin):
586
+ r"""
587
+ Args:
588
+ patch_size (`int`, defaults to `2`):
589
+ The size of the patches to use in the patch embedding layer.
590
+ in_channels (`int`, defaults to `16`):
591
+ The number of channels in the input.
592
+ num_layers (`int`, defaults to `30`):
593
+ The number of layers of Transformer blocks to use.
594
+ attention_head_dim (`int`, defaults to `40`):
595
+ The number of channels in each head.
596
+ num_attention_heads (`int`, defaults to `64`):
597
+ The number of heads to use for multi-head attention.
598
+ out_channels (`int`, defaults to `16`):
599
+ The number of channels in the output.
600
+ text_embed_dim (`int`, defaults to `4096`):
601
+ Input dimension of text embeddings from the text encoder.
602
+ time_embed_dim (`int`, defaults to `512`):
603
+ Output dimension of timestep embeddings.
604
+ condition_dim (`int`, defaults to `256`):
605
+ The embedding dimension of the input SDXL-style resolution conditions (original_size, target_size,
606
+ crop_coords).
607
+ pos_embed_max_size (`int`, defaults to `128`):
608
+ The maximum resolution of the positional embeddings, from which slices of shape `H x W` are taken and added
609
+ to input patched latents, where `H` and `W` are the latent height and width respectively. A value of 128
610
+ means that the maximum supported height and width for image generation is `128 * vae_scale_factor *
611
+ patch_size => 128 * 8 * 2 => 2048`.
612
+ sample_size (`int`, defaults to `128`):
613
+ The base resolution of input latents. If height/width is not provided during generation, this value is used
614
+ to determine the resolution as `sample_size * vae_scale_factor => 128 * 8 => 1024`
615
+ """
616
+
617
+ _supports_gradient_checkpointing = True
618
+ _no_split_modules = ["CogView4TransformerBlock", "CogView4PatchEmbed", "CogView4PatchEmbed"]
619
+ _skip_layerwise_casting_patterns = ["patch_embed", "norm", "proj_out"]
620
+
621
+ @register_to_config
622
+ def __init__(
623
+ self,
624
+ patch_size: int = 2,
625
+ in_channels: int = 16,
626
+ out_channels: int = 16,
627
+ num_layers: int = 30,
628
+ attention_head_dim: int = 40,
629
+ num_attention_heads: int = 64,
630
+ text_embed_dim: int = 4096,
631
+ time_embed_dim: int = 512,
632
+ condition_dim: int = 256,
633
+ pos_embed_max_size: int = 128,
634
+ sample_size: int = 128,
635
+ rope_axes_dim: Tuple[int, int] = (256, 256),
636
+ ):
637
+ super().__init__()
638
+
639
+ # CogView4 uses 3 additional SDXL-like conditions - original_size, target_size, crop_coords
640
+ # Each of these are sincos embeddings of shape 2 * condition_dim
641
+ pooled_projection_dim = 3 * 2 * condition_dim
642
+ inner_dim = num_attention_heads * attention_head_dim
643
+ out_channels = out_channels
644
+
645
+ # 1. RoPE
646
+ self.rope = CogView4RotaryPosEmbed(attention_head_dim, patch_size, rope_axes_dim, theta=10000.0)
647
+
648
+ # 2. Patch & Text-timestep embedding
649
+ self.patch_embed = CogView4PatchEmbed(in_channels, inner_dim, patch_size, text_embed_dim)
650
+
651
+ self.time_condition_embed = CogView3CombinedTimestepSizeEmbeddings(
652
+ embedding_dim=time_embed_dim,
653
+ condition_dim=condition_dim,
654
+ pooled_projection_dim=pooled_projection_dim,
655
+ timesteps_dim=inner_dim,
656
+ )
657
+
658
+ # 3. Transformer blocks
659
+ self.transformer_blocks = nn.ModuleList(
660
+ [
661
+ CogView4TransformerBlock(inner_dim, num_attention_heads, attention_head_dim, time_embed_dim)
662
+ for _ in range(num_layers)
663
+ ]
664
+ )
665
+
666
+ # 4. Output projection
667
+ self.norm_out = AdaLayerNormContinuous(inner_dim, time_embed_dim, elementwise_affine=False)
668
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels, bias=True)
669
+
670
+ self.gradient_checkpointing = False
671
+
672
+ def forward(
673
+ self,
674
+ hidden_states: torch.Tensor,
675
+ encoder_hidden_states: torch.Tensor,
676
+ timestep: torch.LongTensor,
677
+ original_size: torch.Tensor,
678
+ target_size: torch.Tensor,
679
+ crop_coords: torch.Tensor,
680
+ attention_kwargs: Optional[Dict[str, Any]] = None,
681
+ return_dict: bool = True,
682
+ attention_mask: Optional[torch.Tensor] = None,
683
+ image_rotary_emb: Optional[
684
+ Union[Tuple[torch.Tensor, torch.Tensor], List[Tuple[torch.Tensor, torch.Tensor]]]
685
+ ] = None,
686
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
687
+ if attention_kwargs is not None:
688
+ attention_kwargs = attention_kwargs.copy()
689
+ lora_scale = attention_kwargs.pop("scale", 1.0)
690
+ else:
691
+ lora_scale = 1.0
692
+
693
+ if USE_PEFT_BACKEND:
694
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
695
+ scale_lora_layers(self, lora_scale)
696
+ else:
697
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
698
+ logger.warning(
699
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
700
+ )
701
+
702
+ batch_size, num_channels, height, width = hidden_states.shape
703
+
704
+ # 1. RoPE
705
+ if image_rotary_emb is None:
706
+ image_rotary_emb = self.rope(hidden_states)
707
+
708
+ # 2. Patch & Timestep embeddings
709
+ p = self.config.patch_size
710
+ post_patch_height = height // p
711
+ post_patch_width = width // p
712
+
713
+ hidden_states, encoder_hidden_states = self.patch_embed(hidden_states, encoder_hidden_states)
714
+
715
+ temb = self.time_condition_embed(timestep, original_size, target_size, crop_coords, hidden_states.dtype)
716
+ temb = F.silu(temb)
717
+
718
+ # 3. Transformer blocks
719
+ for block in self.transformer_blocks:
720
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
721
+ hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
722
+ block,
723
+ hidden_states,
724
+ encoder_hidden_states,
725
+ temb,
726
+ image_rotary_emb,
727
+ attention_mask,
728
+ attention_kwargs,
729
+ )
730
+ else:
731
+ hidden_states, encoder_hidden_states = block(
732
+ hidden_states,
733
+ encoder_hidden_states,
734
+ temb,
735
+ image_rotary_emb,
736
+ attention_mask,
737
+ attention_kwargs,
738
+ )
739
+
740
+ # 4. Output norm & projection
741
+ hidden_states = self.norm_out(hidden_states, temb)
742
+ hidden_states = self.proj_out(hidden_states)
743
+
744
+ # 5. Unpatchify
745
+ hidden_states = hidden_states.reshape(batch_size, post_patch_height, post_patch_width, -1, p, p)
746
+ output = hidden_states.permute(0, 3, 1, 4, 2, 5).flatten(4, 5).flatten(2, 3)
747
+
748
+ if USE_PEFT_BACKEND:
749
+ # remove `lora_scale` from each PEFT layer
750
+ unscale_lora_layers(self, lora_scale)
751
+
752
+ if not return_dict:
753
+ return (output,)
754
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_easyanimate.py ADDED
@@ -0,0 +1,527 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2025 The EasyAnimate team and The HuggingFace Team.
2
+ # All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ from typing import List, Optional, Tuple, Union
17
+
18
+ import torch
19
+ import torch.nn.functional as F
20
+ from torch import nn
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...utils import logging
24
+ from ...utils.torch_utils import maybe_allow_in_graph
25
+ from ..attention import Attention, FeedForward
26
+ from ..embeddings import TimestepEmbedding, Timesteps, get_3d_rotary_pos_embed
27
+ from ..modeling_outputs import Transformer2DModelOutput
28
+ from ..modeling_utils import ModelMixin
29
+ from ..normalization import AdaLayerNorm, FP32LayerNorm, RMSNorm
30
+
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+
35
+ class EasyAnimateLayerNormZero(nn.Module):
36
+ def __init__(
37
+ self,
38
+ conditioning_dim: int,
39
+ embedding_dim: int,
40
+ elementwise_affine: bool = True,
41
+ eps: float = 1e-5,
42
+ bias: bool = True,
43
+ norm_type: str = "fp32_layer_norm",
44
+ ) -> None:
45
+ super().__init__()
46
+
47
+ self.silu = nn.SiLU()
48
+ self.linear = nn.Linear(conditioning_dim, 6 * embedding_dim, bias=bias)
49
+
50
+ if norm_type == "layer_norm":
51
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=elementwise_affine, eps=eps)
52
+ elif norm_type == "fp32_layer_norm":
53
+ self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=elementwise_affine, eps=eps)
54
+ else:
55
+ raise ValueError(
56
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
57
+ )
58
+
59
+ def forward(
60
+ self, hidden_states: torch.Tensor, encoder_hidden_states: torch.Tensor, temb: torch.Tensor
61
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
62
+ shift, scale, gate, enc_shift, enc_scale, enc_gate = self.linear(self.silu(temb)).chunk(6, dim=1)
63
+ hidden_states = self.norm(hidden_states) * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
64
+ encoder_hidden_states = self.norm(encoder_hidden_states) * (1 + enc_scale.unsqueeze(1)) + enc_shift.unsqueeze(
65
+ 1
66
+ )
67
+ return hidden_states, encoder_hidden_states, gate, enc_gate
68
+
69
+
70
+ class EasyAnimateRotaryPosEmbed(nn.Module):
71
+ def __init__(self, patch_size: int, rope_dim: List[int]) -> None:
72
+ super().__init__()
73
+
74
+ self.patch_size = patch_size
75
+ self.rope_dim = rope_dim
76
+
77
+ def get_resize_crop_region_for_grid(self, src, tgt_width, tgt_height):
78
+ tw = tgt_width
79
+ th = tgt_height
80
+ h, w = src
81
+ r = h / w
82
+ if r > (th / tw):
83
+ resize_height = th
84
+ resize_width = int(round(th / h * w))
85
+ else:
86
+ resize_width = tw
87
+ resize_height = int(round(tw / w * h))
88
+
89
+ crop_top = int(round((th - resize_height) / 2.0))
90
+ crop_left = int(round((tw - resize_width) / 2.0))
91
+
92
+ return (crop_top, crop_left), (crop_top + resize_height, crop_left + resize_width)
93
+
94
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
95
+ bs, c, num_frames, grid_height, grid_width = hidden_states.size()
96
+ grid_height = grid_height // self.patch_size
97
+ grid_width = grid_width // self.patch_size
98
+ base_size_width = 90 // self.patch_size
99
+ base_size_height = 60 // self.patch_size
100
+
101
+ grid_crops_coords = self.get_resize_crop_region_for_grid(
102
+ (grid_height, grid_width), base_size_width, base_size_height
103
+ )
104
+ image_rotary_emb = get_3d_rotary_pos_embed(
105
+ self.rope_dim,
106
+ grid_crops_coords,
107
+ grid_size=(grid_height, grid_width),
108
+ temporal_size=hidden_states.size(2),
109
+ use_real=True,
110
+ )
111
+ return image_rotary_emb
112
+
113
+
114
+ class EasyAnimateAttnProcessor2_0:
115
+ r"""
116
+ Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). This is
117
+ used in the EasyAnimateTransformer3DModel model.
118
+ """
119
+
120
+ def __init__(self):
121
+ if not hasattr(F, "scaled_dot_product_attention"):
122
+ raise ImportError(
123
+ "EasyAnimateAttnProcessor2_0 requires PyTorch 2.0 or above. To use it, please install PyTorch 2.0."
124
+ )
125
+
126
+ def __call__(
127
+ self,
128
+ attn: Attention,
129
+ hidden_states: torch.Tensor,
130
+ encoder_hidden_states: torch.Tensor,
131
+ attention_mask: Optional[torch.Tensor] = None,
132
+ image_rotary_emb: Optional[torch.Tensor] = None,
133
+ ) -> torch.Tensor:
134
+ if attn.add_q_proj is None and encoder_hidden_states is not None:
135
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
136
+
137
+ # 1. QKV projections
138
+ query = attn.to_q(hidden_states)
139
+ key = attn.to_k(hidden_states)
140
+ value = attn.to_v(hidden_states)
141
+
142
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
143
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
144
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
145
+
146
+ # 2. QK normalization
147
+ if attn.norm_q is not None:
148
+ query = attn.norm_q(query)
149
+ if attn.norm_k is not None:
150
+ key = attn.norm_k(key)
151
+
152
+ # 3. Encoder condition QKV projection and normalization
153
+ if attn.add_q_proj is not None and encoder_hidden_states is not None:
154
+ encoder_query = attn.add_q_proj(encoder_hidden_states)
155
+ encoder_key = attn.add_k_proj(encoder_hidden_states)
156
+ encoder_value = attn.add_v_proj(encoder_hidden_states)
157
+
158
+ encoder_query = encoder_query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
159
+ encoder_key = encoder_key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
160
+ encoder_value = encoder_value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
161
+
162
+ if attn.norm_added_q is not None:
163
+ encoder_query = attn.norm_added_q(encoder_query)
164
+ if attn.norm_added_k is not None:
165
+ encoder_key = attn.norm_added_k(encoder_key)
166
+
167
+ query = torch.cat([encoder_query, query], dim=2)
168
+ key = torch.cat([encoder_key, key], dim=2)
169
+ value = torch.cat([encoder_value, value], dim=2)
170
+
171
+ if image_rotary_emb is not None:
172
+ from ..embeddings import apply_rotary_emb
173
+
174
+ query[:, :, encoder_hidden_states.shape[1] :] = apply_rotary_emb(
175
+ query[:, :, encoder_hidden_states.shape[1] :], image_rotary_emb
176
+ )
177
+ if not attn.is_cross_attention:
178
+ key[:, :, encoder_hidden_states.shape[1] :] = apply_rotary_emb(
179
+ key[:, :, encoder_hidden_states.shape[1] :], image_rotary_emb
180
+ )
181
+
182
+ # 5. Attention
183
+ hidden_states = F.scaled_dot_product_attention(
184
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
185
+ )
186
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
187
+ hidden_states = hidden_states.to(query.dtype)
188
+
189
+ # 6. Output projection
190
+ if encoder_hidden_states is not None:
191
+ encoder_hidden_states, hidden_states = (
192
+ hidden_states[:, : encoder_hidden_states.shape[1]],
193
+ hidden_states[:, encoder_hidden_states.shape[1] :],
194
+ )
195
+
196
+ if getattr(attn, "to_out", None) is not None:
197
+ hidden_states = attn.to_out[0](hidden_states)
198
+ hidden_states = attn.to_out[1](hidden_states)
199
+
200
+ if getattr(attn, "to_add_out", None) is not None:
201
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
202
+ else:
203
+ if getattr(attn, "to_out", None) is not None:
204
+ hidden_states = attn.to_out[0](hidden_states)
205
+ hidden_states = attn.to_out[1](hidden_states)
206
+
207
+ return hidden_states, encoder_hidden_states
208
+
209
+
210
+ @maybe_allow_in_graph
211
+ class EasyAnimateTransformerBlock(nn.Module):
212
+ def __init__(
213
+ self,
214
+ dim: int,
215
+ num_attention_heads: int,
216
+ attention_head_dim: int,
217
+ time_embed_dim: int,
218
+ dropout: float = 0.0,
219
+ activation_fn: str = "gelu-approximate",
220
+ norm_elementwise_affine: bool = True,
221
+ norm_eps: float = 1e-6,
222
+ final_dropout: bool = True,
223
+ ff_inner_dim: Optional[int] = None,
224
+ ff_bias: bool = True,
225
+ qk_norm: bool = True,
226
+ after_norm: bool = False,
227
+ norm_type: str = "fp32_layer_norm",
228
+ is_mmdit_block: bool = True,
229
+ ):
230
+ super().__init__()
231
+
232
+ # Attention Part
233
+ self.norm1 = EasyAnimateLayerNormZero(
234
+ time_embed_dim, dim, norm_elementwise_affine, norm_eps, norm_type=norm_type, bias=True
235
+ )
236
+
237
+ self.attn1 = Attention(
238
+ query_dim=dim,
239
+ dim_head=attention_head_dim,
240
+ heads=num_attention_heads,
241
+ qk_norm="layer_norm" if qk_norm else None,
242
+ eps=1e-6,
243
+ bias=True,
244
+ added_proj_bias=True,
245
+ added_kv_proj_dim=dim if is_mmdit_block else None,
246
+ context_pre_only=False if is_mmdit_block else None,
247
+ processor=EasyAnimateAttnProcessor2_0(),
248
+ )
249
+
250
+ # FFN Part
251
+ self.norm2 = EasyAnimateLayerNormZero(
252
+ time_embed_dim, dim, norm_elementwise_affine, norm_eps, norm_type=norm_type, bias=True
253
+ )
254
+ self.ff = FeedForward(
255
+ dim,
256
+ dropout=dropout,
257
+ activation_fn=activation_fn,
258
+ final_dropout=final_dropout,
259
+ inner_dim=ff_inner_dim,
260
+ bias=ff_bias,
261
+ )
262
+
263
+ self.txt_ff = None
264
+ if is_mmdit_block:
265
+ self.txt_ff = FeedForward(
266
+ dim,
267
+ dropout=dropout,
268
+ activation_fn=activation_fn,
269
+ final_dropout=final_dropout,
270
+ inner_dim=ff_inner_dim,
271
+ bias=ff_bias,
272
+ )
273
+
274
+ self.norm3 = None
275
+ if after_norm:
276
+ self.norm3 = FP32LayerNorm(dim, elementwise_affine=norm_elementwise_affine, eps=norm_eps)
277
+
278
+ def forward(
279
+ self,
280
+ hidden_states: torch.Tensor,
281
+ encoder_hidden_states: torch.Tensor,
282
+ temb: torch.Tensor,
283
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
284
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
285
+ # 1. Attention
286
+ norm_hidden_states, norm_encoder_hidden_states, gate_msa, enc_gate_msa = self.norm1(
287
+ hidden_states, encoder_hidden_states, temb
288
+ )
289
+ attn_hidden_states, attn_encoder_hidden_states = self.attn1(
290
+ hidden_states=norm_hidden_states,
291
+ encoder_hidden_states=norm_encoder_hidden_states,
292
+ image_rotary_emb=image_rotary_emb,
293
+ )
294
+ hidden_states = hidden_states + gate_msa.unsqueeze(1) * attn_hidden_states
295
+ encoder_hidden_states = encoder_hidden_states + enc_gate_msa.unsqueeze(1) * attn_encoder_hidden_states
296
+
297
+ # 2. Feed-forward
298
+ norm_hidden_states, norm_encoder_hidden_states, gate_ff, enc_gate_ff = self.norm2(
299
+ hidden_states, encoder_hidden_states, temb
300
+ )
301
+ if self.norm3 is not None:
302
+ norm_hidden_states = self.norm3(self.ff(norm_hidden_states))
303
+ if self.txt_ff is not None:
304
+ norm_encoder_hidden_states = self.norm3(self.txt_ff(norm_encoder_hidden_states))
305
+ else:
306
+ norm_encoder_hidden_states = self.norm3(self.ff(norm_encoder_hidden_states))
307
+ else:
308
+ norm_hidden_states = self.ff(norm_hidden_states)
309
+ if self.txt_ff is not None:
310
+ norm_encoder_hidden_states = self.txt_ff(norm_encoder_hidden_states)
311
+ else:
312
+ norm_encoder_hidden_states = self.ff(norm_encoder_hidden_states)
313
+ hidden_states = hidden_states + gate_ff.unsqueeze(1) * norm_hidden_states
314
+ encoder_hidden_states = encoder_hidden_states + enc_gate_ff.unsqueeze(1) * norm_encoder_hidden_states
315
+ return hidden_states, encoder_hidden_states
316
+
317
+
318
+ class EasyAnimateTransformer3DModel(ModelMixin, ConfigMixin):
319
+ """
320
+ A Transformer model for video-like data in [EasyAnimate](https://github.com/aigc-apps/EasyAnimate).
321
+
322
+ Parameters:
323
+ num_attention_heads (`int`, defaults to `48`):
324
+ The number of heads to use for multi-head attention.
325
+ attention_head_dim (`int`, defaults to `64`):
326
+ The number of channels in each head.
327
+ in_channels (`int`, defaults to `16`):
328
+ The number of channels in the input.
329
+ out_channels (`int`, *optional*, defaults to `16`):
330
+ The number of channels in the output.
331
+ patch_size (`int`, defaults to `2`):
332
+ The size of the patches to use in the patch embedding layer.
333
+ sample_width (`int`, defaults to `90`):
334
+ The width of the input latents.
335
+ sample_height (`int`, defaults to `60`):
336
+ The height of the input latents.
337
+ activation_fn (`str`, defaults to `"gelu-approximate"`):
338
+ Activation function to use in feed-forward.
339
+ timestep_activation_fn (`str`, defaults to `"silu"`):
340
+ Activation function to use when generating the timestep embeddings.
341
+ num_layers (`int`, defaults to `30`):
342
+ The number of layers of Transformer blocks to use.
343
+ mmdit_layers (`int`, defaults to `1000`):
344
+ The number of layers of Multi Modal Transformer blocks to use.
345
+ dropout (`float`, defaults to `0.0`):
346
+ The dropout probability to use.
347
+ time_embed_dim (`int`, defaults to `512`):
348
+ Output dimension of timestep embeddings.
349
+ text_embed_dim (`int`, defaults to `4096`):
350
+ Input dimension of text embeddings from the text encoder.
351
+ norm_eps (`float`, defaults to `1e-5`):
352
+ The epsilon value to use in normalization layers.
353
+ norm_elementwise_affine (`bool`, defaults to `True`):
354
+ Whether to use elementwise affine in normalization layers.
355
+ flip_sin_to_cos (`bool`, defaults to `True`):
356
+ Whether to flip the sin to cos in the time embedding.
357
+ time_position_encoding_type (`str`, defaults to `3d_rope`):
358
+ Type of time position encoding.
359
+ after_norm (`bool`, defaults to `False`):
360
+ Flag to apply normalization after.
361
+ resize_inpaint_mask_directly (`bool`, defaults to `True`):
362
+ Flag to resize inpaint mask directly.
363
+ enable_text_attention_mask (`bool`, defaults to `True`):
364
+ Flag to enable text attention mask.
365
+ add_noise_in_inpaint_model (`bool`, defaults to `False`):
366
+ Flag to add noise in inpaint model.
367
+ """
368
+
369
+ _supports_gradient_checkpointing = True
370
+ _no_split_modules = ["EasyAnimateTransformerBlock"]
371
+ _skip_layerwise_casting_patterns = ["^proj$", "norm", "^proj_out$"]
372
+
373
+ @register_to_config
374
+ def __init__(
375
+ self,
376
+ num_attention_heads: int = 48,
377
+ attention_head_dim: int = 64,
378
+ in_channels: Optional[int] = None,
379
+ out_channels: Optional[int] = None,
380
+ patch_size: Optional[int] = None,
381
+ sample_width: int = 90,
382
+ sample_height: int = 60,
383
+ activation_fn: str = "gelu-approximate",
384
+ timestep_activation_fn: str = "silu",
385
+ freq_shift: int = 0,
386
+ num_layers: int = 48,
387
+ mmdit_layers: int = 48,
388
+ dropout: float = 0.0,
389
+ time_embed_dim: int = 512,
390
+ add_norm_text_encoder: bool = False,
391
+ text_embed_dim: int = 3584,
392
+ text_embed_dim_t5: int = None,
393
+ norm_eps: float = 1e-5,
394
+ norm_elementwise_affine: bool = True,
395
+ flip_sin_to_cos: bool = True,
396
+ time_position_encoding_type: str = "3d_rope",
397
+ after_norm=False,
398
+ resize_inpaint_mask_directly: bool = True,
399
+ enable_text_attention_mask: bool = True,
400
+ add_noise_in_inpaint_model: bool = True,
401
+ ):
402
+ super().__init__()
403
+ inner_dim = num_attention_heads * attention_head_dim
404
+
405
+ # 1. Timestep embedding
406
+ self.time_proj = Timesteps(inner_dim, flip_sin_to_cos, freq_shift)
407
+ self.time_embedding = TimestepEmbedding(inner_dim, time_embed_dim, timestep_activation_fn)
408
+ self.rope_embedding = EasyAnimateRotaryPosEmbed(patch_size, attention_head_dim)
409
+
410
+ # 2. Patch embedding
411
+ self.proj = nn.Conv2d(
412
+ in_channels, inner_dim, kernel_size=(patch_size, patch_size), stride=patch_size, bias=True
413
+ )
414
+
415
+ # 3. Text refined embedding
416
+ self.text_proj = None
417
+ self.text_proj_t5 = None
418
+ if not add_norm_text_encoder:
419
+ self.text_proj = nn.Linear(text_embed_dim, inner_dim)
420
+ if text_embed_dim_t5 is not None:
421
+ self.text_proj_t5 = nn.Linear(text_embed_dim_t5, inner_dim)
422
+ else:
423
+ self.text_proj = nn.Sequential(
424
+ RMSNorm(text_embed_dim, 1e-6, elementwise_affine=True), nn.Linear(text_embed_dim, inner_dim)
425
+ )
426
+ if text_embed_dim_t5 is not None:
427
+ self.text_proj_t5 = nn.Sequential(
428
+ RMSNorm(text_embed_dim, 1e-6, elementwise_affine=True), nn.Linear(text_embed_dim_t5, inner_dim)
429
+ )
430
+
431
+ # 4. Transformer blocks
432
+ self.transformer_blocks = nn.ModuleList(
433
+ [
434
+ EasyAnimateTransformerBlock(
435
+ dim=inner_dim,
436
+ num_attention_heads=num_attention_heads,
437
+ attention_head_dim=attention_head_dim,
438
+ time_embed_dim=time_embed_dim,
439
+ dropout=dropout,
440
+ activation_fn=activation_fn,
441
+ norm_elementwise_affine=norm_elementwise_affine,
442
+ norm_eps=norm_eps,
443
+ after_norm=after_norm,
444
+ is_mmdit_block=True if _ < mmdit_layers else False,
445
+ )
446
+ for _ in range(num_layers)
447
+ ]
448
+ )
449
+ self.norm_final = nn.LayerNorm(inner_dim, norm_eps, norm_elementwise_affine)
450
+
451
+ # 5. Output norm & projection
452
+ self.norm_out = AdaLayerNorm(
453
+ embedding_dim=time_embed_dim,
454
+ output_dim=2 * inner_dim,
455
+ norm_elementwise_affine=norm_elementwise_affine,
456
+ norm_eps=norm_eps,
457
+ chunk_dim=1,
458
+ )
459
+ self.proj_out = nn.Linear(inner_dim, patch_size * patch_size * out_channels)
460
+
461
+ self.gradient_checkpointing = False
462
+
463
+ def forward(
464
+ self,
465
+ hidden_states: torch.Tensor,
466
+ timestep: torch.Tensor,
467
+ timestep_cond: Optional[torch.Tensor] = None,
468
+ encoder_hidden_states: Optional[torch.Tensor] = None,
469
+ encoder_hidden_states_t5: Optional[torch.Tensor] = None,
470
+ inpaint_latents: Optional[torch.Tensor] = None,
471
+ control_latents: Optional[torch.Tensor] = None,
472
+ return_dict: bool = True,
473
+ ) -> Union[Tuple[torch.Tensor], Transformer2DModelOutput]:
474
+ batch_size, channels, video_length, height, width = hidden_states.size()
475
+ p = self.config.patch_size
476
+ post_patch_height = height // p
477
+ post_patch_width = width // p
478
+
479
+ # 1. Time embedding
480
+ temb = self.time_proj(timestep).to(dtype=hidden_states.dtype)
481
+ temb = self.time_embedding(temb, timestep_cond)
482
+ image_rotary_emb = self.rope_embedding(hidden_states)
483
+
484
+ # 2. Patch embedding
485
+ if inpaint_latents is not None:
486
+ hidden_states = torch.concat([hidden_states, inpaint_latents], 1)
487
+ if control_latents is not None:
488
+ hidden_states = torch.concat([hidden_states, control_latents], 1)
489
+
490
+ hidden_states = hidden_states.permute(0, 2, 1, 3, 4).flatten(0, 1) # [B, C, F, H, W] -> [BF, C, H, W]
491
+ hidden_states = self.proj(hidden_states)
492
+ hidden_states = hidden_states.unflatten(0, (batch_size, -1)).permute(
493
+ 0, 2, 1, 3, 4
494
+ ) # [BF, C, H, W] -> [B, F, C, H, W]
495
+ hidden_states = hidden_states.flatten(2, 4).transpose(1, 2) # [B, F, C, H, W] -> [B, FHW, C]
496
+
497
+ # 3. Text embedding
498
+ encoder_hidden_states = self.text_proj(encoder_hidden_states)
499
+ if encoder_hidden_states_t5 is not None:
500
+ encoder_hidden_states_t5 = self.text_proj_t5(encoder_hidden_states_t5)
501
+ encoder_hidden_states = torch.cat([encoder_hidden_states, encoder_hidden_states_t5], dim=1).contiguous()
502
+
503
+ # 4. Transformer blocks
504
+ for block in self.transformer_blocks:
505
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
506
+ hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
507
+ block, hidden_states, encoder_hidden_states, temb, image_rotary_emb
508
+ )
509
+ else:
510
+ hidden_states, encoder_hidden_states = block(
511
+ hidden_states, encoder_hidden_states, temb, image_rotary_emb
512
+ )
513
+
514
+ hidden_states = self.norm_final(hidden_states)
515
+
516
+ # 5. Output norm & projection
517
+ hidden_states = self.norm_out(hidden_states, temb=temb)
518
+ hidden_states = self.proj_out(hidden_states)
519
+
520
+ # 6. Unpatchify
521
+ p = self.config.patch_size
522
+ output = hidden_states.reshape(batch_size, video_length, post_patch_height, post_patch_width, channels, p, p)
523
+ output = output.permute(0, 4, 1, 2, 5, 3, 6).flatten(5, 6).flatten(3, 4)
524
+
525
+ if not return_dict:
526
+ return (output,)
527
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_flux.py ADDED
@@ -0,0 +1,551 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 Black Forest Labs, The HuggingFace Team and The InstantX Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+
16
+ from typing import Any, Dict, Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+ import torch.nn as nn
21
+
22
+ from ...configuration_utils import ConfigMixin, register_to_config
23
+ from ...loaders import FluxTransformer2DLoadersMixin, FromOriginalModelMixin, PeftAdapterMixin
24
+ from ...models.attention import FeedForward
25
+ from ...models.attention_processor import (
26
+ Attention,
27
+ AttentionProcessor,
28
+ FluxAttnProcessor2_0,
29
+ FluxAttnProcessor2_0_NPU,
30
+ FusedFluxAttnProcessor2_0,
31
+ )
32
+ from ...models.modeling_utils import ModelMixin
33
+ from ...models.normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle
34
+ from ...utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
35
+ from ...utils.import_utils import is_torch_npu_available
36
+ from ...utils.torch_utils import maybe_allow_in_graph
37
+ from ..cache_utils import CacheMixin
38
+ from ..embeddings import CombinedTimestepGuidanceTextProjEmbeddings, CombinedTimestepTextProjEmbeddings, FluxPosEmbed
39
+ from ..modeling_outputs import Transformer2DModelOutput
40
+
41
+
42
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
43
+
44
+
45
+ @maybe_allow_in_graph
46
+ class FluxSingleTransformerBlock(nn.Module):
47
+ def __init__(self, dim: int, num_attention_heads: int, attention_head_dim: int, mlp_ratio: float = 4.0):
48
+ super().__init__()
49
+ self.mlp_hidden_dim = int(dim * mlp_ratio)
50
+
51
+ self.norm = AdaLayerNormZeroSingle(dim)
52
+ self.proj_mlp = nn.Linear(dim, self.mlp_hidden_dim)
53
+ self.act_mlp = nn.GELU(approximate="tanh")
54
+ self.proj_out = nn.Linear(dim + self.mlp_hidden_dim, dim)
55
+
56
+ if is_torch_npu_available():
57
+ deprecation_message = (
58
+ "Defaulting to FluxAttnProcessor2_0_NPU for NPU devices will be removed. Attention processors "
59
+ "should be set explicitly using the `set_attn_processor` method."
60
+ )
61
+ deprecate("npu_processor", "0.34.0", deprecation_message)
62
+ processor = FluxAttnProcessor2_0_NPU()
63
+ else:
64
+ processor = FluxAttnProcessor2_0()
65
+
66
+ self.attn = Attention(
67
+ query_dim=dim,
68
+ cross_attention_dim=None,
69
+ dim_head=attention_head_dim,
70
+ heads=num_attention_heads,
71
+ out_dim=dim,
72
+ bias=True,
73
+ processor=processor,
74
+ qk_norm="rms_norm",
75
+ eps=1e-6,
76
+ pre_only=True,
77
+ )
78
+
79
+ def forward(
80
+ self,
81
+ hidden_states: torch.Tensor,
82
+ temb: torch.Tensor,
83
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
84
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
85
+ ) -> torch.Tensor:
86
+ residual = hidden_states
87
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
88
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
89
+ joint_attention_kwargs = joint_attention_kwargs or {}
90
+ attn_output = self.attn(
91
+ hidden_states=norm_hidden_states,
92
+ image_rotary_emb=image_rotary_emb,
93
+ **joint_attention_kwargs,
94
+ )
95
+
96
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
97
+ gate = gate.unsqueeze(1)
98
+ hidden_states = gate * self.proj_out(hidden_states)
99
+ hidden_states = residual + hidden_states
100
+ if hidden_states.dtype == torch.float16:
101
+ hidden_states = hidden_states.clip(-65504, 65504)
102
+
103
+ return hidden_states
104
+
105
+
106
+ @maybe_allow_in_graph
107
+ class FluxTransformerBlock(nn.Module):
108
+ def __init__(
109
+ self, dim: int, num_attention_heads: int, attention_head_dim: int, qk_norm: str = "rms_norm", eps: float = 1e-6
110
+ ):
111
+ super().__init__()
112
+
113
+ self.norm1 = AdaLayerNormZero(dim)
114
+ self.norm1_context = AdaLayerNormZero(dim)
115
+
116
+ self.attn = Attention(
117
+ query_dim=dim,
118
+ cross_attention_dim=None,
119
+ added_kv_proj_dim=dim,
120
+ dim_head=attention_head_dim,
121
+ heads=num_attention_heads,
122
+ out_dim=dim,
123
+ context_pre_only=False,
124
+ bias=True,
125
+ processor=FluxAttnProcessor2_0(),
126
+ qk_norm=qk_norm,
127
+ eps=eps,
128
+ )
129
+
130
+ self.norm2 = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
131
+ self.ff = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
132
+
133
+ self.norm2_context = nn.LayerNorm(dim, elementwise_affine=False, eps=1e-6)
134
+ self.ff_context = FeedForward(dim=dim, dim_out=dim, activation_fn="gelu-approximate")
135
+
136
+ def forward(
137
+ self,
138
+ hidden_states: torch.Tensor,
139
+ encoder_hidden_states: torch.Tensor,
140
+ temb: torch.Tensor,
141
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
142
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
143
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
144
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
145
+
146
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
147
+ encoder_hidden_states, emb=temb
148
+ )
149
+ joint_attention_kwargs = joint_attention_kwargs or {}
150
+ # Attention.
151
+ attention_outputs = self.attn(
152
+ hidden_states=norm_hidden_states,
153
+ encoder_hidden_states=norm_encoder_hidden_states,
154
+ image_rotary_emb=image_rotary_emb,
155
+ **joint_attention_kwargs,
156
+ )
157
+
158
+ if len(attention_outputs) == 2:
159
+ attn_output, context_attn_output = attention_outputs
160
+ elif len(attention_outputs) == 3:
161
+ attn_output, context_attn_output, ip_attn_output = attention_outputs
162
+
163
+ # Process attention outputs for the `hidden_states`.
164
+ attn_output = gate_msa.unsqueeze(1) * attn_output
165
+ hidden_states = hidden_states + attn_output
166
+
167
+ norm_hidden_states = self.norm2(hidden_states)
168
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
169
+
170
+ ff_output = self.ff(norm_hidden_states)
171
+ ff_output = gate_mlp.unsqueeze(1) * ff_output
172
+
173
+ hidden_states = hidden_states + ff_output
174
+ if len(attention_outputs) == 3:
175
+ hidden_states = hidden_states + ip_attn_output
176
+
177
+ # Process attention outputs for the `encoder_hidden_states`.
178
+
179
+ context_attn_output = c_gate_msa.unsqueeze(1) * context_attn_output
180
+ encoder_hidden_states = encoder_hidden_states + context_attn_output
181
+
182
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
183
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
184
+
185
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
186
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
187
+ if encoder_hidden_states.dtype == torch.float16:
188
+ encoder_hidden_states = encoder_hidden_states.clip(-65504, 65504)
189
+
190
+ return encoder_hidden_states, hidden_states
191
+
192
+
193
+ class FluxTransformer2DModel(
194
+ ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, FluxTransformer2DLoadersMixin, CacheMixin
195
+ ):
196
+ """
197
+ The Transformer model introduced in Flux.
198
+
199
+ Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
200
+
201
+ Args:
202
+ patch_size (`int`, defaults to `1`):
203
+ Patch size to turn the input data into small patches.
204
+ in_channels (`int`, defaults to `64`):
205
+ The number of channels in the input.
206
+ out_channels (`int`, *optional*, defaults to `None`):
207
+ The number of channels in the output. If not specified, it defaults to `in_channels`.
208
+ num_layers (`int`, defaults to `19`):
209
+ The number of layers of dual stream DiT blocks to use.
210
+ num_single_layers (`int`, defaults to `38`):
211
+ The number of layers of single stream DiT blocks to use.
212
+ attention_head_dim (`int`, defaults to `128`):
213
+ The number of dimensions to use for each attention head.
214
+ num_attention_heads (`int`, defaults to `24`):
215
+ The number of attention heads to use.
216
+ joint_attention_dim (`int`, defaults to `4096`):
217
+ The number of dimensions to use for the joint attention (embedding/channel dimension of
218
+ `encoder_hidden_states`).
219
+ pooled_projection_dim (`int`, defaults to `768`):
220
+ The number of dimensions to use for the pooled projection.
221
+ guidance_embeds (`bool`, defaults to `False`):
222
+ Whether to use guidance embeddings for guidance-distilled variant of the model.
223
+ axes_dims_rope (`Tuple[int]`, defaults to `(16, 56, 56)`):
224
+ The dimensions to use for the rotary positional embeddings.
225
+ """
226
+
227
+ _supports_gradient_checkpointing = True
228
+ _no_split_modules = ["FluxTransformerBlock", "FluxSingleTransformerBlock"]
229
+ _skip_layerwise_casting_patterns = ["pos_embed", "norm"]
230
+
231
+ @register_to_config
232
+ def __init__(
233
+ self,
234
+ patch_size: int = 1,
235
+ in_channels: int = 64,
236
+ out_channels: Optional[int] = None,
237
+ num_layers: int = 19,
238
+ num_single_layers: int = 38,
239
+ attention_head_dim: int = 128,
240
+ num_attention_heads: int = 24,
241
+ joint_attention_dim: int = 4096,
242
+ pooled_projection_dim: int = 768,
243
+ guidance_embeds: bool = False,
244
+ axes_dims_rope: Tuple[int] = (16, 56, 56),
245
+ ):
246
+ super().__init__()
247
+ self.out_channels = out_channels or in_channels
248
+ self.inner_dim = num_attention_heads * attention_head_dim
249
+
250
+ self.pos_embed = FluxPosEmbed(theta=10000, axes_dim=axes_dims_rope)
251
+
252
+ text_time_guidance_cls = (
253
+ CombinedTimestepGuidanceTextProjEmbeddings if guidance_embeds else CombinedTimestepTextProjEmbeddings
254
+ )
255
+ self.time_text_embed = text_time_guidance_cls(
256
+ embedding_dim=self.inner_dim, pooled_projection_dim=pooled_projection_dim
257
+ )
258
+
259
+ self.context_embedder = nn.Linear(joint_attention_dim, self.inner_dim)
260
+ self.x_embedder = nn.Linear(in_channels, self.inner_dim)
261
+
262
+ self.transformer_blocks = nn.ModuleList(
263
+ [
264
+ FluxTransformerBlock(
265
+ dim=self.inner_dim,
266
+ num_attention_heads=num_attention_heads,
267
+ attention_head_dim=attention_head_dim,
268
+ )
269
+ for _ in range(num_layers)
270
+ ]
271
+ )
272
+
273
+ self.single_transformer_blocks = nn.ModuleList(
274
+ [
275
+ FluxSingleTransformerBlock(
276
+ dim=self.inner_dim,
277
+ num_attention_heads=num_attention_heads,
278
+ attention_head_dim=attention_head_dim,
279
+ )
280
+ for _ in range(num_single_layers)
281
+ ]
282
+ )
283
+
284
+ self.norm_out = AdaLayerNormContinuous(self.inner_dim, self.inner_dim, elementwise_affine=False, eps=1e-6)
285
+ self.proj_out = nn.Linear(self.inner_dim, patch_size * patch_size * self.out_channels, bias=True)
286
+
287
+ self.gradient_checkpointing = False
288
+
289
+ @property
290
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
291
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
292
+ r"""
293
+ Returns:
294
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
295
+ indexed by its weight name.
296
+ """
297
+ # set recursively
298
+ processors = {}
299
+
300
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
301
+ if hasattr(module, "get_processor"):
302
+ processors[f"{name}.processor"] = module.get_processor()
303
+
304
+ for sub_name, child in module.named_children():
305
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
306
+
307
+ return processors
308
+
309
+ for name, module in self.named_children():
310
+ fn_recursive_add_processors(name, module, processors)
311
+
312
+ return processors
313
+
314
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
315
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
316
+ r"""
317
+ Sets the attention processor to use to compute attention.
318
+
319
+ Parameters:
320
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
321
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
322
+ for **all** `Attention` layers.
323
+
324
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
325
+ processor. This is strongly recommended when setting trainable attention processors.
326
+
327
+ """
328
+ count = len(self.attn_processors.keys())
329
+
330
+ if isinstance(processor, dict) and len(processor) != count:
331
+ raise ValueError(
332
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
333
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
334
+ )
335
+
336
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
337
+ if hasattr(module, "set_processor"):
338
+ if not isinstance(processor, dict):
339
+ module.set_processor(processor)
340
+ else:
341
+ module.set_processor(processor.pop(f"{name}.processor"))
342
+
343
+ for sub_name, child in module.named_children():
344
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
345
+
346
+ for name, module in self.named_children():
347
+ fn_recursive_attn_processor(name, module, processor)
348
+
349
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.fuse_qkv_projections with FusedAttnProcessor2_0->FusedFluxAttnProcessor2_0
350
+ def fuse_qkv_projections(self):
351
+ """
352
+ Enables fused QKV projections. For self-attention modules, all projection matrices (i.e., query, key, value)
353
+ are fused. For cross-attention modules, key and value projection matrices are fused.
354
+
355
+ <Tip warning={true}>
356
+
357
+ This API is 🧪 experimental.
358
+
359
+ </Tip>
360
+ """
361
+ self.original_attn_processors = None
362
+
363
+ for _, attn_processor in self.attn_processors.items():
364
+ if "Added" in str(attn_processor.__class__.__name__):
365
+ raise ValueError("`fuse_qkv_projections()` is not supported for models having added KV projections.")
366
+
367
+ self.original_attn_processors = self.attn_processors
368
+
369
+ for module in self.modules():
370
+ if isinstance(module, Attention):
371
+ module.fuse_projections(fuse=True)
372
+
373
+ self.set_attn_processor(FusedFluxAttnProcessor2_0())
374
+
375
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.unfuse_qkv_projections
376
+ def unfuse_qkv_projections(self):
377
+ """Disables the fused QKV projection if enabled.
378
+
379
+ <Tip warning={true}>
380
+
381
+ This API is 🧪 experimental.
382
+
383
+ </Tip>
384
+
385
+ """
386
+ if self.original_attn_processors is not None:
387
+ self.set_attn_processor(self.original_attn_processors)
388
+
389
+ def forward(
390
+ self,
391
+ hidden_states: torch.Tensor,
392
+ encoder_hidden_states: torch.Tensor = None,
393
+ pooled_projections: torch.Tensor = None,
394
+ timestep: torch.LongTensor = None,
395
+ img_ids: torch.Tensor = None,
396
+ txt_ids: torch.Tensor = None,
397
+ guidance: torch.Tensor = None,
398
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
399
+ controlnet_block_samples=None,
400
+ controlnet_single_block_samples=None,
401
+ return_dict: bool = True,
402
+ controlnet_blocks_repeat: bool = False,
403
+ ) -> Union[torch.Tensor, Transformer2DModelOutput]:
404
+ """
405
+ The [`FluxTransformer2DModel`] forward method.
406
+
407
+ Args:
408
+ hidden_states (`torch.Tensor` of shape `(batch_size, image_sequence_length, in_channels)`):
409
+ Input `hidden_states`.
410
+ encoder_hidden_states (`torch.Tensor` of shape `(batch_size, text_sequence_length, joint_attention_dim)`):
411
+ Conditional embeddings (embeddings computed from the input conditions such as prompts) to use.
412
+ pooled_projections (`torch.Tensor` of shape `(batch_size, projection_dim)`): Embeddings projected
413
+ from the embeddings of input conditions.
414
+ timestep ( `torch.LongTensor`):
415
+ Used to indicate denoising step.
416
+ block_controlnet_hidden_states: (`list` of `torch.Tensor`):
417
+ A list of tensors that if specified are added to the residuals of transformer blocks.
418
+ joint_attention_kwargs (`dict`, *optional*):
419
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
420
+ `self.processor` in
421
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
422
+ return_dict (`bool`, *optional*, defaults to `True`):
423
+ Whether or not to return a [`~models.transformer_2d.Transformer2DModelOutput`] instead of a plain
424
+ tuple.
425
+
426
+ Returns:
427
+ If `return_dict` is True, an [`~models.transformer_2d.Transformer2DModelOutput`] is returned, otherwise a
428
+ `tuple` where the first element is the sample tensor.
429
+ """
430
+ if joint_attention_kwargs is not None:
431
+ joint_attention_kwargs = joint_attention_kwargs.copy()
432
+ lora_scale = joint_attention_kwargs.pop("scale", 1.0)
433
+ else:
434
+ lora_scale = 1.0
435
+
436
+ if USE_PEFT_BACKEND:
437
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
438
+ scale_lora_layers(self, lora_scale)
439
+ else:
440
+ if joint_attention_kwargs is not None and joint_attention_kwargs.get("scale", None) is not None:
441
+ logger.warning(
442
+ "Passing `scale` via `joint_attention_kwargs` when not using the PEFT backend is ineffective."
443
+ )
444
+
445
+ hidden_states = self.x_embedder(hidden_states)
446
+
447
+ timestep = timestep.to(hidden_states.dtype) * 1000
448
+ if guidance is not None:
449
+ guidance = guidance.to(hidden_states.dtype) * 1000
450
+ else:
451
+ guidance = None
452
+
453
+ temb = (
454
+ self.time_text_embed(timestep, pooled_projections)
455
+ if guidance is None
456
+ else self.time_text_embed(timestep, guidance, pooled_projections)
457
+ )
458
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states)
459
+
460
+ if txt_ids.ndim == 3:
461
+ logger.warning(
462
+ "Passing `txt_ids` 3d torch.Tensor is deprecated."
463
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
464
+ )
465
+ txt_ids = txt_ids[0]
466
+ if img_ids.ndim == 3:
467
+ logger.warning(
468
+ "Passing `img_ids` 3d torch.Tensor is deprecated."
469
+ "Please remove the batch dimension and pass it as a 2d torch Tensor"
470
+ )
471
+ img_ids = img_ids[0]
472
+
473
+ ids = torch.cat((txt_ids, img_ids), dim=0)
474
+ image_rotary_emb = self.pos_embed(ids)
475
+
476
+ if joint_attention_kwargs is not None and "ip_adapter_image_embeds" in joint_attention_kwargs:
477
+ ip_adapter_image_embeds = joint_attention_kwargs.pop("ip_adapter_image_embeds")
478
+ ip_hidden_states = self.encoder_hid_proj(ip_adapter_image_embeds)
479
+ joint_attention_kwargs.update({"ip_hidden_states": ip_hidden_states})
480
+
481
+ for index_block, block in enumerate(self.transformer_blocks):
482
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
483
+ encoder_hidden_states, hidden_states = self._gradient_checkpointing_func(
484
+ block,
485
+ hidden_states,
486
+ encoder_hidden_states,
487
+ temb,
488
+ image_rotary_emb,
489
+ )
490
+
491
+ else:
492
+ encoder_hidden_states, hidden_states = block(
493
+ hidden_states=hidden_states,
494
+ encoder_hidden_states=encoder_hidden_states,
495
+ temb=temb,
496
+ image_rotary_emb=image_rotary_emb,
497
+ joint_attention_kwargs=joint_attention_kwargs,
498
+ )
499
+
500
+ # controlnet residual
501
+ if controlnet_block_samples is not None:
502
+ interval_control = len(self.transformer_blocks) / len(controlnet_block_samples)
503
+ interval_control = int(np.ceil(interval_control))
504
+ # For Xlabs ControlNet.
505
+ if controlnet_blocks_repeat:
506
+ hidden_states = (
507
+ hidden_states + controlnet_block_samples[index_block % len(controlnet_block_samples)]
508
+ )
509
+ else:
510
+ hidden_states = hidden_states + controlnet_block_samples[index_block // interval_control]
511
+ hidden_states = torch.cat([encoder_hidden_states, hidden_states], dim=1)
512
+
513
+ for index_block, block in enumerate(self.single_transformer_blocks):
514
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
515
+ hidden_states = self._gradient_checkpointing_func(
516
+ block,
517
+ hidden_states,
518
+ temb,
519
+ image_rotary_emb,
520
+ )
521
+
522
+ else:
523
+ hidden_states = block(
524
+ hidden_states=hidden_states,
525
+ temb=temb,
526
+ image_rotary_emb=image_rotary_emb,
527
+ joint_attention_kwargs=joint_attention_kwargs,
528
+ )
529
+
530
+ # controlnet residual
531
+ if controlnet_single_block_samples is not None:
532
+ interval_control = len(self.single_transformer_blocks) / len(controlnet_single_block_samples)
533
+ interval_control = int(np.ceil(interval_control))
534
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...] = (
535
+ hidden_states[:, encoder_hidden_states.shape[1] :, ...]
536
+ + controlnet_single_block_samples[index_block // interval_control]
537
+ )
538
+
539
+ hidden_states = hidden_states[:, encoder_hidden_states.shape[1] :, ...]
540
+
541
+ hidden_states = self.norm_out(hidden_states, temb)
542
+ output = self.proj_out(hidden_states)
543
+
544
+ if USE_PEFT_BACKEND:
545
+ # remove `lora_scale` from each PEFT layer
546
+ unscale_lora_layers(self, lora_scale)
547
+
548
+ if not return_dict:
549
+ return (output,)
550
+
551
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_hidream_image.py ADDED
@@ -0,0 +1,922 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Any, Dict, List, Optional, Tuple, Union
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from ...configuration_utils import ConfigMixin, register_to_config
8
+ from ...loaders import PeftAdapterMixin
9
+ from ...models.modeling_outputs import Transformer2DModelOutput
10
+ from ...models.modeling_utils import ModelMixin
11
+ from ...utils import USE_PEFT_BACKEND, deprecate, logging, scale_lora_layers, unscale_lora_layers
12
+ from ...utils.torch_utils import maybe_allow_in_graph
13
+ from ..attention import Attention
14
+ from ..embeddings import TimestepEmbedding, Timesteps
15
+
16
+
17
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
18
+
19
+
20
+ class HiDreamImageFeedForwardSwiGLU(nn.Module):
21
+ def __init__(
22
+ self,
23
+ dim: int,
24
+ hidden_dim: int,
25
+ multiple_of: int = 256,
26
+ ffn_dim_multiplier: Optional[float] = None,
27
+ ):
28
+ super().__init__()
29
+ hidden_dim = int(2 * hidden_dim / 3)
30
+ # custom dim factor multiplier
31
+ if ffn_dim_multiplier is not None:
32
+ hidden_dim = int(ffn_dim_multiplier * hidden_dim)
33
+ hidden_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
34
+
35
+ self.w1 = nn.Linear(dim, hidden_dim, bias=False)
36
+ self.w2 = nn.Linear(hidden_dim, dim, bias=False)
37
+ self.w3 = nn.Linear(dim, hidden_dim, bias=False)
38
+
39
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
40
+ return self.w2(torch.nn.functional.silu(self.w1(x)) * self.w3(x))
41
+
42
+
43
+ class HiDreamImagePooledEmbed(nn.Module):
44
+ def __init__(self, text_emb_dim, hidden_size):
45
+ super().__init__()
46
+ self.pooled_embedder = TimestepEmbedding(in_channels=text_emb_dim, time_embed_dim=hidden_size)
47
+
48
+ def forward(self, pooled_embed: torch.Tensor) -> torch.Tensor:
49
+ return self.pooled_embedder(pooled_embed)
50
+
51
+
52
+ class HiDreamImageTimestepEmbed(nn.Module):
53
+ def __init__(self, hidden_size, frequency_embedding_size=256):
54
+ super().__init__()
55
+ self.time_proj = Timesteps(num_channels=frequency_embedding_size, flip_sin_to_cos=True, downscale_freq_shift=0)
56
+ self.timestep_embedder = TimestepEmbedding(in_channels=frequency_embedding_size, time_embed_dim=hidden_size)
57
+
58
+ def forward(self, timesteps: torch.Tensor, wdtype: Optional[torch.dtype] = None):
59
+ t_emb = self.time_proj(timesteps).to(dtype=wdtype)
60
+ t_emb = self.timestep_embedder(t_emb)
61
+ return t_emb
62
+
63
+
64
+ class HiDreamImageOutEmbed(nn.Module):
65
+ def __init__(self, hidden_size, patch_size, out_channels):
66
+ super().__init__()
67
+ self.norm_final = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
68
+ self.linear = nn.Linear(hidden_size, patch_size * patch_size * out_channels, bias=True)
69
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(hidden_size, 2 * hidden_size, bias=True))
70
+
71
+ def forward(self, hidden_states: torch.Tensor, temb: torch.Tensor) -> torch.Tensor:
72
+ shift, scale = self.adaLN_modulation(temb).chunk(2, dim=1)
73
+ hidden_states = self.norm_final(hidden_states) * (1 + scale.unsqueeze(1)) + shift.unsqueeze(1)
74
+ hidden_states = self.linear(hidden_states)
75
+ return hidden_states
76
+
77
+
78
+ class HiDreamImagePatchEmbed(nn.Module):
79
+ def __init__(
80
+ self,
81
+ patch_size=2,
82
+ in_channels=4,
83
+ out_channels=1024,
84
+ ):
85
+ super().__init__()
86
+ self.patch_size = patch_size
87
+ self.out_channels = out_channels
88
+ self.proj = nn.Linear(in_channels * patch_size * patch_size, out_channels, bias=True)
89
+
90
+ def forward(self, latent):
91
+ latent = self.proj(latent)
92
+ return latent
93
+
94
+
95
+ def rope(pos: torch.Tensor, dim: int, theta: int) -> torch.Tensor:
96
+ assert dim % 2 == 0, "The dimension must be even."
97
+
98
+ is_mps = pos.device.type == "mps"
99
+ is_npu = pos.device.type == "npu"
100
+
101
+ dtype = torch.float32 if (is_mps or is_npu) else torch.float64
102
+
103
+ scale = torch.arange(0, dim, 2, dtype=dtype, device=pos.device) / dim
104
+ omega = 1.0 / (theta**scale)
105
+
106
+ batch_size, seq_length = pos.shape
107
+ out = torch.einsum("...n,d->...nd", pos, omega)
108
+ cos_out = torch.cos(out)
109
+ sin_out = torch.sin(out)
110
+
111
+ stacked_out = torch.stack([cos_out, -sin_out, sin_out, cos_out], dim=-1)
112
+ out = stacked_out.view(batch_size, -1, dim // 2, 2, 2)
113
+ return out.float()
114
+
115
+
116
+ class HiDreamImageEmbedND(nn.Module):
117
+ def __init__(self, theta: int, axes_dim: List[int]):
118
+ super().__init__()
119
+ self.theta = theta
120
+ self.axes_dim = axes_dim
121
+
122
+ def forward(self, ids: torch.Tensor) -> torch.Tensor:
123
+ n_axes = ids.shape[-1]
124
+ emb = torch.cat(
125
+ [rope(ids[..., i], self.axes_dim[i], self.theta) for i in range(n_axes)],
126
+ dim=-3,
127
+ )
128
+ return emb.unsqueeze(2)
129
+
130
+
131
+ def apply_rope(xq: torch.Tensor, xk: torch.Tensor, freqs_cis: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
132
+ xq_ = xq.float().reshape(*xq.shape[:-1], -1, 1, 2)
133
+ xk_ = xk.float().reshape(*xk.shape[:-1], -1, 1, 2)
134
+ xq_out = freqs_cis[..., 0] * xq_[..., 0] + freqs_cis[..., 1] * xq_[..., 1]
135
+ xk_out = freqs_cis[..., 0] * xk_[..., 0] + freqs_cis[..., 1] * xk_[..., 1]
136
+ return xq_out.reshape(*xq.shape).type_as(xq), xk_out.reshape(*xk.shape).type_as(xk)
137
+
138
+
139
+ @maybe_allow_in_graph
140
+ class HiDreamAttention(Attention):
141
+ def __init__(
142
+ self,
143
+ query_dim: int,
144
+ heads: int = 8,
145
+ dim_head: int = 64,
146
+ upcast_attention: bool = False,
147
+ upcast_softmax: bool = False,
148
+ scale_qk: bool = True,
149
+ eps: float = 1e-5,
150
+ processor=None,
151
+ out_dim: int = None,
152
+ single: bool = False,
153
+ ):
154
+ super(Attention, self).__init__()
155
+ self.inner_dim = out_dim if out_dim is not None else dim_head * heads
156
+ self.query_dim = query_dim
157
+ self.upcast_attention = upcast_attention
158
+ self.upcast_softmax = upcast_softmax
159
+ self.out_dim = out_dim if out_dim is not None else query_dim
160
+
161
+ self.scale_qk = scale_qk
162
+ self.scale = dim_head**-0.5 if self.scale_qk else 1.0
163
+
164
+ self.heads = out_dim // dim_head if out_dim is not None else heads
165
+ self.sliceable_head_dim = heads
166
+ self.single = single
167
+
168
+ self.to_q = nn.Linear(query_dim, self.inner_dim)
169
+ self.to_k = nn.Linear(self.inner_dim, self.inner_dim)
170
+ self.to_v = nn.Linear(self.inner_dim, self.inner_dim)
171
+ self.to_out = nn.Linear(self.inner_dim, self.out_dim)
172
+ self.q_rms_norm = nn.RMSNorm(self.inner_dim, eps)
173
+ self.k_rms_norm = nn.RMSNorm(self.inner_dim, eps)
174
+
175
+ if not single:
176
+ self.to_q_t = nn.Linear(query_dim, self.inner_dim)
177
+ self.to_k_t = nn.Linear(self.inner_dim, self.inner_dim)
178
+ self.to_v_t = nn.Linear(self.inner_dim, self.inner_dim)
179
+ self.to_out_t = nn.Linear(self.inner_dim, self.out_dim)
180
+ self.q_rms_norm_t = nn.RMSNorm(self.inner_dim, eps)
181
+ self.k_rms_norm_t = nn.RMSNorm(self.inner_dim, eps)
182
+
183
+ self.set_processor(processor)
184
+
185
+ def forward(
186
+ self,
187
+ norm_hidden_states: torch.Tensor,
188
+ hidden_states_masks: torch.Tensor = None,
189
+ norm_encoder_hidden_states: torch.Tensor = None,
190
+ image_rotary_emb: torch.Tensor = None,
191
+ ) -> torch.Tensor:
192
+ return self.processor(
193
+ self,
194
+ hidden_states=norm_hidden_states,
195
+ hidden_states_masks=hidden_states_masks,
196
+ encoder_hidden_states=norm_encoder_hidden_states,
197
+ image_rotary_emb=image_rotary_emb,
198
+ )
199
+
200
+
201
+ class HiDreamAttnProcessor:
202
+ """Attention processor used typically in processing the SD3-like self-attention projections."""
203
+
204
+ def __call__(
205
+ self,
206
+ attn: HiDreamAttention,
207
+ hidden_states: torch.Tensor,
208
+ hidden_states_masks: Optional[torch.Tensor] = None,
209
+ encoder_hidden_states: Optional[torch.Tensor] = None,
210
+ image_rotary_emb: torch.Tensor = None,
211
+ *args,
212
+ **kwargs,
213
+ ) -> torch.Tensor:
214
+ dtype = hidden_states.dtype
215
+ batch_size = hidden_states.shape[0]
216
+
217
+ query_i = attn.q_rms_norm(attn.to_q(hidden_states)).to(dtype=dtype)
218
+ key_i = attn.k_rms_norm(attn.to_k(hidden_states)).to(dtype=dtype)
219
+ value_i = attn.to_v(hidden_states)
220
+
221
+ inner_dim = key_i.shape[-1]
222
+ head_dim = inner_dim // attn.heads
223
+
224
+ query_i = query_i.view(batch_size, -1, attn.heads, head_dim)
225
+ key_i = key_i.view(batch_size, -1, attn.heads, head_dim)
226
+ value_i = value_i.view(batch_size, -1, attn.heads, head_dim)
227
+ if hidden_states_masks is not None:
228
+ key_i = key_i * hidden_states_masks.view(batch_size, -1, 1, 1)
229
+
230
+ if not attn.single:
231
+ query_t = attn.q_rms_norm_t(attn.to_q_t(encoder_hidden_states)).to(dtype=dtype)
232
+ key_t = attn.k_rms_norm_t(attn.to_k_t(encoder_hidden_states)).to(dtype=dtype)
233
+ value_t = attn.to_v_t(encoder_hidden_states)
234
+
235
+ query_t = query_t.view(batch_size, -1, attn.heads, head_dim)
236
+ key_t = key_t.view(batch_size, -1, attn.heads, head_dim)
237
+ value_t = value_t.view(batch_size, -1, attn.heads, head_dim)
238
+
239
+ num_image_tokens = query_i.shape[1]
240
+ num_text_tokens = query_t.shape[1]
241
+ query = torch.cat([query_i, query_t], dim=1)
242
+ key = torch.cat([key_i, key_t], dim=1)
243
+ value = torch.cat([value_i, value_t], dim=1)
244
+ else:
245
+ query = query_i
246
+ key = key_i
247
+ value = value_i
248
+
249
+ if query.shape[-1] == image_rotary_emb.shape[-3] * 2:
250
+ query, key = apply_rope(query, key, image_rotary_emb)
251
+
252
+ else:
253
+ query_1, query_2 = query.chunk(2, dim=-1)
254
+ key_1, key_2 = key.chunk(2, dim=-1)
255
+ query_1, key_1 = apply_rope(query_1, key_1, image_rotary_emb)
256
+ query = torch.cat([query_1, query_2], dim=-1)
257
+ key = torch.cat([key_1, key_2], dim=-1)
258
+
259
+ hidden_states = F.scaled_dot_product_attention(
260
+ query.transpose(1, 2), key.transpose(1, 2), value.transpose(1, 2), dropout_p=0.0, is_causal=False
261
+ )
262
+
263
+ hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
264
+ hidden_states = hidden_states.to(query.dtype)
265
+
266
+ if not attn.single:
267
+ hidden_states_i, hidden_states_t = torch.split(hidden_states, [num_image_tokens, num_text_tokens], dim=1)
268
+ hidden_states_i = attn.to_out(hidden_states_i)
269
+ hidden_states_t = attn.to_out_t(hidden_states_t)
270
+ return hidden_states_i, hidden_states_t
271
+ else:
272
+ hidden_states = attn.to_out(hidden_states)
273
+ return hidden_states
274
+
275
+
276
+ # Modified from https://github.com/deepseek-ai/DeepSeek-V3/blob/main/inference/model.py
277
+ class MoEGate(nn.Module):
278
+ def __init__(self, embed_dim, num_routed_experts=4, num_activated_experts=2, aux_loss_alpha=0.01):
279
+ super().__init__()
280
+ self.top_k = num_activated_experts
281
+ self.n_routed_experts = num_routed_experts
282
+
283
+ self.scoring_func = "softmax"
284
+ self.alpha = aux_loss_alpha
285
+ self.seq_aux = False
286
+
287
+ # topk selection algorithm
288
+ self.norm_topk_prob = False
289
+ self.gating_dim = embed_dim
290
+ self.weight = nn.Parameter(torch.randn(self.n_routed_experts, self.gating_dim) / embed_dim**0.5)
291
+
292
+ def forward(self, hidden_states):
293
+ bsz, seq_len, h = hidden_states.shape
294
+ # print(bsz, seq_len, h)
295
+ ### compute gating score
296
+ hidden_states = hidden_states.view(-1, h)
297
+ logits = F.linear(hidden_states, self.weight, None)
298
+ if self.scoring_func == "softmax":
299
+ scores = logits.softmax(dim=-1)
300
+ else:
301
+ raise NotImplementedError(f"insupportable scoring function for MoE gating: {self.scoring_func}")
302
+
303
+ ### select top-k experts
304
+ topk_weight, topk_idx = torch.topk(scores, k=self.top_k, dim=-1, sorted=False)
305
+
306
+ ### norm gate to sum 1
307
+ if self.top_k > 1 and self.norm_topk_prob:
308
+ denominator = topk_weight.sum(dim=-1, keepdim=True) + 1e-20
309
+ topk_weight = topk_weight / denominator
310
+
311
+ ### expert-level computation auxiliary loss
312
+ if self.training and self.alpha > 0.0:
313
+ scores_for_aux = scores
314
+ aux_topk = self.top_k
315
+ # always compute aux loss based on the naive greedy topk method
316
+ topk_idx_for_aux_loss = topk_idx.view(bsz, -1)
317
+ if self.seq_aux:
318
+ scores_for_seq_aux = scores_for_aux.view(bsz, seq_len, -1)
319
+ ce = torch.zeros(bsz, self.n_routed_experts, device=hidden_states.device)
320
+ ce.scatter_add_(
321
+ 1, topk_idx_for_aux_loss, torch.ones(bsz, seq_len * aux_topk, device=hidden_states.device)
322
+ ).div_(seq_len * aux_topk / self.n_routed_experts)
323
+ aux_loss = (ce * scores_for_seq_aux.mean(dim=1)).sum(dim=1).mean() * self.alpha
324
+ else:
325
+ mask_ce = F.one_hot(topk_idx_for_aux_loss.view(-1), num_classes=self.n_routed_experts)
326
+ ce = mask_ce.float().mean(0)
327
+
328
+ Pi = scores_for_aux.mean(0)
329
+ fi = ce * self.n_routed_experts
330
+ aux_loss = (Pi * fi).sum() * self.alpha
331
+ else:
332
+ aux_loss = None
333
+ return topk_idx, topk_weight, aux_loss
334
+
335
+
336
+ # Modified from https://github.com/deepseek-ai/DeepSeek-V3/blob/main/inference/model.py
337
+ class MOEFeedForwardSwiGLU(nn.Module):
338
+ def __init__(
339
+ self,
340
+ dim: int,
341
+ hidden_dim: int,
342
+ num_routed_experts: int,
343
+ num_activated_experts: int,
344
+ ):
345
+ super().__init__()
346
+ self.shared_experts = HiDreamImageFeedForwardSwiGLU(dim, hidden_dim // 2)
347
+ self.experts = nn.ModuleList(
348
+ [HiDreamImageFeedForwardSwiGLU(dim, hidden_dim) for i in range(num_routed_experts)]
349
+ )
350
+ self.gate = MoEGate(
351
+ embed_dim=dim, num_routed_experts=num_routed_experts, num_activated_experts=num_activated_experts
352
+ )
353
+ self.num_activated_experts = num_activated_experts
354
+
355
+ def forward(self, x):
356
+ wtype = x.dtype
357
+ identity = x
358
+ orig_shape = x.shape
359
+ topk_idx, topk_weight, aux_loss = self.gate(x)
360
+ x = x.view(-1, x.shape[-1])
361
+ flat_topk_idx = topk_idx.view(-1)
362
+ if self.training:
363
+ x = x.repeat_interleave(self.num_activated_experts, dim=0)
364
+ y = torch.empty_like(x, dtype=wtype)
365
+ for i, expert in enumerate(self.experts):
366
+ y[flat_topk_idx == i] = expert(x[flat_topk_idx == i]).to(dtype=wtype)
367
+ y = (y.view(*topk_weight.shape, -1) * topk_weight.unsqueeze(-1)).sum(dim=1)
368
+ y = y.view(*orig_shape).to(dtype=wtype)
369
+ # y = AddAuxiliaryLoss.apply(y, aux_loss)
370
+ else:
371
+ y = self.moe_infer(x, flat_topk_idx, topk_weight.view(-1, 1)).view(*orig_shape)
372
+ y = y + self.shared_experts(identity)
373
+ return y
374
+
375
+ @torch.no_grad()
376
+ def moe_infer(self, x, flat_expert_indices, flat_expert_weights):
377
+ expert_cache = torch.zeros_like(x)
378
+ idxs = flat_expert_indices.argsort()
379
+ tokens_per_expert = flat_expert_indices.bincount().cpu().numpy().cumsum(0)
380
+ token_idxs = idxs // self.num_activated_experts
381
+ for i, end_idx in enumerate(tokens_per_expert):
382
+ start_idx = 0 if i == 0 else tokens_per_expert[i - 1]
383
+ if start_idx == end_idx:
384
+ continue
385
+ expert = self.experts[i]
386
+ exp_token_idx = token_idxs[start_idx:end_idx]
387
+ expert_tokens = x[exp_token_idx]
388
+ expert_out = expert(expert_tokens)
389
+ expert_out.mul_(flat_expert_weights[idxs[start_idx:end_idx]])
390
+
391
+ # for fp16 and other dtype
392
+ expert_cache = expert_cache.to(expert_out.dtype)
393
+ expert_cache.scatter_reduce_(0, exp_token_idx.view(-1, 1).repeat(1, x.shape[-1]), expert_out, reduce="sum")
394
+ return expert_cache
395
+
396
+
397
+ class TextProjection(nn.Module):
398
+ def __init__(self, in_features, hidden_size):
399
+ super().__init__()
400
+ self.linear = nn.Linear(in_features=in_features, out_features=hidden_size, bias=False)
401
+
402
+ def forward(self, caption):
403
+ hidden_states = self.linear(caption)
404
+ return hidden_states
405
+
406
+
407
+ @maybe_allow_in_graph
408
+ class HiDreamImageSingleTransformerBlock(nn.Module):
409
+ def __init__(
410
+ self,
411
+ dim: int,
412
+ num_attention_heads: int,
413
+ attention_head_dim: int,
414
+ num_routed_experts: int = 4,
415
+ num_activated_experts: int = 2,
416
+ ):
417
+ super().__init__()
418
+ self.num_attention_heads = num_attention_heads
419
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 6 * dim, bias=True))
420
+
421
+ # 1. Attention
422
+ self.norm1_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
423
+ self.attn1 = HiDreamAttention(
424
+ query_dim=dim,
425
+ heads=num_attention_heads,
426
+ dim_head=attention_head_dim,
427
+ processor=HiDreamAttnProcessor(),
428
+ single=True,
429
+ )
430
+
431
+ # 3. Feed-forward
432
+ self.norm3_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
433
+ if num_routed_experts > 0:
434
+ self.ff_i = MOEFeedForwardSwiGLU(
435
+ dim=dim,
436
+ hidden_dim=4 * dim,
437
+ num_routed_experts=num_routed_experts,
438
+ num_activated_experts=num_activated_experts,
439
+ )
440
+ else:
441
+ self.ff_i = HiDreamImageFeedForwardSwiGLU(dim=dim, hidden_dim=4 * dim)
442
+
443
+ def forward(
444
+ self,
445
+ hidden_states: torch.Tensor,
446
+ hidden_states_masks: Optional[torch.Tensor] = None,
447
+ encoder_hidden_states: Optional[torch.Tensor] = None,
448
+ temb: Optional[torch.Tensor] = None,
449
+ image_rotary_emb: torch.Tensor = None,
450
+ ) -> torch.Tensor:
451
+ wtype = hidden_states.dtype
452
+ shift_msa_i, scale_msa_i, gate_msa_i, shift_mlp_i, scale_mlp_i, gate_mlp_i = self.adaLN_modulation(temb)[
453
+ :, None
454
+ ].chunk(6, dim=-1)
455
+
456
+ # 1. MM-Attention
457
+ norm_hidden_states = self.norm1_i(hidden_states).to(dtype=wtype)
458
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa_i) + shift_msa_i
459
+ attn_output_i = self.attn1(
460
+ norm_hidden_states,
461
+ hidden_states_masks,
462
+ image_rotary_emb=image_rotary_emb,
463
+ )
464
+ hidden_states = gate_msa_i * attn_output_i + hidden_states
465
+
466
+ # 2. Feed-forward
467
+ norm_hidden_states = self.norm3_i(hidden_states).to(dtype=wtype)
468
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp_i) + shift_mlp_i
469
+ ff_output_i = gate_mlp_i * self.ff_i(norm_hidden_states.to(dtype=wtype))
470
+ hidden_states = ff_output_i + hidden_states
471
+ return hidden_states
472
+
473
+
474
+ @maybe_allow_in_graph
475
+ class HiDreamImageTransformerBlock(nn.Module):
476
+ def __init__(
477
+ self,
478
+ dim: int,
479
+ num_attention_heads: int,
480
+ attention_head_dim: int,
481
+ num_routed_experts: int = 4,
482
+ num_activated_experts: int = 2,
483
+ ):
484
+ super().__init__()
485
+ self.num_attention_heads = num_attention_heads
486
+ self.adaLN_modulation = nn.Sequential(nn.SiLU(), nn.Linear(dim, 12 * dim, bias=True))
487
+
488
+ # 1. Attention
489
+ self.norm1_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
490
+ self.norm1_t = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
491
+ self.attn1 = HiDreamAttention(
492
+ query_dim=dim,
493
+ heads=num_attention_heads,
494
+ dim_head=attention_head_dim,
495
+ processor=HiDreamAttnProcessor(),
496
+ single=False,
497
+ )
498
+
499
+ # 3. Feed-forward
500
+ self.norm3_i = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
501
+ if num_routed_experts > 0:
502
+ self.ff_i = MOEFeedForwardSwiGLU(
503
+ dim=dim,
504
+ hidden_dim=4 * dim,
505
+ num_routed_experts=num_routed_experts,
506
+ num_activated_experts=num_activated_experts,
507
+ )
508
+ else:
509
+ self.ff_i = HiDreamImageFeedForwardSwiGLU(dim=dim, hidden_dim=4 * dim)
510
+ self.norm3_t = nn.LayerNorm(dim, eps=1e-06, elementwise_affine=False)
511
+ self.ff_t = HiDreamImageFeedForwardSwiGLU(dim=dim, hidden_dim=4 * dim)
512
+
513
+ def forward(
514
+ self,
515
+ hidden_states: torch.Tensor,
516
+ hidden_states_masks: Optional[torch.Tensor] = None,
517
+ encoder_hidden_states: Optional[torch.Tensor] = None,
518
+ temb: Optional[torch.Tensor] = None,
519
+ image_rotary_emb: torch.Tensor = None,
520
+ ) -> torch.Tensor:
521
+ wtype = hidden_states.dtype
522
+ (
523
+ shift_msa_i,
524
+ scale_msa_i,
525
+ gate_msa_i,
526
+ shift_mlp_i,
527
+ scale_mlp_i,
528
+ gate_mlp_i,
529
+ shift_msa_t,
530
+ scale_msa_t,
531
+ gate_msa_t,
532
+ shift_mlp_t,
533
+ scale_mlp_t,
534
+ gate_mlp_t,
535
+ ) = self.adaLN_modulation(temb)[:, None].chunk(12, dim=-1)
536
+
537
+ # 1. MM-Attention
538
+ norm_hidden_states = self.norm1_i(hidden_states).to(dtype=wtype)
539
+ norm_hidden_states = norm_hidden_states * (1 + scale_msa_i) + shift_msa_i
540
+ norm_encoder_hidden_states = self.norm1_t(encoder_hidden_states).to(dtype=wtype)
541
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + scale_msa_t) + shift_msa_t
542
+
543
+ attn_output_i, attn_output_t = self.attn1(
544
+ norm_hidden_states,
545
+ hidden_states_masks,
546
+ norm_encoder_hidden_states,
547
+ image_rotary_emb=image_rotary_emb,
548
+ )
549
+
550
+ hidden_states = gate_msa_i * attn_output_i + hidden_states
551
+ encoder_hidden_states = gate_msa_t * attn_output_t + encoder_hidden_states
552
+
553
+ # 2. Feed-forward
554
+ norm_hidden_states = self.norm3_i(hidden_states).to(dtype=wtype)
555
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp_i) + shift_mlp_i
556
+ norm_encoder_hidden_states = self.norm3_t(encoder_hidden_states).to(dtype=wtype)
557
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + scale_mlp_t) + shift_mlp_t
558
+
559
+ ff_output_i = gate_mlp_i * self.ff_i(norm_hidden_states)
560
+ ff_output_t = gate_mlp_t * self.ff_t(norm_encoder_hidden_states)
561
+ hidden_states = ff_output_i + hidden_states
562
+ encoder_hidden_states = ff_output_t + encoder_hidden_states
563
+ return hidden_states, encoder_hidden_states
564
+
565
+
566
+ class HiDreamBlock(nn.Module):
567
+ def __init__(self, block: Union[HiDreamImageTransformerBlock, HiDreamImageSingleTransformerBlock]):
568
+ super().__init__()
569
+ self.block = block
570
+
571
+ def forward(
572
+ self,
573
+ hidden_states: torch.Tensor,
574
+ hidden_states_masks: Optional[torch.Tensor] = None,
575
+ encoder_hidden_states: Optional[torch.Tensor] = None,
576
+ temb: Optional[torch.Tensor] = None,
577
+ image_rotary_emb: torch.Tensor = None,
578
+ ) -> torch.Tensor:
579
+ return self.block(
580
+ hidden_states=hidden_states,
581
+ hidden_states_masks=hidden_states_masks,
582
+ encoder_hidden_states=encoder_hidden_states,
583
+ temb=temb,
584
+ image_rotary_emb=image_rotary_emb,
585
+ )
586
+
587
+
588
+ class HiDreamImageTransformer2DModel(ModelMixin, ConfigMixin, PeftAdapterMixin):
589
+ _supports_gradient_checkpointing = True
590
+ _no_split_modules = ["HiDreamImageTransformerBlock", "HiDreamImageSingleTransformerBlock"]
591
+
592
+ @register_to_config
593
+ def __init__(
594
+ self,
595
+ patch_size: Optional[int] = None,
596
+ in_channels: int = 64,
597
+ out_channels: Optional[int] = None,
598
+ num_layers: int = 16,
599
+ num_single_layers: int = 32,
600
+ attention_head_dim: int = 128,
601
+ num_attention_heads: int = 20,
602
+ caption_channels: List[int] = None,
603
+ text_emb_dim: int = 2048,
604
+ num_routed_experts: int = 4,
605
+ num_activated_experts: int = 2,
606
+ axes_dims_rope: Tuple[int, int] = (32, 32),
607
+ max_resolution: Tuple[int, int] = (128, 128),
608
+ llama_layers: List[int] = None,
609
+ ):
610
+ super().__init__()
611
+ self.out_channels = out_channels or in_channels
612
+ self.inner_dim = num_attention_heads * attention_head_dim
613
+
614
+ self.t_embedder = HiDreamImageTimestepEmbed(self.inner_dim)
615
+ self.p_embedder = HiDreamImagePooledEmbed(text_emb_dim, self.inner_dim)
616
+ self.x_embedder = HiDreamImagePatchEmbed(
617
+ patch_size=patch_size,
618
+ in_channels=in_channels,
619
+ out_channels=self.inner_dim,
620
+ )
621
+ self.pe_embedder = HiDreamImageEmbedND(theta=10000, axes_dim=axes_dims_rope)
622
+
623
+ self.double_stream_blocks = nn.ModuleList(
624
+ [
625
+ HiDreamBlock(
626
+ HiDreamImageTransformerBlock(
627
+ dim=self.inner_dim,
628
+ num_attention_heads=num_attention_heads,
629
+ attention_head_dim=attention_head_dim,
630
+ num_routed_experts=num_routed_experts,
631
+ num_activated_experts=num_activated_experts,
632
+ )
633
+ )
634
+ for _ in range(num_layers)
635
+ ]
636
+ )
637
+
638
+ self.single_stream_blocks = nn.ModuleList(
639
+ [
640
+ HiDreamBlock(
641
+ HiDreamImageSingleTransformerBlock(
642
+ dim=self.inner_dim,
643
+ num_attention_heads=num_attention_heads,
644
+ attention_head_dim=attention_head_dim,
645
+ num_routed_experts=num_routed_experts,
646
+ num_activated_experts=num_activated_experts,
647
+ )
648
+ )
649
+ for _ in range(num_single_layers)
650
+ ]
651
+ )
652
+
653
+ self.final_layer = HiDreamImageOutEmbed(self.inner_dim, patch_size, self.out_channels)
654
+
655
+ caption_channels = [caption_channels[1]] * (num_layers + num_single_layers) + [caption_channels[0]]
656
+ caption_projection = []
657
+ for caption_channel in caption_channels:
658
+ caption_projection.append(TextProjection(in_features=caption_channel, hidden_size=self.inner_dim))
659
+ self.caption_projection = nn.ModuleList(caption_projection)
660
+ self.max_seq = max_resolution[0] * max_resolution[1] // (patch_size * patch_size)
661
+
662
+ self.gradient_checkpointing = False
663
+
664
+ def unpatchify(self, x: torch.Tensor, img_sizes: List[Tuple[int, int]], is_training: bool) -> List[torch.Tensor]:
665
+ if is_training:
666
+ B, S, F = x.shape
667
+ C = F // (self.config.patch_size * self.config.patch_size)
668
+ x = (
669
+ x.reshape(B, S, self.config.patch_size, self.config.patch_size, C)
670
+ .permute(0, 4, 1, 2, 3)
671
+ .reshape(B, C, S, self.config.patch_size * self.config.patch_size)
672
+ )
673
+ else:
674
+ x_arr = []
675
+ p1 = self.config.patch_size
676
+ p2 = self.config.patch_size
677
+ for i, img_size in enumerate(img_sizes):
678
+ pH, pW = img_size
679
+ t = x[i, : pH * pW].reshape(1, pH, pW, -1)
680
+ F_token = t.shape[-1]
681
+ C = F_token // (p1 * p2)
682
+ t = t.reshape(1, pH, pW, p1, p2, C)
683
+ t = t.permute(0, 5, 1, 3, 2, 4)
684
+ t = t.reshape(1, C, pH * p1, pW * p2)
685
+ x_arr.append(t)
686
+ x = torch.cat(x_arr, dim=0)
687
+ return x
688
+
689
+ def patchify(self, hidden_states):
690
+ batch_size, channels, height, width = hidden_states.shape
691
+ patch_size = self.config.patch_size
692
+ patch_height, patch_width = height // patch_size, width // patch_size
693
+ device = hidden_states.device
694
+ dtype = hidden_states.dtype
695
+
696
+ # create img_sizes
697
+ img_sizes = torch.tensor([patch_height, patch_width], dtype=torch.int64, device=device).reshape(-1)
698
+ img_sizes = img_sizes.unsqueeze(0).repeat(batch_size, 1)
699
+
700
+ # create hidden_states_masks
701
+ if hidden_states.shape[-2] != hidden_states.shape[-1]:
702
+ hidden_states_masks = torch.zeros((batch_size, self.max_seq), dtype=dtype, device=device)
703
+ hidden_states_masks[:, : patch_height * patch_width] = 1.0
704
+ else:
705
+ hidden_states_masks = None
706
+
707
+ # create img_ids
708
+ img_ids = torch.zeros(patch_height, patch_width, 3, device=device)
709
+ row_indices = torch.arange(patch_height, device=device)[:, None]
710
+ col_indices = torch.arange(patch_width, device=device)[None, :]
711
+ img_ids[..., 1] = img_ids[..., 1] + row_indices
712
+ img_ids[..., 2] = img_ids[..., 2] + col_indices
713
+ img_ids = img_ids.reshape(patch_height * patch_width, -1)
714
+
715
+ if hidden_states.shape[-2] != hidden_states.shape[-1]:
716
+ # Handle non-square latents
717
+ img_ids_pad = torch.zeros(self.max_seq, 3, device=device)
718
+ img_ids_pad[: patch_height * patch_width, :] = img_ids
719
+ img_ids = img_ids_pad.unsqueeze(0).repeat(batch_size, 1, 1)
720
+ else:
721
+ img_ids = img_ids.unsqueeze(0).repeat(batch_size, 1, 1)
722
+
723
+ # patchify hidden_states
724
+ if hidden_states.shape[-2] != hidden_states.shape[-1]:
725
+ # Handle non-square latents
726
+ out = torch.zeros(
727
+ (batch_size, channels, self.max_seq, patch_size * patch_size),
728
+ dtype=dtype,
729
+ device=device,
730
+ )
731
+ hidden_states = hidden_states.reshape(
732
+ batch_size, channels, patch_height, patch_size, patch_width, patch_size
733
+ )
734
+ hidden_states = hidden_states.permute(0, 1, 2, 4, 3, 5)
735
+ hidden_states = hidden_states.reshape(
736
+ batch_size, channels, patch_height * patch_width, patch_size * patch_size
737
+ )
738
+ out[:, :, 0 : patch_height * patch_width] = hidden_states
739
+ hidden_states = out
740
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(
741
+ batch_size, self.max_seq, patch_size * patch_size * channels
742
+ )
743
+
744
+ else:
745
+ # Handle square latents
746
+ hidden_states = hidden_states.reshape(
747
+ batch_size, channels, patch_height, patch_size, patch_width, patch_size
748
+ )
749
+ hidden_states = hidden_states.permute(0, 2, 4, 3, 5, 1)
750
+ hidden_states = hidden_states.reshape(
751
+ batch_size, patch_height * patch_width, patch_size * patch_size * channels
752
+ )
753
+
754
+ return hidden_states, hidden_states_masks, img_sizes, img_ids
755
+
756
+ def forward(
757
+ self,
758
+ hidden_states: torch.Tensor,
759
+ timesteps: torch.LongTensor = None,
760
+ encoder_hidden_states_t5: torch.Tensor = None,
761
+ encoder_hidden_states_llama3: torch.Tensor = None,
762
+ pooled_embeds: torch.Tensor = None,
763
+ img_ids: Optional[torch.Tensor] = None,
764
+ img_sizes: Optional[List[Tuple[int, int]]] = None,
765
+ hidden_states_masks: Optional[torch.Tensor] = None,
766
+ attention_kwargs: Optional[Dict[str, Any]] = None,
767
+ return_dict: bool = True,
768
+ **kwargs,
769
+ ):
770
+ encoder_hidden_states = kwargs.get("encoder_hidden_states", None)
771
+
772
+ if encoder_hidden_states is not None:
773
+ deprecation_message = "The `encoder_hidden_states` argument is deprecated. Please use `encoder_hidden_states_t5` and `encoder_hidden_states_llama3` instead."
774
+ deprecate("encoder_hidden_states", "0.34.0", deprecation_message)
775
+ encoder_hidden_states_t5 = encoder_hidden_states[0]
776
+ encoder_hidden_states_llama3 = encoder_hidden_states[1]
777
+
778
+ if img_ids is not None and img_sizes is not None and hidden_states_masks is None:
779
+ deprecation_message = (
780
+ "Passing `img_ids` and `img_sizes` with unpachified `hidden_states` is deprecated and will be ignored."
781
+ )
782
+ deprecate("img_ids", "0.34.0", deprecation_message)
783
+
784
+ if hidden_states_masks is not None and (img_ids is None or img_sizes is None):
785
+ raise ValueError("if `hidden_states_masks` is passed, `img_ids` and `img_sizes` must also be passed.")
786
+ elif hidden_states_masks is not None and hidden_states.ndim != 3:
787
+ raise ValueError(
788
+ "if `hidden_states_masks` is passed, `hidden_states` must be a 3D tensors with shape (batch_size, patch_height * patch_width, patch_size * patch_size * channels)"
789
+ )
790
+
791
+ if attention_kwargs is not None:
792
+ attention_kwargs = attention_kwargs.copy()
793
+ lora_scale = attention_kwargs.pop("scale", 1.0)
794
+ else:
795
+ lora_scale = 1.0
796
+
797
+ if USE_PEFT_BACKEND:
798
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
799
+ scale_lora_layers(self, lora_scale)
800
+ else:
801
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
802
+ logger.warning(
803
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
804
+ )
805
+
806
+ # spatial forward
807
+ batch_size = hidden_states.shape[0]
808
+ hidden_states_type = hidden_states.dtype
809
+
810
+ # Patchify the input
811
+ if hidden_states_masks is None:
812
+ hidden_states, hidden_states_masks, img_sizes, img_ids = self.patchify(hidden_states)
813
+
814
+ # Embed the hidden states
815
+ hidden_states = self.x_embedder(hidden_states)
816
+
817
+ # 0. time
818
+ timesteps = self.t_embedder(timesteps, hidden_states_type)
819
+ p_embedder = self.p_embedder(pooled_embeds)
820
+ temb = timesteps + p_embedder
821
+
822
+ encoder_hidden_states = [encoder_hidden_states_llama3[k] for k in self.config.llama_layers]
823
+
824
+ if self.caption_projection is not None:
825
+ new_encoder_hidden_states = []
826
+ for i, enc_hidden_state in enumerate(encoder_hidden_states):
827
+ enc_hidden_state = self.caption_projection[i](enc_hidden_state)
828
+ enc_hidden_state = enc_hidden_state.view(batch_size, -1, hidden_states.shape[-1])
829
+ new_encoder_hidden_states.append(enc_hidden_state)
830
+ encoder_hidden_states = new_encoder_hidden_states
831
+ encoder_hidden_states_t5 = self.caption_projection[-1](encoder_hidden_states_t5)
832
+ encoder_hidden_states_t5 = encoder_hidden_states_t5.view(batch_size, -1, hidden_states.shape[-1])
833
+ encoder_hidden_states.append(encoder_hidden_states_t5)
834
+
835
+ txt_ids = torch.zeros(
836
+ batch_size,
837
+ encoder_hidden_states[-1].shape[1]
838
+ + encoder_hidden_states[-2].shape[1]
839
+ + encoder_hidden_states[0].shape[1],
840
+ 3,
841
+ device=img_ids.device,
842
+ dtype=img_ids.dtype,
843
+ )
844
+ ids = torch.cat((img_ids, txt_ids), dim=1)
845
+ image_rotary_emb = self.pe_embedder(ids)
846
+
847
+ # 2. Blocks
848
+ block_id = 0
849
+ initial_encoder_hidden_states = torch.cat([encoder_hidden_states[-1], encoder_hidden_states[-2]], dim=1)
850
+ initial_encoder_hidden_states_seq_len = initial_encoder_hidden_states.shape[1]
851
+ for bid, block in enumerate(self.double_stream_blocks):
852
+ cur_llama31_encoder_hidden_states = encoder_hidden_states[block_id]
853
+ cur_encoder_hidden_states = torch.cat(
854
+ [initial_encoder_hidden_states, cur_llama31_encoder_hidden_states], dim=1
855
+ )
856
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
857
+ hidden_states, initial_encoder_hidden_states = self._gradient_checkpointing_func(
858
+ block,
859
+ hidden_states,
860
+ hidden_states_masks,
861
+ cur_encoder_hidden_states,
862
+ temb,
863
+ image_rotary_emb,
864
+ )
865
+ else:
866
+ hidden_states, initial_encoder_hidden_states = block(
867
+ hidden_states=hidden_states,
868
+ hidden_states_masks=hidden_states_masks,
869
+ encoder_hidden_states=cur_encoder_hidden_states,
870
+ temb=temb,
871
+ image_rotary_emb=image_rotary_emb,
872
+ )
873
+ initial_encoder_hidden_states = initial_encoder_hidden_states[:, :initial_encoder_hidden_states_seq_len]
874
+ block_id += 1
875
+
876
+ image_tokens_seq_len = hidden_states.shape[1]
877
+ hidden_states = torch.cat([hidden_states, initial_encoder_hidden_states], dim=1)
878
+ hidden_states_seq_len = hidden_states.shape[1]
879
+ if hidden_states_masks is not None:
880
+ encoder_attention_mask_ones = torch.ones(
881
+ (batch_size, initial_encoder_hidden_states.shape[1] + cur_llama31_encoder_hidden_states.shape[1]),
882
+ device=hidden_states_masks.device,
883
+ dtype=hidden_states_masks.dtype,
884
+ )
885
+ hidden_states_masks = torch.cat([hidden_states_masks, encoder_attention_mask_ones], dim=1)
886
+
887
+ for bid, block in enumerate(self.single_stream_blocks):
888
+ cur_llama31_encoder_hidden_states = encoder_hidden_states[block_id]
889
+ hidden_states = torch.cat([hidden_states, cur_llama31_encoder_hidden_states], dim=1)
890
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
891
+ hidden_states = self._gradient_checkpointing_func(
892
+ block,
893
+ hidden_states,
894
+ hidden_states_masks,
895
+ None,
896
+ temb,
897
+ image_rotary_emb,
898
+ )
899
+ else:
900
+ hidden_states = block(
901
+ hidden_states=hidden_states,
902
+ hidden_states_masks=hidden_states_masks,
903
+ encoder_hidden_states=None,
904
+ temb=temb,
905
+ image_rotary_emb=image_rotary_emb,
906
+ )
907
+ hidden_states = hidden_states[:, :hidden_states_seq_len]
908
+ block_id += 1
909
+
910
+ hidden_states = hidden_states[:, :image_tokens_seq_len, ...]
911
+ output = self.final_layer(hidden_states, temb)
912
+ output = self.unpatchify(output, img_sizes, self.training)
913
+ if hidden_states_masks is not None:
914
+ hidden_states_masks = hidden_states_masks[:, :image_tokens_seq_len]
915
+
916
+ if USE_PEFT_BACKEND:
917
+ # remove `lora_scale` from each PEFT layer
918
+ unscale_lora_layers(self, lora_scale)
919
+
920
+ if not return_dict:
921
+ return (output,)
922
+ return Transformer2DModelOutput(sample=output)
tasks/tasksmith-f40a643a6ef9/tests/source/src/diffusers/models/transformers/transformer_hunyuan_video.py ADDED
@@ -0,0 +1,1149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2024 The Hunyuan Team and The HuggingFace Team. All rights reserved.
2
+ #
3
+ # Licensed under the Apache License, Version 2.0 (the "License");
4
+ # you may not use this file except in compliance with the License.
5
+ # You may obtain a copy of the License at
6
+ #
7
+ # http://www.apache.org/licenses/LICENSE-2.0
8
+ #
9
+ # Unless required by applicable law or agreed to in writing, software
10
+ # distributed under the License is distributed on an "AS IS" BASIS,
11
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ # See the License for the specific language governing permissions and
13
+ # limitations under the License.
14
+
15
+ from typing import Any, Dict, List, Optional, Tuple, Union
16
+
17
+ import torch
18
+ import torch.nn as nn
19
+ import torch.nn.functional as F
20
+
21
+ from diffusers.loaders import FromOriginalModelMixin
22
+
23
+ from ...configuration_utils import ConfigMixin, register_to_config
24
+ from ...loaders import PeftAdapterMixin
25
+ from ...utils import USE_PEFT_BACKEND, logging, scale_lora_layers, unscale_lora_layers
26
+ from ..attention import FeedForward
27
+ from ..attention_processor import Attention, AttentionProcessor
28
+ from ..cache_utils import CacheMixin
29
+ from ..embeddings import (
30
+ CombinedTimestepTextProjEmbeddings,
31
+ PixArtAlphaTextProjection,
32
+ TimestepEmbedding,
33
+ Timesteps,
34
+ get_1d_rotary_pos_embed,
35
+ )
36
+ from ..modeling_outputs import Transformer2DModelOutput
37
+ from ..modeling_utils import ModelMixin
38
+ from ..normalization import AdaLayerNormContinuous, AdaLayerNormZero, AdaLayerNormZeroSingle, FP32LayerNorm
39
+
40
+
41
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
42
+
43
+
44
+ class HunyuanVideoAttnProcessor2_0:
45
+ def __init__(self):
46
+ if not hasattr(F, "scaled_dot_product_attention"):
47
+ raise ImportError(
48
+ "HunyuanVideoAttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0."
49
+ )
50
+
51
+ def __call__(
52
+ self,
53
+ attn: Attention,
54
+ hidden_states: torch.Tensor,
55
+ encoder_hidden_states: Optional[torch.Tensor] = None,
56
+ attention_mask: Optional[torch.Tensor] = None,
57
+ image_rotary_emb: Optional[torch.Tensor] = None,
58
+ ) -> torch.Tensor:
59
+ if attn.add_q_proj is None and encoder_hidden_states is not None:
60
+ hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
61
+
62
+ # 1. QKV projections
63
+ query = attn.to_q(hidden_states)
64
+ key = attn.to_k(hidden_states)
65
+ value = attn.to_v(hidden_states)
66
+
67
+ query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
68
+ key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
69
+ value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
70
+
71
+ # 2. QK normalization
72
+ if attn.norm_q is not None:
73
+ query = attn.norm_q(query)
74
+ if attn.norm_k is not None:
75
+ key = attn.norm_k(key)
76
+
77
+ # 3. Rotational positional embeddings applied to latent stream
78
+ if image_rotary_emb is not None:
79
+ from ..embeddings import apply_rotary_emb
80
+
81
+ if attn.add_q_proj is None and encoder_hidden_states is not None:
82
+ query = torch.cat(
83
+ [
84
+ apply_rotary_emb(query[:, :, : -encoder_hidden_states.shape[1]], image_rotary_emb),
85
+ query[:, :, -encoder_hidden_states.shape[1] :],
86
+ ],
87
+ dim=2,
88
+ )
89
+ key = torch.cat(
90
+ [
91
+ apply_rotary_emb(key[:, :, : -encoder_hidden_states.shape[1]], image_rotary_emb),
92
+ key[:, :, -encoder_hidden_states.shape[1] :],
93
+ ],
94
+ dim=2,
95
+ )
96
+ else:
97
+ query = apply_rotary_emb(query, image_rotary_emb)
98
+ key = apply_rotary_emb(key, image_rotary_emb)
99
+
100
+ # 4. Encoder condition QKV projection and normalization
101
+ if attn.add_q_proj is not None and encoder_hidden_states is not None:
102
+ encoder_query = attn.add_q_proj(encoder_hidden_states)
103
+ encoder_key = attn.add_k_proj(encoder_hidden_states)
104
+ encoder_value = attn.add_v_proj(encoder_hidden_states)
105
+
106
+ encoder_query = encoder_query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
107
+ encoder_key = encoder_key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
108
+ encoder_value = encoder_value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
109
+
110
+ if attn.norm_added_q is not None:
111
+ encoder_query = attn.norm_added_q(encoder_query)
112
+ if attn.norm_added_k is not None:
113
+ encoder_key = attn.norm_added_k(encoder_key)
114
+
115
+ query = torch.cat([query, encoder_query], dim=2)
116
+ key = torch.cat([key, encoder_key], dim=2)
117
+ value = torch.cat([value, encoder_value], dim=2)
118
+
119
+ # 5. Attention
120
+ hidden_states = F.scaled_dot_product_attention(
121
+ query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
122
+ )
123
+ hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
124
+ hidden_states = hidden_states.to(query.dtype)
125
+
126
+ # 6. Output projection
127
+ if encoder_hidden_states is not None:
128
+ hidden_states, encoder_hidden_states = (
129
+ hidden_states[:, : -encoder_hidden_states.shape[1]],
130
+ hidden_states[:, -encoder_hidden_states.shape[1] :],
131
+ )
132
+
133
+ if getattr(attn, "to_out", None) is not None:
134
+ hidden_states = attn.to_out[0](hidden_states)
135
+ hidden_states = attn.to_out[1](hidden_states)
136
+
137
+ if getattr(attn, "to_add_out", None) is not None:
138
+ encoder_hidden_states = attn.to_add_out(encoder_hidden_states)
139
+
140
+ return hidden_states, encoder_hidden_states
141
+
142
+
143
+ class HunyuanVideoPatchEmbed(nn.Module):
144
+ def __init__(
145
+ self,
146
+ patch_size: Union[int, Tuple[int, int, int]] = 16,
147
+ in_chans: int = 3,
148
+ embed_dim: int = 768,
149
+ ) -> None:
150
+ super().__init__()
151
+
152
+ patch_size = (patch_size, patch_size, patch_size) if isinstance(patch_size, int) else patch_size
153
+ self.proj = nn.Conv3d(in_chans, embed_dim, kernel_size=patch_size, stride=patch_size)
154
+
155
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
156
+ hidden_states = self.proj(hidden_states)
157
+ hidden_states = hidden_states.flatten(2).transpose(1, 2) # BCFHW -> BNC
158
+ return hidden_states
159
+
160
+
161
+ class HunyuanVideoAdaNorm(nn.Module):
162
+ def __init__(self, in_features: int, out_features: Optional[int] = None) -> None:
163
+ super().__init__()
164
+
165
+ out_features = out_features or 2 * in_features
166
+ self.linear = nn.Linear(in_features, out_features)
167
+ self.nonlinearity = nn.SiLU()
168
+
169
+ def forward(
170
+ self, temb: torch.Tensor
171
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
172
+ temb = self.linear(self.nonlinearity(temb))
173
+ gate_msa, gate_mlp = temb.chunk(2, dim=1)
174
+ gate_msa, gate_mlp = gate_msa.unsqueeze(1), gate_mlp.unsqueeze(1)
175
+ return gate_msa, gate_mlp
176
+
177
+
178
+ class HunyuanVideoTokenReplaceAdaLayerNormZero(nn.Module):
179
+ def __init__(self, embedding_dim: int, norm_type: str = "layer_norm", bias: bool = True):
180
+ super().__init__()
181
+
182
+ self.silu = nn.SiLU()
183
+ self.linear = nn.Linear(embedding_dim, 6 * embedding_dim, bias=bias)
184
+
185
+ if norm_type == "layer_norm":
186
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
187
+ elif norm_type == "fp32_layer_norm":
188
+ self.norm = FP32LayerNorm(embedding_dim, elementwise_affine=False, bias=False)
189
+ else:
190
+ raise ValueError(
191
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
192
+ )
193
+
194
+ def forward(
195
+ self,
196
+ hidden_states: torch.Tensor,
197
+ emb: torch.Tensor,
198
+ token_replace_emb: torch.Tensor,
199
+ first_frame_num_tokens: int,
200
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
201
+ emb = self.linear(self.silu(emb))
202
+ token_replace_emb = self.linear(self.silu(token_replace_emb))
203
+
204
+ shift_msa, scale_msa, gate_msa, shift_mlp, scale_mlp, gate_mlp = emb.chunk(6, dim=1)
205
+ tr_shift_msa, tr_scale_msa, tr_gate_msa, tr_shift_mlp, tr_scale_mlp, tr_gate_mlp = token_replace_emb.chunk(
206
+ 6, dim=1
207
+ )
208
+
209
+ norm_hidden_states = self.norm(hidden_states)
210
+ hidden_states_zero = (
211
+ norm_hidden_states[:, :first_frame_num_tokens] * (1 + tr_scale_msa[:, None]) + tr_shift_msa[:, None]
212
+ )
213
+ hidden_states_orig = (
214
+ norm_hidden_states[:, first_frame_num_tokens:] * (1 + scale_msa[:, None]) + shift_msa[:, None]
215
+ )
216
+ hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
217
+
218
+ return (
219
+ hidden_states,
220
+ gate_msa,
221
+ shift_mlp,
222
+ scale_mlp,
223
+ gate_mlp,
224
+ tr_gate_msa,
225
+ tr_shift_mlp,
226
+ tr_scale_mlp,
227
+ tr_gate_mlp,
228
+ )
229
+
230
+
231
+ class HunyuanVideoTokenReplaceAdaLayerNormZeroSingle(nn.Module):
232
+ def __init__(self, embedding_dim: int, norm_type: str = "layer_norm", bias: bool = True):
233
+ super().__init__()
234
+
235
+ self.silu = nn.SiLU()
236
+ self.linear = nn.Linear(embedding_dim, 3 * embedding_dim, bias=bias)
237
+
238
+ if norm_type == "layer_norm":
239
+ self.norm = nn.LayerNorm(embedding_dim, elementwise_affine=False, eps=1e-6)
240
+ else:
241
+ raise ValueError(
242
+ f"Unsupported `norm_type` ({norm_type}) provided. Supported ones are: 'layer_norm', 'fp32_layer_norm'."
243
+ )
244
+
245
+ def forward(
246
+ self,
247
+ hidden_states: torch.Tensor,
248
+ emb: torch.Tensor,
249
+ token_replace_emb: torch.Tensor,
250
+ first_frame_num_tokens: int,
251
+ ) -> Tuple[torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor, torch.Tensor]:
252
+ emb = self.linear(self.silu(emb))
253
+ token_replace_emb = self.linear(self.silu(token_replace_emb))
254
+
255
+ shift_msa, scale_msa, gate_msa = emb.chunk(3, dim=1)
256
+ tr_shift_msa, tr_scale_msa, tr_gate_msa = token_replace_emb.chunk(3, dim=1)
257
+
258
+ norm_hidden_states = self.norm(hidden_states)
259
+ hidden_states_zero = (
260
+ norm_hidden_states[:, :first_frame_num_tokens] * (1 + tr_scale_msa[:, None]) + tr_shift_msa[:, None]
261
+ )
262
+ hidden_states_orig = (
263
+ norm_hidden_states[:, first_frame_num_tokens:] * (1 + scale_msa[:, None]) + shift_msa[:, None]
264
+ )
265
+ hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
266
+
267
+ return hidden_states, gate_msa, tr_gate_msa
268
+
269
+
270
+ class HunyuanVideoConditionEmbedding(nn.Module):
271
+ def __init__(
272
+ self,
273
+ embedding_dim: int,
274
+ pooled_projection_dim: int,
275
+ guidance_embeds: bool,
276
+ image_condition_type: Optional[str] = None,
277
+ ):
278
+ super().__init__()
279
+
280
+ self.image_condition_type = image_condition_type
281
+
282
+ self.time_proj = Timesteps(num_channels=256, flip_sin_to_cos=True, downscale_freq_shift=0)
283
+ self.timestep_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
284
+ self.text_embedder = PixArtAlphaTextProjection(pooled_projection_dim, embedding_dim, act_fn="silu")
285
+
286
+ self.guidance_embedder = None
287
+ if guidance_embeds:
288
+ self.guidance_embedder = TimestepEmbedding(in_channels=256, time_embed_dim=embedding_dim)
289
+
290
+ def forward(
291
+ self, timestep: torch.Tensor, pooled_projection: torch.Tensor, guidance: Optional[torch.Tensor] = None
292
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
293
+ timesteps_proj = self.time_proj(timestep)
294
+ timesteps_emb = self.timestep_embedder(timesteps_proj.to(dtype=pooled_projection.dtype)) # (N, D)
295
+ pooled_projections = self.text_embedder(pooled_projection)
296
+ conditioning = timesteps_emb + pooled_projections
297
+
298
+ token_replace_emb = None
299
+ if self.image_condition_type == "token_replace":
300
+ token_replace_timestep = torch.zeros_like(timestep)
301
+ token_replace_proj = self.time_proj(token_replace_timestep)
302
+ token_replace_emb = self.timestep_embedder(token_replace_proj.to(dtype=pooled_projection.dtype))
303
+ token_replace_emb = token_replace_emb + pooled_projections
304
+
305
+ if self.guidance_embedder is not None:
306
+ guidance_proj = self.time_proj(guidance)
307
+ guidance_emb = self.guidance_embedder(guidance_proj.to(dtype=pooled_projection.dtype))
308
+ conditioning = conditioning + guidance_emb
309
+
310
+ return conditioning, token_replace_emb
311
+
312
+
313
+ class HunyuanVideoIndividualTokenRefinerBlock(nn.Module):
314
+ def __init__(
315
+ self,
316
+ num_attention_heads: int,
317
+ attention_head_dim: int,
318
+ mlp_width_ratio: str = 4.0,
319
+ mlp_drop_rate: float = 0.0,
320
+ attention_bias: bool = True,
321
+ ) -> None:
322
+ super().__init__()
323
+
324
+ hidden_size = num_attention_heads * attention_head_dim
325
+
326
+ self.norm1 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
327
+ self.attn = Attention(
328
+ query_dim=hidden_size,
329
+ cross_attention_dim=None,
330
+ heads=num_attention_heads,
331
+ dim_head=attention_head_dim,
332
+ bias=attention_bias,
333
+ )
334
+
335
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=True, eps=1e-6)
336
+ self.ff = FeedForward(hidden_size, mult=mlp_width_ratio, activation_fn="linear-silu", dropout=mlp_drop_rate)
337
+
338
+ self.norm_out = HunyuanVideoAdaNorm(hidden_size, 2 * hidden_size)
339
+
340
+ def forward(
341
+ self,
342
+ hidden_states: torch.Tensor,
343
+ temb: torch.Tensor,
344
+ attention_mask: Optional[torch.Tensor] = None,
345
+ ) -> torch.Tensor:
346
+ norm_hidden_states = self.norm1(hidden_states)
347
+
348
+ attn_output = self.attn(
349
+ hidden_states=norm_hidden_states,
350
+ encoder_hidden_states=None,
351
+ attention_mask=attention_mask,
352
+ )
353
+
354
+ gate_msa, gate_mlp = self.norm_out(temb)
355
+ hidden_states = hidden_states + attn_output * gate_msa
356
+
357
+ ff_output = self.ff(self.norm2(hidden_states))
358
+ hidden_states = hidden_states + ff_output * gate_mlp
359
+
360
+ return hidden_states
361
+
362
+
363
+ class HunyuanVideoIndividualTokenRefiner(nn.Module):
364
+ def __init__(
365
+ self,
366
+ num_attention_heads: int,
367
+ attention_head_dim: int,
368
+ num_layers: int,
369
+ mlp_width_ratio: float = 4.0,
370
+ mlp_drop_rate: float = 0.0,
371
+ attention_bias: bool = True,
372
+ ) -> None:
373
+ super().__init__()
374
+
375
+ self.refiner_blocks = nn.ModuleList(
376
+ [
377
+ HunyuanVideoIndividualTokenRefinerBlock(
378
+ num_attention_heads=num_attention_heads,
379
+ attention_head_dim=attention_head_dim,
380
+ mlp_width_ratio=mlp_width_ratio,
381
+ mlp_drop_rate=mlp_drop_rate,
382
+ attention_bias=attention_bias,
383
+ )
384
+ for _ in range(num_layers)
385
+ ]
386
+ )
387
+
388
+ def forward(
389
+ self,
390
+ hidden_states: torch.Tensor,
391
+ temb: torch.Tensor,
392
+ attention_mask: Optional[torch.Tensor] = None,
393
+ ) -> None:
394
+ self_attn_mask = None
395
+ if attention_mask is not None:
396
+ batch_size = attention_mask.shape[0]
397
+ seq_len = attention_mask.shape[1]
398
+ attention_mask = attention_mask.to(hidden_states.device).bool()
399
+ self_attn_mask_1 = attention_mask.view(batch_size, 1, 1, seq_len).repeat(1, 1, seq_len, 1)
400
+ self_attn_mask_2 = self_attn_mask_1.transpose(2, 3)
401
+ self_attn_mask = (self_attn_mask_1 & self_attn_mask_2).bool()
402
+ self_attn_mask[:, :, :, 0] = True
403
+
404
+ for block in self.refiner_blocks:
405
+ hidden_states = block(hidden_states, temb, self_attn_mask)
406
+
407
+ return hidden_states
408
+
409
+
410
+ class HunyuanVideoTokenRefiner(nn.Module):
411
+ def __init__(
412
+ self,
413
+ in_channels: int,
414
+ num_attention_heads: int,
415
+ attention_head_dim: int,
416
+ num_layers: int,
417
+ mlp_ratio: float = 4.0,
418
+ mlp_drop_rate: float = 0.0,
419
+ attention_bias: bool = True,
420
+ ) -> None:
421
+ super().__init__()
422
+
423
+ hidden_size = num_attention_heads * attention_head_dim
424
+
425
+ self.time_text_embed = CombinedTimestepTextProjEmbeddings(
426
+ embedding_dim=hidden_size, pooled_projection_dim=in_channels
427
+ )
428
+ self.proj_in = nn.Linear(in_channels, hidden_size, bias=True)
429
+ self.token_refiner = HunyuanVideoIndividualTokenRefiner(
430
+ num_attention_heads=num_attention_heads,
431
+ attention_head_dim=attention_head_dim,
432
+ num_layers=num_layers,
433
+ mlp_width_ratio=mlp_ratio,
434
+ mlp_drop_rate=mlp_drop_rate,
435
+ attention_bias=attention_bias,
436
+ )
437
+
438
+ def forward(
439
+ self,
440
+ hidden_states: torch.Tensor,
441
+ timestep: torch.LongTensor,
442
+ attention_mask: Optional[torch.LongTensor] = None,
443
+ ) -> torch.Tensor:
444
+ if attention_mask is None:
445
+ pooled_projections = hidden_states.mean(dim=1)
446
+ else:
447
+ original_dtype = hidden_states.dtype
448
+ mask_float = attention_mask.float().unsqueeze(-1)
449
+ pooled_projections = (hidden_states * mask_float).sum(dim=1) / mask_float.sum(dim=1)
450
+ pooled_projections = pooled_projections.to(original_dtype)
451
+
452
+ temb = self.time_text_embed(timestep, pooled_projections)
453
+ hidden_states = self.proj_in(hidden_states)
454
+ hidden_states = self.token_refiner(hidden_states, temb, attention_mask)
455
+
456
+ return hidden_states
457
+
458
+
459
+ class HunyuanVideoRotaryPosEmbed(nn.Module):
460
+ def __init__(self, patch_size: int, patch_size_t: int, rope_dim: List[int], theta: float = 256.0) -> None:
461
+ super().__init__()
462
+
463
+ self.patch_size = patch_size
464
+ self.patch_size_t = patch_size_t
465
+ self.rope_dim = rope_dim
466
+ self.theta = theta
467
+
468
+ def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
469
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
470
+ rope_sizes = [num_frames // self.patch_size_t, height // self.patch_size, width // self.patch_size]
471
+
472
+ axes_grids = []
473
+ for i in range(3):
474
+ # Note: The following line diverges from original behaviour. We create the grid on the device, whereas
475
+ # original implementation creates it on CPU and then moves it to device. This results in numerical
476
+ # differences in layerwise debugging outputs, but visually it is the same.
477
+ grid = torch.arange(0, rope_sizes[i], device=hidden_states.device, dtype=torch.float32)
478
+ axes_grids.append(grid)
479
+ grid = torch.meshgrid(*axes_grids, indexing="ij") # [W, H, T]
480
+ grid = torch.stack(grid, dim=0) # [3, W, H, T]
481
+
482
+ freqs = []
483
+ for i in range(3):
484
+ freq = get_1d_rotary_pos_embed(self.rope_dim[i], grid[i].reshape(-1), self.theta, use_real=True)
485
+ freqs.append(freq)
486
+
487
+ freqs_cos = torch.cat([f[0] for f in freqs], dim=1) # (W * H * T, D / 2)
488
+ freqs_sin = torch.cat([f[1] for f in freqs], dim=1) # (W * H * T, D / 2)
489
+ return freqs_cos, freqs_sin
490
+
491
+
492
+ class HunyuanVideoSingleTransformerBlock(nn.Module):
493
+ def __init__(
494
+ self,
495
+ num_attention_heads: int,
496
+ attention_head_dim: int,
497
+ mlp_ratio: float = 4.0,
498
+ qk_norm: str = "rms_norm",
499
+ ) -> None:
500
+ super().__init__()
501
+
502
+ hidden_size = num_attention_heads * attention_head_dim
503
+ mlp_dim = int(hidden_size * mlp_ratio)
504
+
505
+ self.attn = Attention(
506
+ query_dim=hidden_size,
507
+ cross_attention_dim=None,
508
+ dim_head=attention_head_dim,
509
+ heads=num_attention_heads,
510
+ out_dim=hidden_size,
511
+ bias=True,
512
+ processor=HunyuanVideoAttnProcessor2_0(),
513
+ qk_norm=qk_norm,
514
+ eps=1e-6,
515
+ pre_only=True,
516
+ )
517
+
518
+ self.norm = AdaLayerNormZeroSingle(hidden_size, norm_type="layer_norm")
519
+ self.proj_mlp = nn.Linear(hidden_size, mlp_dim)
520
+ self.act_mlp = nn.GELU(approximate="tanh")
521
+ self.proj_out = nn.Linear(hidden_size + mlp_dim, hidden_size)
522
+
523
+ def forward(
524
+ self,
525
+ hidden_states: torch.Tensor,
526
+ encoder_hidden_states: torch.Tensor,
527
+ temb: torch.Tensor,
528
+ attention_mask: Optional[torch.Tensor] = None,
529
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
530
+ *args,
531
+ **kwargs,
532
+ ) -> torch.Tensor:
533
+ text_seq_length = encoder_hidden_states.shape[1]
534
+ hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
535
+
536
+ residual = hidden_states
537
+
538
+ # 1. Input normalization
539
+ norm_hidden_states, gate = self.norm(hidden_states, emb=temb)
540
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
541
+
542
+ norm_hidden_states, norm_encoder_hidden_states = (
543
+ norm_hidden_states[:, :-text_seq_length, :],
544
+ norm_hidden_states[:, -text_seq_length:, :],
545
+ )
546
+
547
+ # 2. Attention
548
+ attn_output, context_attn_output = self.attn(
549
+ hidden_states=norm_hidden_states,
550
+ encoder_hidden_states=norm_encoder_hidden_states,
551
+ attention_mask=attention_mask,
552
+ image_rotary_emb=image_rotary_emb,
553
+ )
554
+ attn_output = torch.cat([attn_output, context_attn_output], dim=1)
555
+
556
+ # 3. Modulation and residual connection
557
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
558
+ hidden_states = gate.unsqueeze(1) * self.proj_out(hidden_states)
559
+ hidden_states = hidden_states + residual
560
+
561
+ hidden_states, encoder_hidden_states = (
562
+ hidden_states[:, :-text_seq_length, :],
563
+ hidden_states[:, -text_seq_length:, :],
564
+ )
565
+ return hidden_states, encoder_hidden_states
566
+
567
+
568
+ class HunyuanVideoTransformerBlock(nn.Module):
569
+ def __init__(
570
+ self,
571
+ num_attention_heads: int,
572
+ attention_head_dim: int,
573
+ mlp_ratio: float,
574
+ qk_norm: str = "rms_norm",
575
+ ) -> None:
576
+ super().__init__()
577
+
578
+ hidden_size = num_attention_heads * attention_head_dim
579
+
580
+ self.norm1 = AdaLayerNormZero(hidden_size, norm_type="layer_norm")
581
+ self.norm1_context = AdaLayerNormZero(hidden_size, norm_type="layer_norm")
582
+
583
+ self.attn = Attention(
584
+ query_dim=hidden_size,
585
+ cross_attention_dim=None,
586
+ added_kv_proj_dim=hidden_size,
587
+ dim_head=attention_head_dim,
588
+ heads=num_attention_heads,
589
+ out_dim=hidden_size,
590
+ context_pre_only=False,
591
+ bias=True,
592
+ processor=HunyuanVideoAttnProcessor2_0(),
593
+ qk_norm=qk_norm,
594
+ eps=1e-6,
595
+ )
596
+
597
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
598
+ self.ff = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
599
+
600
+ self.norm2_context = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
601
+ self.ff_context = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
602
+
603
+ def forward(
604
+ self,
605
+ hidden_states: torch.Tensor,
606
+ encoder_hidden_states: torch.Tensor,
607
+ temb: torch.Tensor,
608
+ attention_mask: Optional[torch.Tensor] = None,
609
+ freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
610
+ *args,
611
+ **kwargs,
612
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
613
+ # 1. Input normalization
614
+ norm_hidden_states, gate_msa, shift_mlp, scale_mlp, gate_mlp = self.norm1(hidden_states, emb=temb)
615
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
616
+ encoder_hidden_states, emb=temb
617
+ )
618
+
619
+ # 2. Joint attention
620
+ attn_output, context_attn_output = self.attn(
621
+ hidden_states=norm_hidden_states,
622
+ encoder_hidden_states=norm_encoder_hidden_states,
623
+ attention_mask=attention_mask,
624
+ image_rotary_emb=freqs_cis,
625
+ )
626
+
627
+ # 3. Modulation and residual connection
628
+ hidden_states = hidden_states + attn_output * gate_msa.unsqueeze(1)
629
+ encoder_hidden_states = encoder_hidden_states + context_attn_output * c_gate_msa.unsqueeze(1)
630
+
631
+ norm_hidden_states = self.norm2(hidden_states)
632
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
633
+
634
+ norm_hidden_states = norm_hidden_states * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
635
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
636
+
637
+ # 4. Feed-forward
638
+ ff_output = self.ff(norm_hidden_states)
639
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
640
+
641
+ hidden_states = hidden_states + gate_mlp.unsqueeze(1) * ff_output
642
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
643
+
644
+ return hidden_states, encoder_hidden_states
645
+
646
+
647
+ class HunyuanVideoTokenReplaceSingleTransformerBlock(nn.Module):
648
+ def __init__(
649
+ self,
650
+ num_attention_heads: int,
651
+ attention_head_dim: int,
652
+ mlp_ratio: float = 4.0,
653
+ qk_norm: str = "rms_norm",
654
+ ) -> None:
655
+ super().__init__()
656
+
657
+ hidden_size = num_attention_heads * attention_head_dim
658
+ mlp_dim = int(hidden_size * mlp_ratio)
659
+
660
+ self.attn = Attention(
661
+ query_dim=hidden_size,
662
+ cross_attention_dim=None,
663
+ dim_head=attention_head_dim,
664
+ heads=num_attention_heads,
665
+ out_dim=hidden_size,
666
+ bias=True,
667
+ processor=HunyuanVideoAttnProcessor2_0(),
668
+ qk_norm=qk_norm,
669
+ eps=1e-6,
670
+ pre_only=True,
671
+ )
672
+
673
+ self.norm = HunyuanVideoTokenReplaceAdaLayerNormZeroSingle(hidden_size, norm_type="layer_norm")
674
+ self.proj_mlp = nn.Linear(hidden_size, mlp_dim)
675
+ self.act_mlp = nn.GELU(approximate="tanh")
676
+ self.proj_out = nn.Linear(hidden_size + mlp_dim, hidden_size)
677
+
678
+ def forward(
679
+ self,
680
+ hidden_states: torch.Tensor,
681
+ encoder_hidden_states: torch.Tensor,
682
+ temb: torch.Tensor,
683
+ attention_mask: Optional[torch.Tensor] = None,
684
+ image_rotary_emb: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
685
+ token_replace_emb: torch.Tensor = None,
686
+ num_tokens: int = None,
687
+ ) -> torch.Tensor:
688
+ text_seq_length = encoder_hidden_states.shape[1]
689
+ hidden_states = torch.cat([hidden_states, encoder_hidden_states], dim=1)
690
+
691
+ residual = hidden_states
692
+
693
+ # 1. Input normalization
694
+ norm_hidden_states, gate, tr_gate = self.norm(hidden_states, temb, token_replace_emb, num_tokens)
695
+ mlp_hidden_states = self.act_mlp(self.proj_mlp(norm_hidden_states))
696
+
697
+ norm_hidden_states, norm_encoder_hidden_states = (
698
+ norm_hidden_states[:, :-text_seq_length, :],
699
+ norm_hidden_states[:, -text_seq_length:, :],
700
+ )
701
+
702
+ # 2. Attention
703
+ attn_output, context_attn_output = self.attn(
704
+ hidden_states=norm_hidden_states,
705
+ encoder_hidden_states=norm_encoder_hidden_states,
706
+ attention_mask=attention_mask,
707
+ image_rotary_emb=image_rotary_emb,
708
+ )
709
+ attn_output = torch.cat([attn_output, context_attn_output], dim=1)
710
+
711
+ # 3. Modulation and residual connection
712
+ hidden_states = torch.cat([attn_output, mlp_hidden_states], dim=2)
713
+
714
+ proj_output = self.proj_out(hidden_states)
715
+ hidden_states_zero = proj_output[:, :num_tokens] * tr_gate.unsqueeze(1)
716
+ hidden_states_orig = proj_output[:, num_tokens:] * gate.unsqueeze(1)
717
+ hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
718
+ hidden_states = hidden_states + residual
719
+
720
+ hidden_states, encoder_hidden_states = (
721
+ hidden_states[:, :-text_seq_length, :],
722
+ hidden_states[:, -text_seq_length:, :],
723
+ )
724
+ return hidden_states, encoder_hidden_states
725
+
726
+
727
+ class HunyuanVideoTokenReplaceTransformerBlock(nn.Module):
728
+ def __init__(
729
+ self,
730
+ num_attention_heads: int,
731
+ attention_head_dim: int,
732
+ mlp_ratio: float,
733
+ qk_norm: str = "rms_norm",
734
+ ) -> None:
735
+ super().__init__()
736
+
737
+ hidden_size = num_attention_heads * attention_head_dim
738
+
739
+ self.norm1 = HunyuanVideoTokenReplaceAdaLayerNormZero(hidden_size, norm_type="layer_norm")
740
+ self.norm1_context = AdaLayerNormZero(hidden_size, norm_type="layer_norm")
741
+
742
+ self.attn = Attention(
743
+ query_dim=hidden_size,
744
+ cross_attention_dim=None,
745
+ added_kv_proj_dim=hidden_size,
746
+ dim_head=attention_head_dim,
747
+ heads=num_attention_heads,
748
+ out_dim=hidden_size,
749
+ context_pre_only=False,
750
+ bias=True,
751
+ processor=HunyuanVideoAttnProcessor2_0(),
752
+ qk_norm=qk_norm,
753
+ eps=1e-6,
754
+ )
755
+
756
+ self.norm2 = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
757
+ self.ff = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
758
+
759
+ self.norm2_context = nn.LayerNorm(hidden_size, elementwise_affine=False, eps=1e-6)
760
+ self.ff_context = FeedForward(hidden_size, mult=mlp_ratio, activation_fn="gelu-approximate")
761
+
762
+ def forward(
763
+ self,
764
+ hidden_states: torch.Tensor,
765
+ encoder_hidden_states: torch.Tensor,
766
+ temb: torch.Tensor,
767
+ attention_mask: Optional[torch.Tensor] = None,
768
+ freqs_cis: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
769
+ token_replace_emb: torch.Tensor = None,
770
+ num_tokens: int = None,
771
+ ) -> Tuple[torch.Tensor, torch.Tensor]:
772
+ # 1. Input normalization
773
+ (
774
+ norm_hidden_states,
775
+ gate_msa,
776
+ shift_mlp,
777
+ scale_mlp,
778
+ gate_mlp,
779
+ tr_gate_msa,
780
+ tr_shift_mlp,
781
+ tr_scale_mlp,
782
+ tr_gate_mlp,
783
+ ) = self.norm1(hidden_states, temb, token_replace_emb, num_tokens)
784
+ norm_encoder_hidden_states, c_gate_msa, c_shift_mlp, c_scale_mlp, c_gate_mlp = self.norm1_context(
785
+ encoder_hidden_states, emb=temb
786
+ )
787
+
788
+ # 2. Joint attention
789
+ attn_output, context_attn_output = self.attn(
790
+ hidden_states=norm_hidden_states,
791
+ encoder_hidden_states=norm_encoder_hidden_states,
792
+ attention_mask=attention_mask,
793
+ image_rotary_emb=freqs_cis,
794
+ )
795
+
796
+ # 3. Modulation and residual connection
797
+ hidden_states_zero = hidden_states[:, :num_tokens] + attn_output[:, :num_tokens] * tr_gate_msa.unsqueeze(1)
798
+ hidden_states_orig = hidden_states[:, num_tokens:] + attn_output[:, num_tokens:] * gate_msa.unsqueeze(1)
799
+ hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
800
+ encoder_hidden_states = encoder_hidden_states + context_attn_output * c_gate_msa.unsqueeze(1)
801
+
802
+ norm_hidden_states = self.norm2(hidden_states)
803
+ norm_encoder_hidden_states = self.norm2_context(encoder_hidden_states)
804
+
805
+ hidden_states_zero = norm_hidden_states[:, :num_tokens] * (1 + tr_scale_mlp[:, None]) + tr_shift_mlp[:, None]
806
+ hidden_states_orig = norm_hidden_states[:, num_tokens:] * (1 + scale_mlp[:, None]) + shift_mlp[:, None]
807
+ norm_hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
808
+ norm_encoder_hidden_states = norm_encoder_hidden_states * (1 + c_scale_mlp[:, None]) + c_shift_mlp[:, None]
809
+
810
+ # 4. Feed-forward
811
+ ff_output = self.ff(norm_hidden_states)
812
+ context_ff_output = self.ff_context(norm_encoder_hidden_states)
813
+
814
+ hidden_states_zero = hidden_states[:, :num_tokens] + ff_output[:, :num_tokens] * tr_gate_mlp.unsqueeze(1)
815
+ hidden_states_orig = hidden_states[:, num_tokens:] + ff_output[:, num_tokens:] * gate_mlp.unsqueeze(1)
816
+ hidden_states = torch.cat([hidden_states_zero, hidden_states_orig], dim=1)
817
+ encoder_hidden_states = encoder_hidden_states + c_gate_mlp.unsqueeze(1) * context_ff_output
818
+
819
+ return hidden_states, encoder_hidden_states
820
+
821
+
822
+ class HunyuanVideoTransformer3DModel(ModelMixin, ConfigMixin, PeftAdapterMixin, FromOriginalModelMixin, CacheMixin):
823
+ r"""
824
+ A Transformer model for video-like data used in [HunyuanVideo](https://huggingface.co/tencent/HunyuanVideo).
825
+
826
+ Args:
827
+ in_channels (`int`, defaults to `16`):
828
+ The number of channels in the input.
829
+ out_channels (`int`, defaults to `16`):
830
+ The number of channels in the output.
831
+ num_attention_heads (`int`, defaults to `24`):
832
+ The number of heads to use for multi-head attention.
833
+ attention_head_dim (`int`, defaults to `128`):
834
+ The number of channels in each head.
835
+ num_layers (`int`, defaults to `20`):
836
+ The number of layers of dual-stream blocks to use.
837
+ num_single_layers (`int`, defaults to `40`):
838
+ The number of layers of single-stream blocks to use.
839
+ num_refiner_layers (`int`, defaults to `2`):
840
+ The number of layers of refiner blocks to use.
841
+ mlp_ratio (`float`, defaults to `4.0`):
842
+ The ratio of the hidden layer size to the input size in the feedforward network.
843
+ patch_size (`int`, defaults to `2`):
844
+ The size of the spatial patches to use in the patch embedding layer.
845
+ patch_size_t (`int`, defaults to `1`):
846
+ The size of the tmeporal patches to use in the patch embedding layer.
847
+ qk_norm (`str`, defaults to `rms_norm`):
848
+ The normalization to use for the query and key projections in the attention layers.
849
+ guidance_embeds (`bool`, defaults to `True`):
850
+ Whether to use guidance embeddings in the model.
851
+ text_embed_dim (`int`, defaults to `4096`):
852
+ Input dimension of text embeddings from the text encoder.
853
+ pooled_projection_dim (`int`, defaults to `768`):
854
+ The dimension of the pooled projection of the text embeddings.
855
+ rope_theta (`float`, defaults to `256.0`):
856
+ The value of theta to use in the RoPE layer.
857
+ rope_axes_dim (`Tuple[int]`, defaults to `(16, 56, 56)`):
858
+ The dimensions of the axes to use in the RoPE layer.
859
+ image_condition_type (`str`, *optional*, defaults to `None`):
860
+ The type of image conditioning to use. If `None`, no image conditioning is used. If `latent_concat`, the
861
+ image is concatenated to the latent stream. If `token_replace`, the image is used to replace first-frame
862
+ tokens in the latent stream and apply conditioning.
863
+ """
864
+
865
+ _supports_gradient_checkpointing = True
866
+ _skip_layerwise_casting_patterns = ["x_embedder", "context_embedder", "norm"]
867
+ _no_split_modules = [
868
+ "HunyuanVideoTransformerBlock",
869
+ "HunyuanVideoSingleTransformerBlock",
870
+ "HunyuanVideoPatchEmbed",
871
+ "HunyuanVideoTokenRefiner",
872
+ ]
873
+
874
+ @register_to_config
875
+ def __init__(
876
+ self,
877
+ in_channels: int = 16,
878
+ out_channels: int = 16,
879
+ num_attention_heads: int = 24,
880
+ attention_head_dim: int = 128,
881
+ num_layers: int = 20,
882
+ num_single_layers: int = 40,
883
+ num_refiner_layers: int = 2,
884
+ mlp_ratio: float = 4.0,
885
+ patch_size: int = 2,
886
+ patch_size_t: int = 1,
887
+ qk_norm: str = "rms_norm",
888
+ guidance_embeds: bool = True,
889
+ text_embed_dim: int = 4096,
890
+ pooled_projection_dim: int = 768,
891
+ rope_theta: float = 256.0,
892
+ rope_axes_dim: Tuple[int] = (16, 56, 56),
893
+ image_condition_type: Optional[str] = None,
894
+ ) -> None:
895
+ super().__init__()
896
+
897
+ supported_image_condition_types = ["latent_concat", "token_replace"]
898
+ if image_condition_type is not None and image_condition_type not in supported_image_condition_types:
899
+ raise ValueError(
900
+ f"Invalid `image_condition_type` ({image_condition_type}). Supported ones are: {supported_image_condition_types}"
901
+ )
902
+
903
+ inner_dim = num_attention_heads * attention_head_dim
904
+ out_channels = out_channels or in_channels
905
+
906
+ # 1. Latent and condition embedders
907
+ self.x_embedder = HunyuanVideoPatchEmbed((patch_size_t, patch_size, patch_size), in_channels, inner_dim)
908
+ self.context_embedder = HunyuanVideoTokenRefiner(
909
+ text_embed_dim, num_attention_heads, attention_head_dim, num_layers=num_refiner_layers
910
+ )
911
+
912
+ self.time_text_embed = HunyuanVideoConditionEmbedding(
913
+ inner_dim, pooled_projection_dim, guidance_embeds, image_condition_type
914
+ )
915
+
916
+ # 2. RoPE
917
+ self.rope = HunyuanVideoRotaryPosEmbed(patch_size, patch_size_t, rope_axes_dim, rope_theta)
918
+
919
+ # 3. Dual stream transformer blocks
920
+ if image_condition_type == "token_replace":
921
+ self.transformer_blocks = nn.ModuleList(
922
+ [
923
+ HunyuanVideoTokenReplaceTransformerBlock(
924
+ num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm
925
+ )
926
+ for _ in range(num_layers)
927
+ ]
928
+ )
929
+ else:
930
+ self.transformer_blocks = nn.ModuleList(
931
+ [
932
+ HunyuanVideoTransformerBlock(
933
+ num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm
934
+ )
935
+ for _ in range(num_layers)
936
+ ]
937
+ )
938
+
939
+ # 4. Single stream transformer blocks
940
+ if image_condition_type == "token_replace":
941
+ self.single_transformer_blocks = nn.ModuleList(
942
+ [
943
+ HunyuanVideoTokenReplaceSingleTransformerBlock(
944
+ num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm
945
+ )
946
+ for _ in range(num_single_layers)
947
+ ]
948
+ )
949
+ else:
950
+ self.single_transformer_blocks = nn.ModuleList(
951
+ [
952
+ HunyuanVideoSingleTransformerBlock(
953
+ num_attention_heads, attention_head_dim, mlp_ratio=mlp_ratio, qk_norm=qk_norm
954
+ )
955
+ for _ in range(num_single_layers)
956
+ ]
957
+ )
958
+
959
+ # 5. Output projection
960
+ self.norm_out = AdaLayerNormContinuous(inner_dim, inner_dim, elementwise_affine=False, eps=1e-6)
961
+ self.proj_out = nn.Linear(inner_dim, patch_size_t * patch_size * patch_size * out_channels)
962
+
963
+ self.gradient_checkpointing = False
964
+
965
+ @property
966
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.attn_processors
967
+ def attn_processors(self) -> Dict[str, AttentionProcessor]:
968
+ r"""
969
+ Returns:
970
+ `dict` of attention processors: A dictionary containing all attention processors used in the model with
971
+ indexed by its weight name.
972
+ """
973
+ # set recursively
974
+ processors = {}
975
+
976
+ def fn_recursive_add_processors(name: str, module: torch.nn.Module, processors: Dict[str, AttentionProcessor]):
977
+ if hasattr(module, "get_processor"):
978
+ processors[f"{name}.processor"] = module.get_processor()
979
+
980
+ for sub_name, child in module.named_children():
981
+ fn_recursive_add_processors(f"{name}.{sub_name}", child, processors)
982
+
983
+ return processors
984
+
985
+ for name, module in self.named_children():
986
+ fn_recursive_add_processors(name, module, processors)
987
+
988
+ return processors
989
+
990
+ # Copied from diffusers.models.unets.unet_2d_condition.UNet2DConditionModel.set_attn_processor
991
+ def set_attn_processor(self, processor: Union[AttentionProcessor, Dict[str, AttentionProcessor]]):
992
+ r"""
993
+ Sets the attention processor to use to compute attention.
994
+
995
+ Parameters:
996
+ processor (`dict` of `AttentionProcessor` or only `AttentionProcessor`):
997
+ The instantiated processor class or a dictionary of processor classes that will be set as the processor
998
+ for **all** `Attention` layers.
999
+
1000
+ If `processor` is a dict, the key needs to define the path to the corresponding cross attention
1001
+ processor. This is strongly recommended when setting trainable attention processors.
1002
+
1003
+ """
1004
+ count = len(self.attn_processors.keys())
1005
+
1006
+ if isinstance(processor, dict) and len(processor) != count:
1007
+ raise ValueError(
1008
+ f"A dict of processors was passed, but the number of processors {len(processor)} does not match the"
1009
+ f" number of attention layers: {count}. Please make sure to pass {count} processor classes."
1010
+ )
1011
+
1012
+ def fn_recursive_attn_processor(name: str, module: torch.nn.Module, processor):
1013
+ if hasattr(module, "set_processor"):
1014
+ if not isinstance(processor, dict):
1015
+ module.set_processor(processor)
1016
+ else:
1017
+ module.set_processor(processor.pop(f"{name}.processor"))
1018
+
1019
+ for sub_name, child in module.named_children():
1020
+ fn_recursive_attn_processor(f"{name}.{sub_name}", child, processor)
1021
+
1022
+ for name, module in self.named_children():
1023
+ fn_recursive_attn_processor(name, module, processor)
1024
+
1025
+ def forward(
1026
+ self,
1027
+ hidden_states: torch.Tensor,
1028
+ timestep: torch.LongTensor,
1029
+ encoder_hidden_states: torch.Tensor,
1030
+ encoder_attention_mask: torch.Tensor,
1031
+ pooled_projections: torch.Tensor,
1032
+ guidance: torch.Tensor = None,
1033
+ attention_kwargs: Optional[Dict[str, Any]] = None,
1034
+ return_dict: bool = True,
1035
+ ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
1036
+ if attention_kwargs is not None:
1037
+ attention_kwargs = attention_kwargs.copy()
1038
+ lora_scale = attention_kwargs.pop("scale", 1.0)
1039
+ else:
1040
+ lora_scale = 1.0
1041
+
1042
+ if USE_PEFT_BACKEND:
1043
+ # weight the lora layers by setting `lora_scale` for each PEFT layer
1044
+ scale_lora_layers(self, lora_scale)
1045
+ else:
1046
+ if attention_kwargs is not None and attention_kwargs.get("scale", None) is not None:
1047
+ logger.warning(
1048
+ "Passing `scale` via `attention_kwargs` when not using the PEFT backend is ineffective."
1049
+ )
1050
+
1051
+ batch_size, num_channels, num_frames, height, width = hidden_states.shape
1052
+ p, p_t = self.config.patch_size, self.config.patch_size_t
1053
+ post_patch_num_frames = num_frames // p_t
1054
+ post_patch_height = height // p
1055
+ post_patch_width = width // p
1056
+ first_frame_num_tokens = 1 * post_patch_height * post_patch_width
1057
+
1058
+ # 1. RoPE
1059
+ image_rotary_emb = self.rope(hidden_states)
1060
+
1061
+ # 2. Conditional embeddings
1062
+ temb, token_replace_emb = self.time_text_embed(timestep, pooled_projections, guidance)
1063
+
1064
+ hidden_states = self.x_embedder(hidden_states)
1065
+ encoder_hidden_states = self.context_embedder(encoder_hidden_states, timestep, encoder_attention_mask)
1066
+
1067
+ # 3. Attention mask preparation
1068
+ latent_sequence_length = hidden_states.shape[1]
1069
+ condition_sequence_length = encoder_hidden_states.shape[1]
1070
+ sequence_length = latent_sequence_length + condition_sequence_length
1071
+ attention_mask = torch.zeros(
1072
+ batch_size, sequence_length, device=hidden_states.device, dtype=torch.bool
1073
+ ) # [B, N]
1074
+
1075
+ effective_condition_sequence_length = encoder_attention_mask.sum(dim=1, dtype=torch.int) # [B,]
1076
+ effective_sequence_length = latent_sequence_length + effective_condition_sequence_length
1077
+
1078
+ for i in range(batch_size):
1079
+ attention_mask[i, : effective_sequence_length[i]] = True
1080
+ # [B, 1, 1, N], for broadcasting across attention heads
1081
+ attention_mask = attention_mask.unsqueeze(1).unsqueeze(1)
1082
+
1083
+ # 4. Transformer blocks
1084
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
1085
+ for block in self.transformer_blocks:
1086
+ hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
1087
+ block,
1088
+ hidden_states,
1089
+ encoder_hidden_states,
1090
+ temb,
1091
+ attention_mask,
1092
+ image_rotary_emb,
1093
+ token_replace_emb,
1094
+ first_frame_num_tokens,
1095
+ )
1096
+
1097
+ for block in self.single_transformer_blocks:
1098
+ hidden_states, encoder_hidden_states = self._gradient_checkpointing_func(
1099
+ block,
1100
+ hidden_states,
1101
+ encoder_hidden_states,
1102
+ temb,
1103
+ attention_mask,
1104
+ image_rotary_emb,
1105
+ token_replace_emb,
1106
+ first_frame_num_tokens,
1107
+ )
1108
+
1109
+ else:
1110
+ for block in self.transformer_blocks:
1111
+ hidden_states, encoder_hidden_states = block(
1112
+ hidden_states,
1113
+ encoder_hidden_states,
1114
+ temb,
1115
+ attention_mask,
1116
+ image_rotary_emb,
1117
+ token_replace_emb,
1118
+ first_frame_num_tokens,
1119
+ )
1120
+
1121
+ for block in self.single_transformer_blocks:
1122
+ hidden_states, encoder_hidden_states = block(
1123
+ hidden_states,
1124
+ encoder_hidden_states,
1125
+ temb,
1126
+ attention_mask,
1127
+ image_rotary_emb,
1128
+ token_replace_emb,
1129
+ first_frame_num_tokens,
1130
+ )
1131
+
1132
+ # 5. Output projection
1133
+ hidden_states = self.norm_out(hidden_states, temb)
1134
+ hidden_states = self.proj_out(hidden_states)
1135
+
1136
+ hidden_states = hidden_states.reshape(
1137
+ batch_size, post_patch_num_frames, post_patch_height, post_patch_width, -1, p_t, p, p
1138
+ )
1139
+ hidden_states = hidden_states.permute(0, 4, 1, 5, 2, 6, 3, 7)
1140
+ hidden_states = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
1141
+
1142
+ if USE_PEFT_BACKEND:
1143
+ # remove `lora_scale` from each PEFT layer
1144
+ unscale_lora_layers(self, lora_scale)
1145
+
1146
+ if not return_dict:
1147
+ return (hidden_states,)
1148
+
1149
+ return Transformer2DModelOutput(sample=hidden_states)