optimum-rbln 0.9.3.post1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of optimum-rbln might be problematic. Click here for more details.

Files changed (264) hide show
  1. optimum/rbln/__init__.py +505 -0
  2. optimum/rbln/__version__.py +34 -0
  3. optimum/rbln/cli.py +660 -0
  4. optimum/rbln/configuration_utils.py +968 -0
  5. optimum/rbln/diffusers/__init__.py +198 -0
  6. optimum/rbln/diffusers/configurations/__init__.py +37 -0
  7. optimum/rbln/diffusers/configurations/models/__init__.py +10 -0
  8. optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl.py +73 -0
  9. optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_cosmos.py +84 -0
  10. optimum/rbln/diffusers/configurations/models/configuration_autoencoder_kl_temporal_decoder.py +67 -0
  11. optimum/rbln/diffusers/configurations/models/configuration_controlnet.py +64 -0
  12. optimum/rbln/diffusers/configurations/models/configuration_prior_transformer.py +59 -0
  13. optimum/rbln/diffusers/configurations/models/configuration_transformer_cosmos.py +78 -0
  14. optimum/rbln/diffusers/configurations/models/configuration_transformer_sd3.py +63 -0
  15. optimum/rbln/diffusers/configurations/models/configuration_unet_2d_condition.py +81 -0
  16. optimum/rbln/diffusers/configurations/models/configuration_unet_spatio_temporal_condition.py +59 -0
  17. optimum/rbln/diffusers/configurations/models/configuration_vq_model.py +74 -0
  18. optimum/rbln/diffusers/configurations/pipelines/__init__.py +34 -0
  19. optimum/rbln/diffusers/configurations/pipelines/configuration_controlnet.py +316 -0
  20. optimum/rbln/diffusers/configurations/pipelines/configuration_cosmos.py +117 -0
  21. optimum/rbln/diffusers/configurations/pipelines/configuration_kandinsky2_2.py +363 -0
  22. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion.py +156 -0
  23. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_3.py +176 -0
  24. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_diffusion_xl.py +159 -0
  25. optimum/rbln/diffusers/configurations/pipelines/configuration_stable_video_diffusion.py +114 -0
  26. optimum/rbln/diffusers/modeling_diffusers.py +451 -0
  27. optimum/rbln/diffusers/models/__init__.py +64 -0
  28. optimum/rbln/diffusers/models/autoencoders/__init__.py +18 -0
  29. optimum/rbln/diffusers/models/autoencoders/autoencoder_kl.py +255 -0
  30. optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_cosmos.py +245 -0
  31. optimum/rbln/diffusers/models/autoencoders/autoencoder_kl_temporal_decoder.py +275 -0
  32. optimum/rbln/diffusers/models/autoencoders/vae.py +178 -0
  33. optimum/rbln/diffusers/models/autoencoders/vq_model.py +211 -0
  34. optimum/rbln/diffusers/models/controlnet.py +281 -0
  35. optimum/rbln/diffusers/models/transformers/__init__.py +17 -0
  36. optimum/rbln/diffusers/models/transformers/prior_transformer.py +160 -0
  37. optimum/rbln/diffusers/models/transformers/transformer_cosmos.py +344 -0
  38. optimum/rbln/diffusers/models/transformers/transformer_sd3.py +191 -0
  39. optimum/rbln/diffusers/models/unets/__init__.py +16 -0
  40. optimum/rbln/diffusers/models/unets/unet_2d_condition.py +408 -0
  41. optimum/rbln/diffusers/models/unets/unet_spatio_temporal_condition.py +201 -0
  42. optimum/rbln/diffusers/pipelines/__init__.py +113 -0
  43. optimum/rbln/diffusers/pipelines/auto_pipeline.py +307 -0
  44. optimum/rbln/diffusers/pipelines/controlnet/__init__.py +19 -0
  45. optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +139 -0
  46. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +669 -0
  47. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +640 -0
  48. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +825 -0
  49. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +837 -0
  50. optimum/rbln/diffusers/pipelines/cosmos/__init__.py +17 -0
  51. optimum/rbln/diffusers/pipelines/cosmos/configuration_cosmos_guardrail.py +113 -0
  52. optimum/rbln/diffusers/pipelines/cosmos/cosmos_guardrail.py +425 -0
  53. optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_text2world.py +128 -0
  54. optimum/rbln/diffusers/pipelines/cosmos/pipeline_cosmos_video2world.py +128 -0
  55. optimum/rbln/diffusers/pipelines/kandinsky2_2/__init__.py +23 -0
  56. optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2.py +34 -0
  57. optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_combined.py +207 -0
  58. optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_img2img.py +34 -0
  59. optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_inpaint.py +34 -0
  60. optimum/rbln/diffusers/pipelines/kandinsky2_2/pipeline_kandinsky2_2_prior.py +31 -0
  61. optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +17 -0
  62. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +32 -0
  63. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +31 -0
  64. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +31 -0
  65. optimum/rbln/diffusers/pipelines/stable_diffusion_3/__init__.py +17 -0
  66. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +31 -0
  67. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +31 -0
  68. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +31 -0
  69. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +17 -0
  70. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +31 -0
  71. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +31 -0
  72. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +31 -0
  73. optimum/rbln/diffusers/pipelines/stable_video_diffusion/__init__.py +15 -0
  74. optimum/rbln/diffusers/pipelines/stable_video_diffusion/pipeline_stable_video_diffusion.py +46 -0
  75. optimum/rbln/modeling.py +364 -0
  76. optimum/rbln/modeling_base.py +637 -0
  77. optimum/rbln/ops/__init__.py +19 -0
  78. optimum/rbln/ops/attn.py +455 -0
  79. optimum/rbln/ops/flash_attn.py +350 -0
  80. optimum/rbln/ops/kv_cache_update.py +29 -0
  81. optimum/rbln/ops/linear.py +32 -0
  82. optimum/rbln/ops/sliding_window_attn.py +111 -0
  83. optimum/rbln/transformers/__init__.py +340 -0
  84. optimum/rbln/transformers/configuration_generic.py +120 -0
  85. optimum/rbln/transformers/modeling_attention_utils.py +385 -0
  86. optimum/rbln/transformers/modeling_generic.py +280 -0
  87. optimum/rbln/transformers/modeling_outputs.py +37 -0
  88. optimum/rbln/transformers/modeling_rope_utils.py +314 -0
  89. optimum/rbln/transformers/models/__init__.py +343 -0
  90. optimum/rbln/transformers/models/audio_spectrogram_transformer/__init__.py +17 -0
  91. optimum/rbln/transformers/models/audio_spectrogram_transformer/configuration_audio_spectrogram_transformer.py +47 -0
  92. optimum/rbln/transformers/models/audio_spectrogram_transformer/modeling_audio_spectrogram_transformer.py +91 -0
  93. optimum/rbln/transformers/models/auto/__init__.py +31 -0
  94. optimum/rbln/transformers/models/auto/auto_factory.py +267 -0
  95. optimum/rbln/transformers/models/auto/modeling_auto.py +162 -0
  96. optimum/rbln/transformers/models/bart/__init__.py +17 -0
  97. optimum/rbln/transformers/models/bart/bart_architecture.py +163 -0
  98. optimum/rbln/transformers/models/bart/configuration_bart.py +36 -0
  99. optimum/rbln/transformers/models/bart/modeling_bart.py +86 -0
  100. optimum/rbln/transformers/models/bert/__init__.py +16 -0
  101. optimum/rbln/transformers/models/bert/bert_architecture.py +16 -0
  102. optimum/rbln/transformers/models/bert/configuration_bert.py +46 -0
  103. optimum/rbln/transformers/models/bert/modeling_bert.py +148 -0
  104. optimum/rbln/transformers/models/blip_2/__init__.py +20 -0
  105. optimum/rbln/transformers/models/blip_2/configuration_blip_2.py +115 -0
  106. optimum/rbln/transformers/models/blip_2/modeling_blip_2.py +526 -0
  107. optimum/rbln/transformers/models/clip/__init__.py +26 -0
  108. optimum/rbln/transformers/models/clip/configuration_clip.py +103 -0
  109. optimum/rbln/transformers/models/clip/modeling_clip.py +384 -0
  110. optimum/rbln/transformers/models/colpali/__init__.py +2 -0
  111. optimum/rbln/transformers/models/colpali/colpali_architecture.py +218 -0
  112. optimum/rbln/transformers/models/colpali/configuration_colpali.py +84 -0
  113. optimum/rbln/transformers/models/colpali/modeling_colpali.py +361 -0
  114. optimum/rbln/transformers/models/colqwen2/__init__.py +2 -0
  115. optimum/rbln/transformers/models/colqwen2/colqwen2_architecture.py +233 -0
  116. optimum/rbln/transformers/models/colqwen2/configuration_colqwen2.py +74 -0
  117. optimum/rbln/transformers/models/colqwen2/modeling_colqwen2.py +446 -0
  118. optimum/rbln/transformers/models/decoderonly/__init__.py +27 -0
  119. optimum/rbln/transformers/models/decoderonly/configuration_decoderonly.py +300 -0
  120. optimum/rbln/transformers/models/decoderonly/configuration_lora.py +411 -0
  121. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +1224 -0
  122. optimum/rbln/transformers/models/decoderonly/decoderonly_runtime_utils.py +508 -0
  123. optimum/rbln/transformers/models/decoderonly/generation_decoderonly.py +119 -0
  124. optimum/rbln/transformers/models/decoderonly/lora_architecture.py +204 -0
  125. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +823 -0
  126. optimum/rbln/transformers/models/depth_anything/__init__.py +16 -0
  127. optimum/rbln/transformers/models/depth_anything/configuration_depth_anything.py +24 -0
  128. optimum/rbln/transformers/models/depth_anything/modeling_depth_anything.py +42 -0
  129. optimum/rbln/transformers/models/distilbert/__init__.py +19 -0
  130. optimum/rbln/transformers/models/distilbert/configuration_distilbert.py +24 -0
  131. optimum/rbln/transformers/models/distilbert/modeling_distilbert.py +51 -0
  132. optimum/rbln/transformers/models/dpt/__init__.py +16 -0
  133. optimum/rbln/transformers/models/dpt/configuration_dpt.py +24 -0
  134. optimum/rbln/transformers/models/dpt/modeling_dpt.py +42 -0
  135. optimum/rbln/transformers/models/exaone/__init__.py +24 -0
  136. optimum/rbln/transformers/models/exaone/configuration_exaone.py +42 -0
  137. optimum/rbln/transformers/models/exaone/exaone_architecture.py +77 -0
  138. optimum/rbln/transformers/models/exaone/modeling_exaone.py +145 -0
  139. optimum/rbln/transformers/models/gemma/__init__.py +16 -0
  140. optimum/rbln/transformers/models/gemma/configuration_gemma.py +50 -0
  141. optimum/rbln/transformers/models/gemma/gemma_architecture.py +27 -0
  142. optimum/rbln/transformers/models/gemma/modeling_gemma.py +104 -0
  143. optimum/rbln/transformers/models/gemma3/__init__.py +16 -0
  144. optimum/rbln/transformers/models/gemma3/configuration_gemma3.py +109 -0
  145. optimum/rbln/transformers/models/gemma3/gemma3_architecture.py +170 -0
  146. optimum/rbln/transformers/models/gemma3/gemma3_runtime_utils.py +245 -0
  147. optimum/rbln/transformers/models/gemma3/modeling_gemma3.py +611 -0
  148. optimum/rbln/transformers/models/gpt2/__init__.py +16 -0
  149. optimum/rbln/transformers/models/gpt2/configuration_gpt2.py +50 -0
  150. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +93 -0
  151. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +55 -0
  152. optimum/rbln/transformers/models/grounding_dino/__init__.py +10 -0
  153. optimum/rbln/transformers/models/grounding_dino/configuration_grounding_dino.py +92 -0
  154. optimum/rbln/transformers/models/grounding_dino/grounding_dino_architecture.py +599 -0
  155. optimum/rbln/transformers/models/grounding_dino/modeling_grounding_dino.py +1048 -0
  156. optimum/rbln/transformers/models/idefics3/__init__.py +16 -0
  157. optimum/rbln/transformers/models/idefics3/configuration_idefics3.py +89 -0
  158. optimum/rbln/transformers/models/idefics3/modeling_idefics3.py +497 -0
  159. optimum/rbln/transformers/models/llama/__init__.py +16 -0
  160. optimum/rbln/transformers/models/llama/configuration_llama.py +50 -0
  161. optimum/rbln/transformers/models/llama/llama_architecture.py +19 -0
  162. optimum/rbln/transformers/models/llama/modeling_llama.py +104 -0
  163. optimum/rbln/transformers/models/llava/__init__.py +16 -0
  164. optimum/rbln/transformers/models/llava/configuration_llava.py +72 -0
  165. optimum/rbln/transformers/models/llava/modeling_llava.py +490 -0
  166. optimum/rbln/transformers/models/llava_next/__init__.py +16 -0
  167. optimum/rbln/transformers/models/llava_next/configuration_llava_next.py +69 -0
  168. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +493 -0
  169. optimum/rbln/transformers/models/midm/__init__.py +24 -0
  170. optimum/rbln/transformers/models/midm/configuration_midm.py +42 -0
  171. optimum/rbln/transformers/models/midm/midm_architecture.py +144 -0
  172. optimum/rbln/transformers/models/midm/modeling_midm.py +144 -0
  173. optimum/rbln/transformers/models/mistral/__init__.py +16 -0
  174. optimum/rbln/transformers/models/mistral/configuration_mistral.py +50 -0
  175. optimum/rbln/transformers/models/mistral/mistral_architecture.py +19 -0
  176. optimum/rbln/transformers/models/mistral/modeling_mistral.py +115 -0
  177. optimum/rbln/transformers/models/opt/__init__.py +16 -0
  178. optimum/rbln/transformers/models/opt/configuration_opt.py +29 -0
  179. optimum/rbln/transformers/models/opt/modeling_opt.py +102 -0
  180. optimum/rbln/transformers/models/opt/opt_architecture.py +74 -0
  181. optimum/rbln/transformers/models/pegasus/__init__.py +17 -0
  182. optimum/rbln/transformers/models/pegasus/configuration_pegasus.py +38 -0
  183. optimum/rbln/transformers/models/pegasus/modeling_pegasus.py +71 -0
  184. optimum/rbln/transformers/models/pegasus/pegasus_architecture.py +161 -0
  185. optimum/rbln/transformers/models/phi/__init__.py +16 -0
  186. optimum/rbln/transformers/models/phi/configuration_phi.py +50 -0
  187. optimum/rbln/transformers/models/phi/modeling_phi.py +92 -0
  188. optimum/rbln/transformers/models/phi/phi_architecture.py +115 -0
  189. optimum/rbln/transformers/models/pixtral/__init__.py +16 -0
  190. optimum/rbln/transformers/models/pixtral/configuration_pixtral.py +43 -0
  191. optimum/rbln/transformers/models/pixtral/modeling_pixtral.py +322 -0
  192. optimum/rbln/transformers/models/pixtral/pixtral_architecture.py +73 -0
  193. optimum/rbln/transformers/models/qwen2/__init__.py +16 -0
  194. optimum/rbln/transformers/models/qwen2/configuration_qwen2.py +50 -0
  195. optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +123 -0
  196. optimum/rbln/transformers/models/qwen2/qwen2_architecture.py +19 -0
  197. optimum/rbln/transformers/models/qwen2_5_vl/__init__.py +19 -0
  198. optimum/rbln/transformers/models/qwen2_5_vl/configuration_qwen2_5_vl.py +111 -0
  199. optimum/rbln/transformers/models/qwen2_5_vl/modeling_qwen2_5_vl.py +636 -0
  200. optimum/rbln/transformers/models/qwen2_5_vl/qwen2_5_vl_architecture.py +220 -0
  201. optimum/rbln/transformers/models/qwen2_vl/__init__.py +19 -0
  202. optimum/rbln/transformers/models/qwen2_vl/configuration_qwen2_vl.py +88 -0
  203. optimum/rbln/transformers/models/qwen2_vl/modeling_qwen2_vl.py +513 -0
  204. optimum/rbln/transformers/models/qwen2_vl/qwen2_vl_architecture.py +165 -0
  205. optimum/rbln/transformers/models/qwen3/__init__.py +16 -0
  206. optimum/rbln/transformers/models/qwen3/configuration_qwen3.py +71 -0
  207. optimum/rbln/transformers/models/qwen3/modeling_qwen3.py +133 -0
  208. optimum/rbln/transformers/models/qwen3/qwen3_architecture.py +31 -0
  209. optimum/rbln/transformers/models/resnet/__init__.py +23 -0
  210. optimum/rbln/transformers/models/resnet/configuration_resnet.py +42 -0
  211. optimum/rbln/transformers/models/resnet/modeling_resnet.py +99 -0
  212. optimum/rbln/transformers/models/roberta/__init__.py +24 -0
  213. optimum/rbln/transformers/models/roberta/configuration_roberta.py +33 -0
  214. optimum/rbln/transformers/models/roberta/modeling_roberta.py +72 -0
  215. optimum/rbln/transformers/models/seq2seq/__init__.py +16 -0
  216. optimum/rbln/transformers/models/seq2seq/configuration_seq2seq.py +71 -0
  217. optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +477 -0
  218. optimum/rbln/transformers/models/seq2seq/seq2seq_architecture.py +527 -0
  219. optimum/rbln/transformers/models/siglip/__init__.py +16 -0
  220. optimum/rbln/transformers/models/siglip/configuration_siglip.py +76 -0
  221. optimum/rbln/transformers/models/siglip/modeling_siglip.py +199 -0
  222. optimum/rbln/transformers/models/swin/__init__.py +16 -0
  223. optimum/rbln/transformers/models/swin/configuration_swin.py +42 -0
  224. optimum/rbln/transformers/models/swin/modeling_swin.py +354 -0
  225. optimum/rbln/transformers/models/t5/__init__.py +17 -0
  226. optimum/rbln/transformers/models/t5/configuration_t5.py +36 -0
  227. optimum/rbln/transformers/models/t5/modeling_t5.py +130 -0
  228. optimum/rbln/transformers/models/t5/t5_architecture.py +264 -0
  229. optimum/rbln/transformers/models/time_series_transformer/__init__.py +26 -0
  230. optimum/rbln/transformers/models/time_series_transformer/configuration_time_series_transformer.py +41 -0
  231. optimum/rbln/transformers/models/time_series_transformer/modeling_time_series_transformer.py +435 -0
  232. optimum/rbln/transformers/models/time_series_transformer/time_series_transformers_architecture.py +337 -0
  233. optimum/rbln/transformers/models/vit/__init__.py +19 -0
  234. optimum/rbln/transformers/models/vit/configuration_vit.py +24 -0
  235. optimum/rbln/transformers/models/vit/modeling_vit.py +44 -0
  236. optimum/rbln/transformers/models/wav2vec2/__init__.py +16 -0
  237. optimum/rbln/transformers/models/wav2vec2/configuration_wav2vec2.py +38 -0
  238. optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +104 -0
  239. optimum/rbln/transformers/models/whisper/__init__.py +17 -0
  240. optimum/rbln/transformers/models/whisper/configuration_whisper.py +72 -0
  241. optimum/rbln/transformers/models/whisper/generation_whisper.py +159 -0
  242. optimum/rbln/transformers/models/whisper/modeling_whisper.py +475 -0
  243. optimum/rbln/transformers/models/whisper/whisper_architecture.py +349 -0
  244. optimum/rbln/transformers/models/xlm_roberta/__init__.py +24 -0
  245. optimum/rbln/transformers/models/xlm_roberta/configuration_xlm_roberta.py +32 -0
  246. optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +82 -0
  247. optimum/rbln/transformers/utils/__init__.py +0 -0
  248. optimum/rbln/transformers/utils/rbln_quantization.py +589 -0
  249. optimum/rbln/transformers/utils/rbln_runtime_wrapper.py +79 -0
  250. optimum/rbln/utils/__init__.py +16 -0
  251. optimum/rbln/utils/decorator_utils.py +86 -0
  252. optimum/rbln/utils/deprecation.py +213 -0
  253. optimum/rbln/utils/hub.py +94 -0
  254. optimum/rbln/utils/import_utils.py +170 -0
  255. optimum/rbln/utils/logging.py +110 -0
  256. optimum/rbln/utils/model_utils.py +63 -0
  257. optimum/rbln/utils/runtime_utils.py +249 -0
  258. optimum/rbln/utils/save_utils.py +102 -0
  259. optimum/rbln/utils/submodule.py +152 -0
  260. optimum_rbln-0.9.3.post1.dist-info/METADATA +124 -0
  261. optimum_rbln-0.9.3.post1.dist-info/RECORD +264 -0
  262. optimum_rbln-0.9.3.post1.dist-info/WHEEL +4 -0
  263. optimum_rbln-0.9.3.post1.dist-info/entry_points.txt +2 -0
  264. optimum_rbln-0.9.3.post1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,825 @@
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
+ # Copyright 2025 Rebellions Inc. All rights reserved.
16
+
17
+ # Licensed under the Apache License, Version 2.0 (the "License");
18
+ # you may not use this file except in compliance with the License.
19
+ # You may obtain a copy of the License at:
20
+
21
+ # http://www.apache.org/licenses/LICENSE-2.0
22
+
23
+ # Unless required by applicable law or agreed to in writing, software
24
+ # distributed under the License is distributed on an "AS IS" BASIS,
25
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26
+ # See the License for the specific language governing permissions and
27
+ # limitations under the License.
28
+
29
+ from typing import Any, Callable, Dict, List, Optional, Tuple, Union
30
+
31
+ import torch
32
+ import torch.nn.functional as F
33
+ from diffusers import StableDiffusionXLControlNetPipeline
34
+ from diffusers.image_processor import PipelineImageInput
35
+ from diffusers.pipelines.stable_diffusion_xl.pipeline_output import StableDiffusionXLPipelineOutput
36
+ from diffusers.utils import deprecate, logging
37
+ from diffusers.utils.torch_utils import is_compiled_module, is_torch_version
38
+
39
+ from ....utils.decorator_utils import remove_compile_time_kwargs
40
+ from ...configurations import RBLNStableDiffusionXLControlNetPipelineConfig
41
+ from ...modeling_diffusers import RBLNDiffusionMixin
42
+ from ...models import RBLNControlNetModel
43
+ from ...pipelines.controlnet.multicontrolnet import RBLNMultiControlNetModel
44
+
45
+
46
+ logger = logging.get_logger(__name__)
47
+
48
+
49
+ class RBLNStableDiffusionXLControlNetPipeline(RBLNDiffusionMixin, StableDiffusionXLControlNetPipeline):
50
+ """
51
+ RBLN-accelerated implementation of Stable Diffusion XL pipeline with ControlNet for high-resolution guided text-to-image generation.
52
+
53
+ This pipeline compiles Stable Diffusion XL and ControlNet models to run efficiently on RBLN NPUs, enabling high-performance
54
+ inference for generating high-quality images with precise structural control and enhanced detail preservation.
55
+ """
56
+
57
+ original_class = StableDiffusionXLControlNetPipeline
58
+ _rbln_config_class = RBLNStableDiffusionXLControlNetPipelineConfig
59
+ _submodules = ["text_encoder", "text_encoder_2", "unet", "vae", "controlnet"]
60
+
61
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.py
62
+ def check_inputs(
63
+ self,
64
+ prompt,
65
+ prompt_2,
66
+ image,
67
+ callback_steps,
68
+ negative_prompt=None,
69
+ negative_prompt_2=None,
70
+ prompt_embeds=None,
71
+ negative_prompt_embeds=None,
72
+ pooled_prompt_embeds=None,
73
+ ip_adapter_image=None,
74
+ ip_adapter_image_embeds=None,
75
+ negative_pooled_prompt_embeds=None,
76
+ controlnet_conditioning_scale=1.0,
77
+ control_guidance_start=0.0,
78
+ control_guidance_end=1.0,
79
+ callback_on_step_end_tensor_inputs=None,
80
+ ):
81
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
82
+ raise ValueError(
83
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
84
+ f" {type(callback_steps)}."
85
+ )
86
+
87
+ if callback_on_step_end_tensor_inputs is not None and not all(
88
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
89
+ ):
90
+ raise ValueError(
91
+ f"`callback_on_step_end_tensor_inputs` has to be in {self._callback_tensor_inputs}, but found {[k for k in callback_on_step_end_tensor_inputs if k not in self._callback_tensor_inputs]}"
92
+ )
93
+
94
+ if prompt is not None and prompt_embeds is not None:
95
+ raise ValueError(
96
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
97
+ " only forward one of the two."
98
+ )
99
+ elif prompt_2 is not None and prompt_embeds is not None:
100
+ raise ValueError(
101
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
102
+ " only forward one of the two."
103
+ )
104
+ elif prompt is None and prompt_embeds is None:
105
+ raise ValueError(
106
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
107
+ )
108
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
109
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
110
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
111
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
112
+
113
+ if negative_prompt is not None and negative_prompt_embeds is not None:
114
+ raise ValueError(
115
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
116
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
117
+ )
118
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
119
+ raise ValueError(
120
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
121
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
122
+ )
123
+
124
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
125
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
126
+ raise ValueError(
127
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
128
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
129
+ f" {negative_prompt_embeds.shape}."
130
+ )
131
+
132
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
133
+ raise ValueError(
134
+ "If `prompt_embeds` are provided, `pooled_prompt_embeds` also have to be passed. Make sure to generate `pooled_prompt_embeds` from the same text encoder that was used to generate `prompt_embeds`."
135
+ )
136
+
137
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
138
+ raise ValueError(
139
+ "If `negative_prompt_embeds` are provided, `negative_pooled_prompt_embeds` also have to be passed. Make sure to generate `negative_pooled_prompt_embeds` from the same text encoder that was used to generate `negative_prompt_embeds`."
140
+ )
141
+
142
+ # `prompt` needs more sophisticated handling when there are multiple
143
+ # conditionings.
144
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
145
+ if isinstance(prompt, list):
146
+ logger.warning(
147
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
148
+ " prompts. The conditionings will be fixed across the prompts."
149
+ )
150
+
151
+ # Check `image`
152
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
153
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
154
+ )
155
+ if (
156
+ isinstance(self.controlnet, RBLNControlNetModel)
157
+ or is_compiled
158
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
159
+ ):
160
+ self.check_image(image, prompt, prompt_embeds)
161
+ elif (
162
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
163
+ or is_compiled
164
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
165
+ ):
166
+ if not isinstance(image, list):
167
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
168
+
169
+ # When `image` is a nested list:
170
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
171
+ elif any(isinstance(i, list) for i in image):
172
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
173
+ elif len(image) != len(self.controlnet.nets):
174
+ raise ValueError(
175
+ f"For multiple controlnets: `image` must have the same length as the number of controlnets, but got {len(image)} images and {len(self.controlnet.nets)} ControlNets."
176
+ )
177
+
178
+ for image_ in image:
179
+ self.check_image(image_, prompt, prompt_embeds)
180
+ else:
181
+ assert False
182
+
183
+ # Check `controlnet_conditioning_scale`
184
+ if (
185
+ isinstance(self.controlnet, RBLNControlNetModel)
186
+ or is_compiled
187
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
188
+ ):
189
+ if not isinstance(controlnet_conditioning_scale, float):
190
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
191
+ elif (
192
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
193
+ or is_compiled
194
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
195
+ ):
196
+ if isinstance(controlnet_conditioning_scale, list):
197
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
198
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
199
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
200
+ self.controlnet.nets
201
+ ):
202
+ raise ValueError(
203
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
204
+ " the same length as the number of controlnets"
205
+ )
206
+ else:
207
+ assert False
208
+
209
+ if not isinstance(control_guidance_start, (tuple, list)):
210
+ control_guidance_start = [control_guidance_start]
211
+
212
+ if not isinstance(control_guidance_end, (tuple, list)):
213
+ control_guidance_end = [control_guidance_end]
214
+
215
+ if len(control_guidance_start) != len(control_guidance_end):
216
+ raise ValueError(
217
+ f"`control_guidance_start` has {len(control_guidance_start)} elements, but `control_guidance_end` has {len(control_guidance_end)} elements. Make sure to provide the same number of elements to each list."
218
+ )
219
+
220
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
221
+ if len(control_guidance_start) != len(self.controlnet.nets):
222
+ raise ValueError(
223
+ f"`control_guidance_start`: {control_guidance_start} has {len(control_guidance_start)} elements but there are {len(self.controlnet.nets)} controlnets available. Make sure to provide {len(self.controlnet.nets)}."
224
+ )
225
+
226
+ for start, end in zip(control_guidance_start, control_guidance_end):
227
+ if start >= end:
228
+ raise ValueError(
229
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
230
+ )
231
+ if start < 0.0:
232
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
233
+ if end > 1.0:
234
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
235
+
236
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
237
+ raise ValueError(
238
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
239
+ )
240
+
241
+ if ip_adapter_image_embeds is not None:
242
+ if not isinstance(ip_adapter_image_embeds, list):
243
+ raise ValueError(
244
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
245
+ )
246
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
247
+ raise ValueError(
248
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
249
+ )
250
+
251
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl.py
252
+ @torch.no_grad()
253
+ @remove_compile_time_kwargs
254
+ def __call__(
255
+ self,
256
+ prompt: Union[str, List[str]] = None,
257
+ prompt_2: Optional[Union[str, List[str]]] = None,
258
+ image: PipelineImageInput = None,
259
+ height: Optional[int] = None,
260
+ width: Optional[int] = None,
261
+ num_inference_steps: int = 50,
262
+ denoising_end: Optional[float] = None,
263
+ guidance_scale: float = 5.0,
264
+ negative_prompt: Optional[Union[str, List[str]]] = None,
265
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
266
+ num_images_per_prompt: Optional[int] = 1,
267
+ eta: float = 0.0,
268
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
269
+ latents: Optional[torch.FloatTensor] = None,
270
+ prompt_embeds: Optional[torch.FloatTensor] = None,
271
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
272
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
273
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
274
+ ip_adapter_image: Optional[PipelineImageInput] = None,
275
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
276
+ output_type: Optional[str] = "pil",
277
+ return_dict: bool = True,
278
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
279
+ controlnet_conditioning_scale: Union[float, List[float]] = 1.0,
280
+ guess_mode: bool = False,
281
+ control_guidance_start: Union[float, List[float]] = 0.0,
282
+ control_guidance_end: Union[float, List[float]] = 1.0,
283
+ original_size: Tuple[int, int] = None,
284
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
285
+ target_size: Tuple[int, int] = None,
286
+ negative_original_size: Optional[Tuple[int, int]] = None,
287
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
288
+ negative_target_size: Optional[Tuple[int, int]] = None,
289
+ clip_skip: Optional[int] = None,
290
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
291
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
292
+ **kwargs,
293
+ ):
294
+ r"""
295
+ The call function to the pipeline for generation.
296
+
297
+ Args:
298
+ prompt (`str` or `List[str]`, *optional*):
299
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
300
+ prompt_2 (`str` or `List[str]`, *optional*):
301
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
302
+ used in both text-encoders.
303
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
304
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
305
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
306
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
307
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
308
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
309
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
310
+ input to a single ControlNet.
311
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
312
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
313
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
314
+ and checkpoints that are not specifically fine-tuned on low resolutions.
315
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
316
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
317
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
318
+ and checkpoints that are not specifically fine-tuned on low resolutions.
319
+ num_inference_steps (`int`, *optional*, defaults to 50):
320
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
321
+ expense of slower inference.
322
+ denoising_end (`float`, *optional*):
323
+ When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
324
+ completed before it is intentionally prematurely terminated. As a result, the returned sample will
325
+ still retain a substantial amount of noise as determined by the discrete timesteps selected by the
326
+ scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
327
+ "Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
328
+ Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
329
+ guidance_scale (`float`, *optional*, defaults to 5.0):
330
+ A higher guidance scale value encourages the model to generate images closely linked to the text
331
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
332
+ negative_prompt (`str` or `List[str]`, *optional*):
333
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
334
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
335
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
336
+ The prompt or prompts to guide what to not include in image generation. This is sent to `tokenizer_2`
337
+ and `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders.
338
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
339
+ The number of images to generate per prompt.
340
+ eta (`float`, *optional*, defaults to 0.0):
341
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
342
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
343
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
344
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
345
+ generation deterministic.
346
+ latents (`torch.FloatTensor`, *optional*):
347
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
348
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
349
+ tensor is generated by sampling using the supplied random `generator`.
350
+ prompt_embeds (`torch.FloatTensor`, *optional*):
351
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
352
+ provided, text embeddings are generated from the `prompt` input argument.
353
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
354
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
355
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
356
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
357
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
358
+ not provided, pooled text embeddings are generated from `prompt` input argument.
359
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
360
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs (prompt
361
+ weighting). If not provided, pooled `negative_prompt_embeds` are generated from `negative_prompt` input
362
+ argument.
363
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
364
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
365
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
366
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
367
+ if `do_classifier_free_guidance` is set to `True`.
368
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
369
+ output_type (`str`, *optional*, defaults to `"pil"`):
370
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
371
+ return_dict (`bool`, *optional*, defaults to `True`):
372
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
373
+ plain tuple.
374
+ cross_attention_kwargs (`dict`, *optional*):
375
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
376
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
377
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
378
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
379
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
380
+ the corresponding scale as a list.
381
+ guess_mode (`bool`, *optional*, defaults to `False`):
382
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
383
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
384
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
385
+ The percentage of total steps at which the ControlNet starts applying.
386
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
387
+ The percentage of total steps at which the ControlNet stops applying.
388
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
389
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
390
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
391
+ explained in section 2.2 of
392
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
393
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
394
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
395
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
396
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
397
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
398
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
399
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
400
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
401
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
402
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
403
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
404
+ micro-conditioning as explained in section 2.2 of
405
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
406
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
407
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
408
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
409
+ micro-conditioning as explained in section 2.2 of
410
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
411
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
412
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
413
+ To negatively condition the generation process based on a target image resolution. It should be as same
414
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
415
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
416
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
417
+ clip_skip (`int`, *optional*):
418
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
419
+ the output of the pre-final layer will be used for computing the prompt embeddings.
420
+ callback_on_step_end (`Callable`, *optional*):
421
+ A function that calls at the end of each denoising steps during the inference. The function is called
422
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
423
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
424
+ `callback_on_step_end_tensor_inputs`.
425
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
426
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
427
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
428
+ `._callback_tensor_inputs` attribute of your pipeine class.
429
+
430
+ Examples:
431
+
432
+ Returns:
433
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
434
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
435
+ otherwise a `tuple` is returned containing the output images.
436
+ """
437
+
438
+ callback = kwargs.pop("callback", None)
439
+ callback_steps = kwargs.pop("callback_steps", None)
440
+
441
+ if callback is not None:
442
+ deprecate(
443
+ "callback",
444
+ "1.0.0",
445
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
446
+ )
447
+ if callback_steps is not None:
448
+ deprecate(
449
+ "callback_steps",
450
+ "1.0.0",
451
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
452
+ )
453
+
454
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
455
+
456
+ # align format for control guidance
457
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
458
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
459
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
460
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
461
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
462
+ mult = len(controlnet.nets) if isinstance(controlnet, RBLNMultiControlNetModel) else 1
463
+ control_guidance_start, control_guidance_end = (
464
+ mult * [control_guidance_start],
465
+ mult * [control_guidance_end],
466
+ )
467
+
468
+ # 1. Check inputs. Raise error if not correct
469
+ self.check_inputs(
470
+ prompt,
471
+ prompt_2,
472
+ image,
473
+ callback_steps,
474
+ negative_prompt,
475
+ negative_prompt_2,
476
+ prompt_embeds,
477
+ negative_prompt_embeds,
478
+ pooled_prompt_embeds,
479
+ ip_adapter_image,
480
+ ip_adapter_image_embeds,
481
+ negative_pooled_prompt_embeds,
482
+ controlnet_conditioning_scale,
483
+ control_guidance_start,
484
+ control_guidance_end,
485
+ callback_on_step_end_tensor_inputs,
486
+ )
487
+
488
+ self._guidance_scale = guidance_scale
489
+ self._clip_skip = clip_skip
490
+ self._cross_attention_kwargs = cross_attention_kwargs
491
+ self._denoising_end = denoising_end
492
+
493
+ # 2. Define call parameters
494
+ if prompt is not None and isinstance(prompt, str):
495
+ batch_size = 1
496
+ elif prompt is not None and isinstance(prompt, list):
497
+ batch_size = len(prompt)
498
+ else:
499
+ batch_size = prompt_embeds.shape[0]
500
+
501
+ device = self._execution_device
502
+
503
+ if isinstance(controlnet, RBLNMultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
504
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
505
+
506
+ global_pool_conditions = (
507
+ controlnet.config.global_pool_conditions
508
+ if isinstance(controlnet, RBLNControlNetModel)
509
+ else controlnet.nets[0].config.global_pool_conditions
510
+ )
511
+ guess_mode = guess_mode or global_pool_conditions
512
+
513
+ # 3.1 Encode input prompt
514
+ text_encoder_lora_scale = (
515
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
516
+ )
517
+
518
+ (
519
+ prompt_embeds,
520
+ negative_prompt_embeds,
521
+ pooled_prompt_embeds,
522
+ negative_pooled_prompt_embeds,
523
+ ) = self.encode_prompt(
524
+ prompt,
525
+ prompt_2,
526
+ device,
527
+ num_images_per_prompt,
528
+ self.do_classifier_free_guidance,
529
+ negative_prompt,
530
+ negative_prompt_2,
531
+ prompt_embeds=prompt_embeds,
532
+ negative_prompt_embeds=negative_prompt_embeds,
533
+ pooled_prompt_embeds=pooled_prompt_embeds,
534
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
535
+ lora_scale=text_encoder_lora_scale,
536
+ clip_skip=self.clip_skip,
537
+ )
538
+
539
+ # 3.2 Encode ip_adapter_image
540
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
541
+ image_embeds = self.prepare_ip_adapter_image_embeds(
542
+ ip_adapter_image,
543
+ ip_adapter_image_embeds,
544
+ device,
545
+ batch_size * num_images_per_prompt,
546
+ self.do_classifier_free_guidance,
547
+ )
548
+
549
+ # 4. Prepare image
550
+ if isinstance(controlnet, RBLNControlNetModel):
551
+ image = self.prepare_image(
552
+ image=image,
553
+ width=width,
554
+ height=height,
555
+ batch_size=batch_size * num_images_per_prompt,
556
+ num_images_per_prompt=num_images_per_prompt,
557
+ device=device,
558
+ dtype=controlnet.dtype,
559
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
560
+ guess_mode=guess_mode,
561
+ )
562
+ height, width = image.shape[-2:]
563
+ elif isinstance(controlnet, RBLNMultiControlNetModel):
564
+ images = []
565
+
566
+ for image_ in image:
567
+ image_ = self.prepare_image(
568
+ image=image_,
569
+ width=width,
570
+ height=height,
571
+ batch_size=batch_size * num_images_per_prompt,
572
+ num_images_per_prompt=num_images_per_prompt,
573
+ device=device,
574
+ dtype=controlnet.dtype,
575
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
576
+ guess_mode=guess_mode,
577
+ )
578
+
579
+ images.append(image_)
580
+
581
+ image = images
582
+ height, width = image[0].shape[-2:]
583
+ else:
584
+ assert False
585
+
586
+ # 5. Prepare timesteps
587
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
588
+ timesteps = self.scheduler.timesteps
589
+ self._num_timesteps = len(timesteps)
590
+
591
+ # 6. Prepare latent variables
592
+ num_channels_latents = self.unet.config.in_channels
593
+ latents = self.prepare_latents(
594
+ batch_size * num_images_per_prompt,
595
+ num_channels_latents,
596
+ height,
597
+ width,
598
+ prompt_embeds.dtype,
599
+ device,
600
+ generator,
601
+ latents,
602
+ )
603
+
604
+ # 6.5 Optionally get Guidance Scale Embedding
605
+ timestep_cond = None
606
+ if self.unet.config.time_cond_proj_dim is not None:
607
+ guidance_scale_tensor = torch.tensor(self.guidance_scale - 1).repeat(batch_size * num_images_per_prompt)
608
+ timestep_cond = self.get_guidance_scale_embedding(
609
+ guidance_scale_tensor, embedding_dim=self.unet.config.time_cond_proj_dim
610
+ ).to(device=device, dtype=latents.dtype)
611
+
612
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
613
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
614
+
615
+ # 7.1 Create tensor stating which controlnets to keep
616
+ controlnet_keep = []
617
+ for i in range(len(timesteps)):
618
+ keeps = [
619
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
620
+ for s, e in zip(control_guidance_start, control_guidance_end)
621
+ ]
622
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, RBLNControlNetModel) else keeps)
623
+
624
+ # 7.2 Prepare added time ids & embeddings
625
+ if isinstance(image, list):
626
+ original_size = original_size or image[0].shape[-2:]
627
+ else:
628
+ original_size = original_size or image.shape[-2:]
629
+ target_size = target_size or (height, width)
630
+
631
+ add_text_embeds = pooled_prompt_embeds
632
+ if self.text_encoder_2 is None:
633
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
634
+ else:
635
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
636
+
637
+ add_time_ids = self._get_add_time_ids(
638
+ original_size,
639
+ crops_coords_top_left,
640
+ target_size,
641
+ dtype=prompt_embeds.dtype,
642
+ text_encoder_projection_dim=text_encoder_projection_dim,
643
+ )
644
+
645
+ if negative_original_size is not None and negative_target_size is not None:
646
+ negative_add_time_ids = self._get_add_time_ids(
647
+ negative_original_size,
648
+ negative_crops_coords_top_left,
649
+ negative_target_size,
650
+ dtype=prompt_embeds.dtype,
651
+ text_encoder_projection_dim=text_encoder_projection_dim,
652
+ )
653
+ else:
654
+ negative_add_time_ids = add_time_ids
655
+
656
+ if self.do_classifier_free_guidance:
657
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
658
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
659
+ add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
660
+
661
+ prompt_embeds = prompt_embeds.to(device)
662
+ add_text_embeds = add_text_embeds.to(device)
663
+ add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
664
+
665
+ # 8. Denoising loop
666
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
667
+
668
+ # 8.1 Apply denoising_end
669
+ if (
670
+ self.denoising_end is not None
671
+ and isinstance(self.denoising_end, float)
672
+ and self.denoising_end > 0
673
+ and self.denoising_end < 1
674
+ ):
675
+ discrete_timestep_cutoff = int(
676
+ round(
677
+ self.scheduler.config.num_train_timesteps
678
+ - (self.denoising_end * self.scheduler.config.num_train_timesteps)
679
+ )
680
+ )
681
+ num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
682
+ timesteps = timesteps[:num_inference_steps]
683
+
684
+ is_unet_compiled = is_compiled_module(self.unet)
685
+ is_controlnet_compiled = is_compiled_module(self.controlnet)
686
+ is_torch_higher_equal_2_1 = is_torch_version(">=", "2.1")
687
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
688
+ for i, t in enumerate(timesteps):
689
+ # Relevant thread:
690
+ # https://dev-discuss.pytorch.org/t/cudagraphs-in-pytorch-2-0/1428
691
+ if (is_unet_compiled and is_controlnet_compiled) and is_torch_higher_equal_2_1:
692
+ torch._inductor.cudagraph_mark_step_begin()
693
+ # expand the latents if we are doing classifier free guidance
694
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
695
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
696
+
697
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
698
+
699
+ # controlnet(s) inference
700
+ if guess_mode and self.do_classifier_free_guidance:
701
+ # Infer ControlNet only for the conditional batch.
702
+ control_model_input = latents
703
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
704
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
705
+ controlnet_added_cond_kwargs = {
706
+ "text_embeds": add_text_embeds.chunk(2)[1],
707
+ "time_ids": add_time_ids.chunk(2)[1],
708
+ }
709
+ else:
710
+ control_model_input = latent_model_input
711
+ controlnet_prompt_embeds = prompt_embeds
712
+ controlnet_added_cond_kwargs = added_cond_kwargs
713
+
714
+ if isinstance(controlnet_keep[i], list):
715
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
716
+ else:
717
+ controlnet_cond_scale = controlnet_conditioning_scale
718
+ if isinstance(controlnet_cond_scale, list):
719
+ controlnet_cond_scale = controlnet_cond_scale[0]
720
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
721
+
722
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
723
+ control_model_input,
724
+ t,
725
+ encoder_hidden_states=controlnet_prompt_embeds,
726
+ controlnet_cond=image,
727
+ conditioning_scale=cond_scale,
728
+ guess_mode=guess_mode,
729
+ added_cond_kwargs=controlnet_added_cond_kwargs,
730
+ return_dict=False,
731
+ )
732
+
733
+ if guess_mode and self.do_classifier_free_guidance:
734
+ # Infered ControlNet only for the conditional batch.
735
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
736
+ # add 0 to the unconditional batch to keep it unchanged.
737
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
738
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
739
+
740
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
741
+ added_cond_kwargs["image_embeds"] = image_embeds
742
+
743
+ # predict the noise residual
744
+ noise_pred = self.unet(
745
+ latent_model_input,
746
+ t,
747
+ encoder_hidden_states=prompt_embeds,
748
+ timestep_cond=timestep_cond,
749
+ cross_attention_kwargs=self.cross_attention_kwargs,
750
+ down_block_additional_residuals=down_block_res_samples,
751
+ mid_block_additional_residual=mid_block_res_sample,
752
+ added_cond_kwargs=added_cond_kwargs,
753
+ return_dict=False,
754
+ )[0]
755
+
756
+ # perform guidance
757
+ if self.do_classifier_free_guidance:
758
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
759
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
760
+
761
+ # compute the previous noisy sample x_t -> x_t-1
762
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
763
+
764
+ if callback_on_step_end is not None:
765
+ callback_kwargs = {}
766
+ for k in callback_on_step_end_tensor_inputs:
767
+ callback_kwargs[k] = locals()[k]
768
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
769
+
770
+ latents = callback_outputs.pop("latents", latents)
771
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
772
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
773
+
774
+ # call the callback, if provided
775
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
776
+ progress_bar.update()
777
+ if callback is not None and i % callback_steps == 0:
778
+ step_idx = i // getattr(self.scheduler, "order", 1)
779
+ callback(step_idx, t, latents)
780
+
781
+ if not output_type == "latent":
782
+ # make sure the VAE is in float32 mode, as it overflows in float16
783
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
784
+
785
+ if needs_upcasting:
786
+ self.upcast_vae()
787
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
788
+
789
+ # unscale/denormalize the latents
790
+ # denormalize with the mean and std if available and not None
791
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
792
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
793
+ if has_latents_mean and has_latents_std:
794
+ latents_mean = (
795
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
796
+ )
797
+ latents_std = (
798
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
799
+ )
800
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
801
+ else:
802
+ latents = latents / self.vae.config.scaling_factor
803
+
804
+ image = self.vae.decode(latents, return_dict=False)[0]
805
+
806
+ # cast back to fp16 if needed
807
+ if needs_upcasting:
808
+ self.vae.to(dtype=torch.float16)
809
+ else:
810
+ image = latents
811
+
812
+ if not output_type == "latent":
813
+ # apply watermark if available
814
+ if self.watermark is not None:
815
+ image = self.watermark.apply_watermark(image)
816
+
817
+ image = self.image_processor.postprocess(image, output_type=output_type)
818
+
819
+ # Offload all models
820
+ self.maybe_free_model_hooks()
821
+
822
+ if not return_dict:
823
+ return (image,)
824
+
825
+ return StableDiffusionXLPipelineOutput(images=image)