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,837 @@
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 StableDiffusionXLControlNetImg2ImgPipeline
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
38
+
39
+ from ....utils.decorator_utils import remove_compile_time_kwargs
40
+ from ...configurations import RBLNStableDiffusionXLControlNetImg2ImgPipelineConfig
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 RBLNStableDiffusionXLControlNetImg2ImgPipeline(RBLNDiffusionMixin, StableDiffusionXLControlNetImg2ImgPipeline):
50
+ """
51
+ RBLN-accelerated implementation of Stable Diffusion XL pipeline with ControlNet for high-resolution guided image-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 transforming input images with precise structural control and enhanced quality preservation.
55
+ """
56
+
57
+ original_class = StableDiffusionXLControlNetImg2ImgPipeline
58
+ _rbln_config_class = RBLNStableDiffusionXLControlNetImg2ImgPipelineConfig
59
+ _submodules = ["text_encoder", "text_encoder_2", "unet", "vae", "controlnet"]
60
+
61
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl_img2img.py
62
+ def check_inputs(
63
+ self,
64
+ prompt,
65
+ prompt_2,
66
+ image,
67
+ strength,
68
+ num_inference_steps,
69
+ callback_steps,
70
+ negative_prompt=None,
71
+ negative_prompt_2=None,
72
+ prompt_embeds=None,
73
+ negative_prompt_embeds=None,
74
+ pooled_prompt_embeds=None,
75
+ negative_pooled_prompt_embeds=None,
76
+ ip_adapter_image=None,
77
+ ip_adapter_image_embeds=None,
78
+ controlnet_conditioning_scale=1.0,
79
+ control_guidance_start=0.0,
80
+ control_guidance_end=1.0,
81
+ callback_on_step_end_tensor_inputs=None,
82
+ ):
83
+ if strength < 0 or strength > 1:
84
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
85
+ if num_inference_steps is None:
86
+ raise ValueError("`num_inference_steps` cannot be None.")
87
+ elif not isinstance(num_inference_steps, int) or num_inference_steps <= 0:
88
+ raise ValueError(
89
+ f"`num_inference_steps` has to be a positive integer but is {num_inference_steps} of type"
90
+ f" {type(num_inference_steps)}."
91
+ )
92
+
93
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
94
+ raise ValueError(
95
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
96
+ f" {type(callback_steps)}."
97
+ )
98
+
99
+ if callback_on_step_end_tensor_inputs is not None and not all(
100
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
101
+ ):
102
+ raise ValueError(
103
+ 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]}"
104
+ )
105
+
106
+ if prompt is not None and prompt_embeds is not None:
107
+ raise ValueError(
108
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
109
+ " only forward one of the two."
110
+ )
111
+ elif prompt_2 is not None and prompt_embeds is not None:
112
+ raise ValueError(
113
+ f"Cannot forward both `prompt_2`: {prompt_2} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
114
+ " only forward one of the two."
115
+ )
116
+ elif prompt is None and prompt_embeds is None:
117
+ raise ValueError(
118
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
119
+ )
120
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
121
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
122
+ elif prompt_2 is not None and (not isinstance(prompt_2, str) and not isinstance(prompt_2, list)):
123
+ raise ValueError(f"`prompt_2` has to be of type `str` or `list` but is {type(prompt_2)}")
124
+
125
+ if negative_prompt is not None and negative_prompt_embeds is not None:
126
+ raise ValueError(
127
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
128
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
129
+ )
130
+ elif negative_prompt_2 is not None and negative_prompt_embeds is not None:
131
+ raise ValueError(
132
+ f"Cannot forward both `negative_prompt_2`: {negative_prompt_2} and `negative_prompt_embeds`:"
133
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
134
+ )
135
+
136
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
137
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
138
+ raise ValueError(
139
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
140
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
141
+ f" {negative_prompt_embeds.shape}."
142
+ )
143
+
144
+ if prompt_embeds is not None and pooled_prompt_embeds is None:
145
+ raise ValueError(
146
+ "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`."
147
+ )
148
+
149
+ if negative_prompt_embeds is not None and negative_pooled_prompt_embeds is None:
150
+ raise ValueError(
151
+ "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`."
152
+ )
153
+
154
+ # `prompt` needs more sophisticated handling when there are multiple
155
+ # conditionings.
156
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
157
+ if isinstance(prompt, list):
158
+ logger.warning(
159
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
160
+ " prompts. The conditionings will be fixed across the prompts."
161
+ )
162
+
163
+ # Check `image`
164
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
165
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
166
+ )
167
+ if (
168
+ isinstance(self.controlnet, RBLNControlNetModel)
169
+ or is_compiled
170
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
171
+ ):
172
+ self.check_image(image, prompt, prompt_embeds)
173
+ elif (
174
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
175
+ or is_compiled
176
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
177
+ ):
178
+ if not isinstance(image, list):
179
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
180
+
181
+ # When `image` is a nested list:
182
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
183
+ elif any(isinstance(i, list) for i in image):
184
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
185
+ elif len(image) != len(self.controlnet.nets):
186
+ raise ValueError(
187
+ 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."
188
+ )
189
+
190
+ for image_ in image:
191
+ self.check_image(image_, prompt, prompt_embeds)
192
+ else:
193
+ assert False
194
+
195
+ # Check `controlnet_conditioning_scale`
196
+ if (
197
+ isinstance(self.controlnet, RBLNControlNetModel)
198
+ or is_compiled
199
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
200
+ ):
201
+ if not isinstance(controlnet_conditioning_scale, float):
202
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
203
+ elif (
204
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
205
+ or is_compiled
206
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
207
+ ):
208
+ if isinstance(controlnet_conditioning_scale, list):
209
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
210
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
211
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
212
+ self.controlnet.nets
213
+ ):
214
+ raise ValueError(
215
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
216
+ " the same length as the number of controlnets"
217
+ )
218
+ else:
219
+ assert False
220
+
221
+ if not isinstance(control_guidance_start, (tuple, list)):
222
+ control_guidance_start = [control_guidance_start]
223
+
224
+ if not isinstance(control_guidance_end, (tuple, list)):
225
+ control_guidance_end = [control_guidance_end]
226
+
227
+ if len(control_guidance_start) != len(control_guidance_end):
228
+ raise ValueError(
229
+ 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."
230
+ )
231
+
232
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
233
+ if len(control_guidance_start) != len(self.controlnet.nets):
234
+ raise ValueError(
235
+ 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)}."
236
+ )
237
+
238
+ for start, end in zip(control_guidance_start, control_guidance_end):
239
+ if start >= end:
240
+ raise ValueError(
241
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
242
+ )
243
+ if start < 0.0:
244
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
245
+ if end > 1.0:
246
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
247
+
248
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
249
+ raise ValueError(
250
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
251
+ )
252
+
253
+ if ip_adapter_image_embeds is not None:
254
+ if not isinstance(ip_adapter_image_embeds, list):
255
+ raise ValueError(
256
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
257
+ )
258
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
259
+ raise ValueError(
260
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
261
+ )
262
+
263
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_sd_xl_img2img.py
264
+ @torch.no_grad()
265
+ @remove_compile_time_kwargs
266
+ def __call__(
267
+ self,
268
+ prompt: Union[str, List[str]] = None,
269
+ prompt_2: Optional[Union[str, List[str]]] = None,
270
+ image: PipelineImageInput = None,
271
+ control_image: PipelineImageInput = None,
272
+ height: Optional[int] = None,
273
+ width: Optional[int] = None,
274
+ strength: float = 0.8,
275
+ num_inference_steps: int = 50,
276
+ guidance_scale: float = 5.0,
277
+ negative_prompt: Optional[Union[str, List[str]]] = None,
278
+ negative_prompt_2: Optional[Union[str, List[str]]] = None,
279
+ num_images_per_prompt: Optional[int] = 1,
280
+ eta: float = 0.0,
281
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
282
+ latents: Optional[torch.FloatTensor] = None,
283
+ prompt_embeds: Optional[torch.FloatTensor] = None,
284
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
285
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
286
+ negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
287
+ ip_adapter_image: Optional[PipelineImageInput] = None,
288
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
289
+ output_type: Optional[str] = "pil",
290
+ return_dict: bool = True,
291
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
292
+ controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
293
+ guess_mode: bool = False,
294
+ control_guidance_start: Union[float, List[float]] = 0.0,
295
+ control_guidance_end: Union[float, List[float]] = 1.0,
296
+ original_size: Tuple[int, int] = None,
297
+ crops_coords_top_left: Tuple[int, int] = (0, 0),
298
+ target_size: Tuple[int, int] = None,
299
+ negative_original_size: Optional[Tuple[int, int]] = None,
300
+ negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
301
+ negative_target_size: Optional[Tuple[int, int]] = None,
302
+ aesthetic_score: float = 6.0,
303
+ negative_aesthetic_score: float = 2.5,
304
+ clip_skip: Optional[int] = None,
305
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
306
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
307
+ **kwargs,
308
+ ):
309
+ r"""
310
+ Function invoked when calling the pipeline for generation.
311
+
312
+ Args:
313
+ prompt (`str` or `List[str]`, *optional*):
314
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
315
+ instead.
316
+ prompt_2 (`str` or `List[str]`, *optional*):
317
+ The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
318
+ used in both text-encoders
319
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
320
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
321
+ The initial image will be used as the starting point for the image generation process. Can also accept
322
+ image latents as `image`, if passing latents directly, it will not be encoded again.
323
+ control_image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
324
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
325
+ The ControlNet input condition. ControlNet uses this input condition to generate guidance to Unet. If
326
+ the type is specified as `Torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can
327
+ also be accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If
328
+ height and/or width are passed, `image` is resized according to them. If multiple ControlNets are
329
+ specified in init, images must be passed as a list such that each element of the list can be correctly
330
+ batched for input to a single controlnet.
331
+ height (`int`, *optional*, defaults to the size of control_image):
332
+ The height in pixels of the generated image. Anything below 512 pixels won't work well for
333
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
334
+ and checkpoints that are not specifically fine-tuned on low resolutions.
335
+ width (`int`, *optional*, defaults to the size of control_image):
336
+ The width in pixels of the generated image. Anything below 512 pixels won't work well for
337
+ [stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
338
+ and checkpoints that are not specifically fine-tuned on low resolutions.
339
+ strength (`float`, *optional*, defaults to 0.8):
340
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
341
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
342
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
343
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
344
+ essentially ignores `image`.
345
+ num_inference_steps (`int`, *optional*, defaults to 50):
346
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
347
+ expense of slower inference.
348
+ guidance_scale (`float`, *optional*, defaults to 7.5):
349
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
350
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
351
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
352
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
353
+ usually at the expense of lower image quality.
354
+ negative_prompt (`str` or `List[str]`, *optional*):
355
+ The prompt or prompts not to guide the image generation. If not defined, one has to pass
356
+ `negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
357
+ less than `1`).
358
+ negative_prompt_2 (`str` or `List[str]`, *optional*):
359
+ The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
360
+ `text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
361
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
362
+ The number of images to generate per prompt.
363
+ eta (`float`, *optional*, defaults to 0.0):
364
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
365
+ [`schedulers.DDIMScheduler`], will be ignored for others.
366
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
367
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
368
+ to make generation deterministic.
369
+ latents (`torch.FloatTensor`, *optional*):
370
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
371
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
372
+ tensor will ge generated by sampling using the supplied random `generator`.
373
+ prompt_embeds (`torch.FloatTensor`, *optional*):
374
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
375
+ provided, text embeddings will be generated from `prompt` input argument.
376
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
377
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
378
+ weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
379
+ argument.
380
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
381
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
382
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
383
+ negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
384
+ Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
385
+ weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
386
+ input argument.
387
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
388
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
389
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
390
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
391
+ if `do_classifier_free_guidance` is set to `True`.
392
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
393
+ output_type (`str`, *optional*, defaults to `"pil"`):
394
+ The output format of the generate image. Choose between
395
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
396
+ return_dict (`bool`, *optional*, defaults to `True`):
397
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
398
+ plain tuple.
399
+ cross_attention_kwargs (`dict`, *optional*):
400
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
401
+ `self.processor` in
402
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
403
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
404
+ The outputs of the controlnet are multiplied by `controlnet_conditioning_scale` before they are added
405
+ to the residual in the original unet. If multiple ControlNets are specified in init, you can set the
406
+ corresponding scale as a list.
407
+ guess_mode (`bool`, *optional*, defaults to `False`):
408
+ In this mode, the ControlNet encoder will try best to recognize the content of the input image even if
409
+ you remove all prompts. The `guidance_scale` between 3.0 and 5.0 is recommended.
410
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
411
+ The percentage of total steps at which the controlnet starts applying.
412
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
413
+ The percentage of total steps at which the controlnet stops applying.
414
+ original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
415
+ If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
416
+ `original_size` defaults to `(height, width)` if not specified. Part of SDXL's micro-conditioning as
417
+ explained in section 2.2 of
418
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
419
+ crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
420
+ `crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
421
+ `crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
422
+ `crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
423
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
424
+ target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
425
+ For most cases, `target_size` should be set to the desired height and width of the generated image. If
426
+ not specified it will default to `(height, width)`. Part of SDXL's micro-conditioning as explained in
427
+ section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
428
+ negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
429
+ To negatively condition the generation process based on a specific image resolution. Part of SDXL's
430
+ micro-conditioning as explained in section 2.2 of
431
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
432
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
433
+ negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
434
+ To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
435
+ micro-conditioning as explained in section 2.2 of
436
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
437
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
438
+ negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
439
+ To negatively condition the generation process based on a target image resolution. It should be as same
440
+ as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
441
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
442
+ information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
443
+ aesthetic_score (`float`, *optional*, defaults to 6.0):
444
+ Used to simulate an aesthetic score of the generated image by influencing the positive text condition.
445
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
446
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
447
+ negative_aesthetic_score (`float`, *optional*, defaults to 2.5):
448
+ Part of SDXL's micro-conditioning as explained in section 2.2 of
449
+ [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). Can be used to
450
+ simulate an aesthetic score of the generated image by influencing the negative text condition.
451
+ clip_skip (`int`, *optional*):
452
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
453
+ the output of the pre-final layer will be used for computing the prompt embeddings.
454
+ callback_on_step_end (`Callable`, *optional*):
455
+ A function that calls at the end of each denoising steps during the inference. The function is called
456
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
457
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
458
+ `callback_on_step_end_tensor_inputs`.
459
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
460
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
461
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
462
+ `._callback_tensor_inputs` attribute of your pipeine class.
463
+
464
+ Examples:
465
+
466
+ Returns:
467
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
468
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple`
469
+ containing the output images.
470
+ """
471
+
472
+ callback = kwargs.pop("callback", None)
473
+ callback_steps = kwargs.pop("callback_steps", None)
474
+
475
+ if callback is not None:
476
+ deprecate(
477
+ "callback",
478
+ "1.0.0",
479
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
480
+ )
481
+ if callback_steps is not None:
482
+ deprecate(
483
+ "callback_steps",
484
+ "1.0.0",
485
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
486
+ )
487
+
488
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
489
+
490
+ # align format for control guidance
491
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
492
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
493
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
494
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
495
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
496
+ mult = len(controlnet.nets) if isinstance(controlnet, RBLNMultiControlNetModel) else 1
497
+ control_guidance_start, control_guidance_end = (
498
+ mult * [control_guidance_start],
499
+ mult * [control_guidance_end],
500
+ )
501
+
502
+ # 1. Check inputs. Raise error if not correct
503
+ self.check_inputs(
504
+ prompt,
505
+ prompt_2,
506
+ control_image,
507
+ strength,
508
+ num_inference_steps,
509
+ callback_steps,
510
+ negative_prompt,
511
+ negative_prompt_2,
512
+ prompt_embeds,
513
+ negative_prompt_embeds,
514
+ pooled_prompt_embeds,
515
+ negative_pooled_prompt_embeds,
516
+ ip_adapter_image,
517
+ ip_adapter_image_embeds,
518
+ controlnet_conditioning_scale,
519
+ control_guidance_start,
520
+ control_guidance_end,
521
+ callback_on_step_end_tensor_inputs,
522
+ )
523
+
524
+ self._guidance_scale = guidance_scale
525
+ self._clip_skip = clip_skip
526
+ self._cross_attention_kwargs = cross_attention_kwargs
527
+
528
+ # 2. Define call parameters
529
+ if prompt is not None and isinstance(prompt, str):
530
+ batch_size = 1
531
+ elif prompt is not None and isinstance(prompt, list):
532
+ batch_size = len(prompt)
533
+ else:
534
+ batch_size = prompt_embeds.shape[0]
535
+
536
+ device = self._execution_device
537
+
538
+ if isinstance(controlnet, RBLNMultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
539
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
540
+
541
+ global_pool_conditions = (
542
+ controlnet.config.global_pool_conditions
543
+ if isinstance(controlnet, RBLNControlNetModel)
544
+ else controlnet.nets[0].config.global_pool_conditions
545
+ )
546
+ guess_mode = guess_mode or global_pool_conditions
547
+
548
+ # 3.1. Encode input prompt
549
+ text_encoder_lora_scale = (
550
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
551
+ )
552
+
553
+ (
554
+ prompt_embeds,
555
+ negative_prompt_embeds,
556
+ pooled_prompt_embeds,
557
+ negative_pooled_prompt_embeds,
558
+ ) = self.encode_prompt(
559
+ prompt,
560
+ prompt_2,
561
+ device,
562
+ num_images_per_prompt,
563
+ self.do_classifier_free_guidance,
564
+ negative_prompt,
565
+ negative_prompt_2,
566
+ prompt_embeds=prompt_embeds,
567
+ negative_prompt_embeds=negative_prompt_embeds,
568
+ pooled_prompt_embeds=pooled_prompt_embeds,
569
+ negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
570
+ lora_scale=text_encoder_lora_scale,
571
+ clip_skip=self.clip_skip,
572
+ )
573
+
574
+ # 3.2 Encode ip_adapter_image
575
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
576
+ image_embeds = self.prepare_ip_adapter_image_embeds(
577
+ ip_adapter_image,
578
+ ip_adapter_image_embeds,
579
+ device,
580
+ batch_size * num_images_per_prompt,
581
+ self.do_classifier_free_guidance,
582
+ )
583
+
584
+ # 4. Prepare image and controlnet_conditioning_image
585
+ image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
586
+
587
+ if isinstance(controlnet, RBLNControlNetModel):
588
+ control_image = self.prepare_control_image(
589
+ image=control_image,
590
+ width=width,
591
+ height=height,
592
+ batch_size=batch_size * num_images_per_prompt,
593
+ num_images_per_prompt=num_images_per_prompt,
594
+ device=device,
595
+ dtype=controlnet.dtype,
596
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
597
+ guess_mode=guess_mode,
598
+ )
599
+ height, width = control_image.shape[-2:]
600
+ elif isinstance(controlnet, RBLNMultiControlNetModel):
601
+ control_images = []
602
+
603
+ for control_image_ in control_image:
604
+ control_image_ = self.prepare_control_image(
605
+ image=control_image_,
606
+ width=width,
607
+ height=height,
608
+ batch_size=batch_size * num_images_per_prompt,
609
+ num_images_per_prompt=num_images_per_prompt,
610
+ device=device,
611
+ dtype=controlnet.dtype,
612
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
613
+ guess_mode=guess_mode,
614
+ )
615
+
616
+ control_images.append(control_image_)
617
+
618
+ control_image = control_images
619
+ height, width = control_image[0].shape[-2:]
620
+ else:
621
+ assert False
622
+
623
+ # 5. Prepare timesteps
624
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
625
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
626
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
627
+ self._num_timesteps = len(timesteps)
628
+
629
+ # 6. Prepare latent variables
630
+ latents = self.prepare_latents(
631
+ image,
632
+ latent_timestep,
633
+ batch_size,
634
+ num_images_per_prompt,
635
+ prompt_embeds.dtype,
636
+ device,
637
+ generator,
638
+ True,
639
+ )
640
+
641
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
642
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
643
+
644
+ # 7.1 Create tensor stating which controlnets to keep
645
+ controlnet_keep = []
646
+ for i in range(len(timesteps)):
647
+ keeps = [
648
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
649
+ for s, e in zip(control_guidance_start, control_guidance_end)
650
+ ]
651
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, RBLNControlNetModel) else keeps)
652
+
653
+ # 7.2 Prepare added time ids & embeddings
654
+ if isinstance(control_image, list):
655
+ original_size = original_size or control_image[0].shape[-2:]
656
+ else:
657
+ original_size = original_size or control_image.shape[-2:]
658
+ target_size = target_size or (height, width)
659
+
660
+ if negative_original_size is None:
661
+ negative_original_size = original_size
662
+ if negative_target_size is None:
663
+ negative_target_size = target_size
664
+ add_text_embeds = pooled_prompt_embeds
665
+
666
+ if self.text_encoder_2 is None:
667
+ text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
668
+ else:
669
+ text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
670
+
671
+ add_time_ids, add_neg_time_ids = self._get_add_time_ids(
672
+ original_size,
673
+ crops_coords_top_left,
674
+ target_size,
675
+ aesthetic_score,
676
+ negative_aesthetic_score,
677
+ negative_original_size,
678
+ negative_crops_coords_top_left,
679
+ negative_target_size,
680
+ dtype=prompt_embeds.dtype,
681
+ text_encoder_projection_dim=text_encoder_projection_dim,
682
+ )
683
+ add_time_ids = add_time_ids.repeat(batch_size * num_images_per_prompt, 1)
684
+
685
+ if self.do_classifier_free_guidance:
686
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
687
+ add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
688
+ add_neg_time_ids = add_neg_time_ids.repeat(batch_size * num_images_per_prompt, 1)
689
+ add_time_ids = torch.cat([add_neg_time_ids, add_time_ids], dim=0)
690
+
691
+ prompt_embeds = prompt_embeds.to(device)
692
+ add_text_embeds = add_text_embeds.to(device)
693
+ add_time_ids = add_time_ids.to(device)
694
+
695
+ # 8. Denoising loop
696
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
697
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
698
+ for i, t in enumerate(timesteps):
699
+ # expand the latents if we are doing classifier free guidance
700
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
701
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
702
+
703
+ added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
704
+
705
+ # controlnet(s) inference
706
+ if guess_mode and self.do_classifier_free_guidance:
707
+ # Infer ControlNet only for the conditional batch.
708
+ control_model_input = latents
709
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
710
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
711
+ controlnet_added_cond_kwargs = {
712
+ "text_embeds": add_text_embeds.chunk(2)[1],
713
+ "time_ids": add_time_ids.chunk(2)[1],
714
+ }
715
+ else:
716
+ control_model_input = latent_model_input
717
+ controlnet_prompt_embeds = prompt_embeds
718
+ controlnet_added_cond_kwargs = added_cond_kwargs
719
+
720
+ if isinstance(controlnet_keep[i], list):
721
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
722
+ else:
723
+ controlnet_cond_scale = controlnet_conditioning_scale
724
+ if isinstance(controlnet_cond_scale, list):
725
+ controlnet_cond_scale = controlnet_cond_scale[0]
726
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
727
+
728
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
729
+ control_model_input,
730
+ t,
731
+ encoder_hidden_states=controlnet_prompt_embeds,
732
+ controlnet_cond=control_image,
733
+ conditioning_scale=cond_scale,
734
+ guess_mode=guess_mode,
735
+ added_cond_kwargs=controlnet_added_cond_kwargs,
736
+ return_dict=False,
737
+ )
738
+
739
+ if guess_mode and self.do_classifier_free_guidance:
740
+ # Infered ControlNet only for the conditional batch.
741
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
742
+ # add 0 to the unconditional batch to keep it unchanged.
743
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
744
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
745
+
746
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
747
+ added_cond_kwargs["image_embeds"] = image_embeds
748
+
749
+ # predict the noise residual
750
+ noise_pred = self.unet(
751
+ latent_model_input,
752
+ t,
753
+ encoder_hidden_states=prompt_embeds,
754
+ cross_attention_kwargs=self.cross_attention_kwargs,
755
+ down_block_additional_residuals=down_block_res_samples,
756
+ mid_block_additional_residual=mid_block_res_sample,
757
+ added_cond_kwargs=added_cond_kwargs,
758
+ return_dict=False,
759
+ )[0]
760
+
761
+ # perform guidance
762
+ if self.do_classifier_free_guidance:
763
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
764
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
765
+
766
+ # compute the previous noisy sample x_t -> x_t-1
767
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
768
+
769
+ if callback_on_step_end is not None:
770
+ callback_kwargs = {}
771
+ for k in callback_on_step_end_tensor_inputs:
772
+ callback_kwargs[k] = locals()[k]
773
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
774
+
775
+ latents = callback_outputs.pop("latents", latents)
776
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
777
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
778
+
779
+ # call the callback, if provided
780
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
781
+ progress_bar.update()
782
+ if callback is not None and i % callback_steps == 0:
783
+ step_idx = i // getattr(self.scheduler, "order", 1)
784
+ callback(step_idx, t, latents)
785
+
786
+ # If we do sequential model offloading, let's offload unet and controlnet
787
+ # manually for max memory savings
788
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
789
+ self.unet.to("cpu")
790
+ self.controlnet.to("cpu")
791
+ torch.cuda.empty_cache()
792
+
793
+ if not output_type == "latent":
794
+ # make sure the VAE is in float32 mode, as it overflows in float16
795
+ needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
796
+
797
+ if needs_upcasting:
798
+ self.upcast_vae()
799
+ latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
800
+
801
+ # unscale/denormalize the latents
802
+ # denormalize with the mean and std if available and not None
803
+ has_latents_mean = hasattr(self.vae.config, "latents_mean") and self.vae.config.latents_mean is not None
804
+ has_latents_std = hasattr(self.vae.config, "latents_std") and self.vae.config.latents_std is not None
805
+ if has_latents_mean and has_latents_std:
806
+ latents_mean = (
807
+ torch.tensor(self.vae.config.latents_mean).view(1, 4, 1, 1).to(latents.device, latents.dtype)
808
+ )
809
+ latents_std = (
810
+ torch.tensor(self.vae.config.latents_std).view(1, 4, 1, 1).to(latents.device, latents.dtype)
811
+ )
812
+ latents = latents * latents_std / self.vae.config.scaling_factor + latents_mean
813
+ else:
814
+ latents = latents / self.vae.config.scaling_factor
815
+
816
+ image = self.vae.decode(latents, return_dict=False)[0]
817
+
818
+ # cast back to fp16 if needed
819
+ if needs_upcasting:
820
+ self.vae.to(dtype=torch.float16)
821
+ else:
822
+ image = latents
823
+ return StableDiffusionXLPipelineOutput(images=image)
824
+
825
+ # apply watermark if available
826
+ if self.watermark is not None:
827
+ image = self.watermark.apply_watermark(image)
828
+
829
+ image = self.image_processor.postprocess(image, output_type=output_type)
830
+
831
+ # Offload all models
832
+ self.maybe_free_model_hooks()
833
+
834
+ if not return_dict:
835
+ return (image,)
836
+
837
+ return StableDiffusionXLPipelineOutput(images=image)