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,640 @@
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, Union
30
+
31
+ import torch
32
+ import torch.nn.functional as F
33
+ from diffusers import StableDiffusionControlNetImg2ImgPipeline
34
+ from diffusers.image_processor import PipelineImageInput
35
+ from diffusers.pipelines.stable_diffusion import StableDiffusionPipelineOutput
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 RBLNStableDiffusionControlNetImg2ImgPipelineConfig
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 RBLNStableDiffusionControlNetImg2ImgPipeline(RBLNDiffusionMixin, StableDiffusionControlNetImg2ImgPipeline):
50
+ """
51
+ RBLN-accelerated implementation of Stable Diffusion pipeline with ControlNet for guided image-to-image generation.
52
+
53
+ This pipeline compiles Stable Diffusion and ControlNet models to run efficiently on RBLN NPUs, enabling high-performance
54
+ inference for transforming input images with precise structural control and conditioning guidance.
55
+ """
56
+
57
+ original_class = StableDiffusionControlNetImg2ImgPipeline
58
+ _submodules = ["text_encoder", "unet", "vae", "controlnet"]
59
+ _rbln_config_class = RBLNStableDiffusionControlNetImg2ImgPipelineConfig
60
+
61
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_img2img.py
62
+ def check_inputs(
63
+ self,
64
+ prompt,
65
+ image,
66
+ callback_steps,
67
+ negative_prompt=None,
68
+ prompt_embeds=None,
69
+ negative_prompt_embeds=None,
70
+ ip_adapter_image=None,
71
+ ip_adapter_image_embeds=None,
72
+ controlnet_conditioning_scale=1.0,
73
+ control_guidance_start=0.0,
74
+ control_guidance_end=1.0,
75
+ callback_on_step_end_tensor_inputs=None,
76
+ ):
77
+ if callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0):
78
+ raise ValueError(
79
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
80
+ f" {type(callback_steps)}."
81
+ )
82
+
83
+ if callback_on_step_end_tensor_inputs is not None and not all(
84
+ k in self._callback_tensor_inputs for k in callback_on_step_end_tensor_inputs
85
+ ):
86
+ raise ValueError(
87
+ 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]}"
88
+ )
89
+
90
+ if prompt is not None and prompt_embeds is not None:
91
+ raise ValueError(
92
+ f"Cannot forward both `prompt`: {prompt} and `prompt_embeds`: {prompt_embeds}. Please make sure to"
93
+ " only forward one of the two."
94
+ )
95
+ elif prompt is None and prompt_embeds is None:
96
+ raise ValueError(
97
+ "Provide either `prompt` or `prompt_embeds`. Cannot leave both `prompt` and `prompt_embeds` undefined."
98
+ )
99
+ elif prompt is not None and (not isinstance(prompt, str) and not isinstance(prompt, list)):
100
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
101
+
102
+ if negative_prompt is not None and negative_prompt_embeds is not None:
103
+ raise ValueError(
104
+ f"Cannot forward both `negative_prompt`: {negative_prompt} and `negative_prompt_embeds`:"
105
+ f" {negative_prompt_embeds}. Please make sure to only forward one of the two."
106
+ )
107
+
108
+ if prompt_embeds is not None and negative_prompt_embeds is not None:
109
+ if prompt_embeds.shape != negative_prompt_embeds.shape:
110
+ raise ValueError(
111
+ "`prompt_embeds` and `negative_prompt_embeds` must have the same shape when passed directly, but"
112
+ f" got: `prompt_embeds` {prompt_embeds.shape} != `negative_prompt_embeds`"
113
+ f" {negative_prompt_embeds.shape}."
114
+ )
115
+
116
+ # `prompt` needs more sophisticated handling when there are multiple
117
+ # conditionings.
118
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
119
+ if isinstance(prompt, list):
120
+ logger.warning(
121
+ f"You have {len(self.controlnet.nets)} ControlNets and you have passed {len(prompt)}"
122
+ " prompts. The conditionings will be fixed across the prompts."
123
+ )
124
+
125
+ # Check `image`
126
+ is_compiled = hasattr(F, "scaled_dot_product_attention") and isinstance(
127
+ self.controlnet, torch._dynamo.eval_frame.OptimizedModule
128
+ )
129
+ if (
130
+ isinstance(self.controlnet, RBLNControlNetModel)
131
+ or is_compiled
132
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
133
+ ):
134
+ self.check_image(image, prompt, prompt_embeds)
135
+ elif (
136
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
137
+ or is_compiled
138
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
139
+ ):
140
+ if not isinstance(image, list):
141
+ raise TypeError("For multiple controlnets: `image` must be type `list`")
142
+
143
+ # When `image` is a nested list:
144
+ # (e.g. [[canny_image_1, pose_image_1], [canny_image_2, pose_image_2]])
145
+ elif any(isinstance(i, list) for i in image):
146
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
147
+ elif len(image) != len(self.controlnet.nets):
148
+ raise ValueError(
149
+ 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."
150
+ )
151
+
152
+ for image_ in image:
153
+ self.check_image(image_, prompt, prompt_embeds)
154
+ else:
155
+ assert False
156
+
157
+ # Check `controlnet_conditioning_scale`
158
+ if (
159
+ isinstance(self.controlnet, RBLNControlNetModel)
160
+ or is_compiled
161
+ and isinstance(self.controlnet._orig_mod, RBLNControlNetModel)
162
+ ):
163
+ if not isinstance(controlnet_conditioning_scale, float):
164
+ raise TypeError("For single controlnet: `controlnet_conditioning_scale` must be type `float`.")
165
+ elif (
166
+ isinstance(self.controlnet, RBLNMultiControlNetModel)
167
+ or is_compiled
168
+ and isinstance(self.controlnet._orig_mod, RBLNMultiControlNetModel)
169
+ ):
170
+ if isinstance(controlnet_conditioning_scale, list):
171
+ if any(isinstance(i, list) for i in controlnet_conditioning_scale):
172
+ raise ValueError("A single batch of multiple conditionings are supported at the moment.")
173
+ elif isinstance(controlnet_conditioning_scale, list) and len(controlnet_conditioning_scale) != len(
174
+ self.controlnet.nets
175
+ ):
176
+ raise ValueError(
177
+ "For multiple controlnets: When `controlnet_conditioning_scale` is specified as `list`, it must have"
178
+ " the same length as the number of controlnets"
179
+ )
180
+ else:
181
+ assert False
182
+
183
+ if len(control_guidance_start) != len(control_guidance_end):
184
+ raise ValueError(
185
+ 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."
186
+ )
187
+
188
+ if isinstance(self.controlnet, RBLNMultiControlNetModel):
189
+ if len(control_guidance_start) != len(self.controlnet.nets):
190
+ raise ValueError(
191
+ 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)}."
192
+ )
193
+
194
+ for start, end in zip(control_guidance_start, control_guidance_end):
195
+ if start >= end:
196
+ raise ValueError(
197
+ f"control guidance start: {start} cannot be larger or equal to control guidance end: {end}."
198
+ )
199
+ if start < 0.0:
200
+ raise ValueError(f"control guidance start: {start} can't be smaller than 0.")
201
+ if end > 1.0:
202
+ raise ValueError(f"control guidance end: {end} can't be larger than 1.0.")
203
+
204
+ if ip_adapter_image is not None and ip_adapter_image_embeds is not None:
205
+ raise ValueError(
206
+ "Provide either `ip_adapter_image` or `ip_adapter_image_embeds`. Cannot leave both `ip_adapter_image` and `ip_adapter_image_embeds` defined."
207
+ )
208
+
209
+ if ip_adapter_image_embeds is not None:
210
+ if not isinstance(ip_adapter_image_embeds, list):
211
+ raise ValueError(
212
+ f"`ip_adapter_image_embeds` has to be of type `list` but is {type(ip_adapter_image_embeds)}"
213
+ )
214
+ elif ip_adapter_image_embeds[0].ndim not in [3, 4]:
215
+ raise ValueError(
216
+ f"`ip_adapter_image_embeds` has to be a list of 3D or 4D tensors but is {ip_adapter_image_embeds[0].ndim}D"
217
+ )
218
+
219
+ # Almost copied from diffusers.pipelines.controlnet.pipeline_controlnet_img2img.py
220
+ @torch.no_grad()
221
+ @remove_compile_time_kwargs
222
+ def __call__(
223
+ self,
224
+ prompt: Union[str, List[str]] = None,
225
+ image: PipelineImageInput = None,
226
+ control_image: PipelineImageInput = None,
227
+ height: Optional[int] = None,
228
+ width: Optional[int] = None,
229
+ strength: float = 0.8,
230
+ num_inference_steps: int = 50,
231
+ guidance_scale: float = 7.5,
232
+ negative_prompt: Optional[Union[str, List[str]]] = None,
233
+ num_images_per_prompt: Optional[int] = 1,
234
+ eta: float = 0.0,
235
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
236
+ latents: Optional[torch.FloatTensor] = None,
237
+ prompt_embeds: Optional[torch.FloatTensor] = None,
238
+ negative_prompt_embeds: Optional[torch.FloatTensor] = None,
239
+ ip_adapter_image: Optional[PipelineImageInput] = None,
240
+ ip_adapter_image_embeds: Optional[List[torch.FloatTensor]] = None,
241
+ output_type: Optional[str] = "pil",
242
+ return_dict: bool = True,
243
+ cross_attention_kwargs: Optional[Dict[str, Any]] = None,
244
+ controlnet_conditioning_scale: Union[float, List[float]] = 0.8,
245
+ guess_mode: bool = False,
246
+ control_guidance_start: Union[float, List[float]] = 0.0,
247
+ control_guidance_end: Union[float, List[float]] = 1.0,
248
+ clip_skip: Optional[int] = None,
249
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
250
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
251
+ **kwargs,
252
+ ):
253
+ r"""
254
+ The call function to the pipeline for generation.
255
+
256
+ Args:
257
+ prompt (`str` or `List[str]`, *optional*):
258
+ The prompt or prompts to guide image generation. If not defined, you need to pass `prompt_embeds`.
259
+ image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
260
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
261
+ The initial image to be used as the starting point for the image generation process. Can also accept
262
+ image latents as `image`, and if passing latents directly they are not encoded again.
263
+ control_image (`torch.FloatTensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.FloatTensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
264
+ `List[List[torch.FloatTensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
265
+ The ControlNet input condition to provide guidance to the `unet` for generation. If the type is
266
+ specified as `torch.FloatTensor`, it is passed to ControlNet as is. `PIL.Image.Image` can also be
267
+ accepted as an image. The dimensions of the output image defaults to `image`'s dimensions. If height
268
+ and/or width are passed, `image` is resized accordingly. If multiple ControlNets are specified in
269
+ `init`, images must be passed as a list such that each element of the list can be correctly batched for
270
+ input to a single ControlNet.
271
+ height (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
272
+ The height in pixels of the generated image.
273
+ width (`int`, *optional*, defaults to `self.unet.config.sample_size * self.vae_scale_factor`):
274
+ The width in pixels of the generated image.
275
+ strength (`float`, *optional*, defaults to 0.8):
276
+ Indicates extent to transform the reference `image`. Must be between 0 and 1. `image` is used as a
277
+ starting point and more noise is added the higher the `strength`. The number of denoising steps depends
278
+ on the amount of noise initially added. When `strength` is 1, added noise is maximum and the denoising
279
+ process runs for the full number of iterations specified in `num_inference_steps`. A value of 1
280
+ essentially ignores `image`.
281
+ num_inference_steps (`int`, *optional*, defaults to 50):
282
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
283
+ expense of slower inference.
284
+ guidance_scale (`float`, *optional*, defaults to 7.5):
285
+ A higher guidance scale value encourages the model to generate images closely linked to the text
286
+ `prompt` at the expense of lower image quality. Guidance scale is enabled when `guidance_scale > 1`.
287
+ negative_prompt (`str` or `List[str]`, *optional*):
288
+ The prompt or prompts to guide what to not include in image generation. If not defined, you need to
289
+ pass `negative_prompt_embeds` instead. Ignored when not using guidance (`guidance_scale < 1`).
290
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
291
+ The number of images to generate per prompt.
292
+ eta (`float`, *optional*, defaults to 0.0):
293
+ Corresponds to parameter eta (η) from the [DDIM](https://arxiv.org/abs/2010.02502) paper. Only applies
294
+ to the [`~schedulers.DDIMScheduler`], and is ignored in other schedulers.
295
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
296
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
297
+ generation deterministic.
298
+ latents (`torch.FloatTensor`, *optional*):
299
+ Pre-generated noisy latents sampled from a Gaussian distribution, to be used as inputs for image
300
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
301
+ tensor is generated by sampling using the supplied random `generator`.
302
+ prompt_embeds (`torch.FloatTensor`, *optional*):
303
+ Pre-generated text embeddings. Can be used to easily tweak text inputs (prompt weighting). If not
304
+ provided, text embeddings are generated from the `prompt` input argument.
305
+ negative_prompt_embeds (`torch.FloatTensor`, *optional*):
306
+ Pre-generated negative text embeddings. Can be used to easily tweak text inputs (prompt weighting). If
307
+ not provided, `negative_prompt_embeds` are generated from the `negative_prompt` input argument.
308
+ ip_adapter_image: (`PipelineImageInput`, *optional*): Optional image input to work with IP Adapters.
309
+ ip_adapter_image_embeds (`List[torch.FloatTensor]`, *optional*):
310
+ Pre-generated image embeddings for IP-Adapter. It should be a list of length same as number of IP-adapters.
311
+ Each element should be a tensor of shape `(batch_size, num_images, emb_dim)`. It should contain the negative image embedding
312
+ if `do_classifier_free_guidance` is set to `True`.
313
+ If not provided, embeddings are computed from the `ip_adapter_image` input argument.
314
+ output_type (`str`, *optional*, defaults to `"pil"`):
315
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
316
+ return_dict (`bool`, *optional*, defaults to `True`):
317
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
318
+ plain tuple.
319
+ cross_attention_kwargs (`dict`, *optional*):
320
+ A kwargs dictionary that if specified is passed along to the [`AttentionProcessor`] as defined in
321
+ [`self.processor`](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
322
+ controlnet_conditioning_scale (`float` or `List[float]`, *optional*, defaults to 1.0):
323
+ The outputs of the ControlNet are multiplied by `controlnet_conditioning_scale` before they are added
324
+ to the residual in the original `unet`. If multiple ControlNets are specified in `init`, you can set
325
+ the corresponding scale as a list.
326
+ guess_mode (`bool`, *optional*, defaults to `False`):
327
+ The ControlNet encoder tries to recognize the content of the input image even if you remove all
328
+ prompts. A `guidance_scale` value between 3.0 and 5.0 is recommended.
329
+ control_guidance_start (`float` or `List[float]`, *optional*, defaults to 0.0):
330
+ The percentage of total steps at which the ControlNet starts applying.
331
+ control_guidance_end (`float` or `List[float]`, *optional*, defaults to 1.0):
332
+ The percentage of total steps at which the ControlNet stops applying.
333
+ clip_skip (`int`, *optional*):
334
+ Number of layers to be skipped from CLIP while computing the prompt embeddings. A value of 1 means that
335
+ the output of the pre-final layer will be used for computing the prompt embeddings.
336
+ callback_on_step_end (`Callable`, *optional*):
337
+ A function that calls at the end of each denoising steps during the inference. The function is called
338
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
339
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
340
+ `callback_on_step_end_tensor_inputs`.
341
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
342
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
343
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
344
+ `._callback_tensor_inputs` attribute of your pipeine class.
345
+
346
+ Examples:
347
+
348
+ Returns:
349
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
350
+ If `return_dict` is `True`, [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] is returned,
351
+ otherwise a `tuple` is returned where the first element is a list with the generated images and the
352
+ second element is a list of `bool`s indicating whether the corresponding generated image contains
353
+ "not-safe-for-work" (nsfw) content.
354
+ """
355
+
356
+ callback = kwargs.pop("callback", None)
357
+ callback_steps = kwargs.pop("callback_steps", None)
358
+
359
+ if callback is not None:
360
+ deprecate(
361
+ "callback",
362
+ "1.0.0",
363
+ "Passing `callback` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
364
+ )
365
+ if callback_steps is not None:
366
+ deprecate(
367
+ "callback_steps",
368
+ "1.0.0",
369
+ "Passing `callback_steps` as an input argument to `__call__` is deprecated, consider using `callback_on_step_end`",
370
+ )
371
+
372
+ controlnet = self.controlnet._orig_mod if is_compiled_module(self.controlnet) else self.controlnet
373
+
374
+ # align format for control guidance
375
+ if not isinstance(control_guidance_start, list) and isinstance(control_guidance_end, list):
376
+ control_guidance_start = len(control_guidance_end) * [control_guidance_start]
377
+ elif not isinstance(control_guidance_end, list) and isinstance(control_guidance_start, list):
378
+ control_guidance_end = len(control_guidance_start) * [control_guidance_end]
379
+ elif not isinstance(control_guidance_start, list) and not isinstance(control_guidance_end, list):
380
+ mult = len(controlnet.nets) if isinstance(controlnet, RBLNMultiControlNetModel) else 1
381
+ control_guidance_start, control_guidance_end = (
382
+ mult * [control_guidance_start],
383
+ mult * [control_guidance_end],
384
+ )
385
+
386
+ # 1. Check inputs. Raise error if not correct
387
+ self.check_inputs(
388
+ prompt,
389
+ control_image,
390
+ callback_steps,
391
+ negative_prompt,
392
+ prompt_embeds,
393
+ negative_prompt_embeds,
394
+ ip_adapter_image,
395
+ ip_adapter_image_embeds,
396
+ controlnet_conditioning_scale,
397
+ control_guidance_start,
398
+ control_guidance_end,
399
+ callback_on_step_end_tensor_inputs,
400
+ )
401
+
402
+ self._guidance_scale = guidance_scale
403
+ self._clip_skip = clip_skip
404
+ self._cross_attention_kwargs = cross_attention_kwargs
405
+
406
+ # 2. Define call parameters
407
+ if prompt is not None and isinstance(prompt, str):
408
+ batch_size = 1
409
+ elif prompt is not None and isinstance(prompt, list):
410
+ batch_size = len(prompt)
411
+ else:
412
+ batch_size = prompt_embeds.shape[0]
413
+
414
+ device = self._execution_device
415
+
416
+ if isinstance(controlnet, RBLNMultiControlNetModel) and isinstance(controlnet_conditioning_scale, float):
417
+ controlnet_conditioning_scale = [controlnet_conditioning_scale] * len(controlnet.nets)
418
+
419
+ global_pool_conditions = (
420
+ controlnet.config.global_pool_conditions
421
+ if isinstance(controlnet, RBLNControlNetModel)
422
+ else controlnet.nets[0].config.global_pool_conditions
423
+ )
424
+ guess_mode = guess_mode or global_pool_conditions
425
+
426
+ # 3. Encode input prompt
427
+ text_encoder_lora_scale = (
428
+ self.cross_attention_kwargs.get("scale", None) if self.cross_attention_kwargs is not None else None
429
+ )
430
+
431
+ prompt_embeds, negative_prompt_embeds = self.encode_prompt(
432
+ prompt,
433
+ device,
434
+ num_images_per_prompt,
435
+ self.do_classifier_free_guidance,
436
+ negative_prompt,
437
+ prompt_embeds=prompt_embeds,
438
+ negative_prompt_embeds=negative_prompt_embeds,
439
+ lora_scale=text_encoder_lora_scale,
440
+ clip_skip=self.clip_skip,
441
+ )
442
+ # For classifier free guidance, we need to do two forward passes.
443
+ # Here we concatenate the unconditional and text embeddings into a single batch
444
+ # to avoid doing two forward passes
445
+ if self.do_classifier_free_guidance:
446
+ prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds])
447
+
448
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None:
449
+ image_embeds = self.prepare_ip_adapter_image_embeds(
450
+ ip_adapter_image,
451
+ ip_adapter_image_embeds,
452
+ device,
453
+ batch_size * num_images_per_prompt,
454
+ self.do_classifier_free_guidance,
455
+ )
456
+
457
+ # 4. Prepare image
458
+ image = self.image_processor.preprocess(image, height=height, width=width).to(dtype=torch.float32)
459
+
460
+ # 5. Prepare controlnet_conditioning_image
461
+ if isinstance(controlnet, RBLNControlNetModel):
462
+ control_image = self.prepare_control_image(
463
+ image=control_image,
464
+ width=width,
465
+ height=height,
466
+ batch_size=batch_size * num_images_per_prompt,
467
+ num_images_per_prompt=num_images_per_prompt,
468
+ device=device,
469
+ dtype=controlnet.dtype,
470
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
471
+ guess_mode=guess_mode,
472
+ )
473
+ elif isinstance(controlnet, RBLNMultiControlNetModel):
474
+ control_images = []
475
+
476
+ for control_image_ in control_image:
477
+ control_image_ = self.prepare_control_image(
478
+ image=control_image_,
479
+ width=width,
480
+ height=height,
481
+ batch_size=batch_size * num_images_per_prompt,
482
+ num_images_per_prompt=num_images_per_prompt,
483
+ device=device,
484
+ dtype=controlnet.dtype,
485
+ do_classifier_free_guidance=self.do_classifier_free_guidance,
486
+ guess_mode=guess_mode,
487
+ )
488
+
489
+ control_images.append(control_image_)
490
+
491
+ control_image = control_images
492
+ else:
493
+ assert False
494
+
495
+ # 5. Prepare timesteps
496
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
497
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
498
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
499
+ self._num_timesteps = len(timesteps)
500
+
501
+ # 6. Prepare latent variables
502
+ latents = self.prepare_latents(
503
+ image,
504
+ latent_timestep,
505
+ batch_size,
506
+ num_images_per_prompt,
507
+ prompt_embeds.dtype,
508
+ device,
509
+ generator,
510
+ )
511
+
512
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
513
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
514
+
515
+ # 7.1 Add image embeds for IP-Adapter
516
+ added_cond_kwargs = (
517
+ {"image_embeds": image_embeds}
518
+ if ip_adapter_image is not None or ip_adapter_image_embeds is not None
519
+ else None
520
+ )
521
+
522
+ # 7.2 Create tensor stating which controlnets to keep
523
+ controlnet_keep = []
524
+ for i in range(len(timesteps)):
525
+ keeps = [
526
+ 1.0 - float(i / len(timesteps) < s or (i + 1) / len(timesteps) > e)
527
+ for s, e in zip(control_guidance_start, control_guidance_end)
528
+ ]
529
+ controlnet_keep.append(keeps[0] if isinstance(controlnet, RBLNControlNetModel) else keeps)
530
+
531
+ # 8. Denoising loop
532
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
533
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
534
+ for i, t in enumerate(timesteps):
535
+ # expand the latents if we are doing classifier free guidance
536
+ latent_model_input = torch.cat([latents] * 2) if self.do_classifier_free_guidance else latents
537
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
538
+
539
+ # controlnet(s) inference
540
+ if guess_mode and self.do_classifier_free_guidance:
541
+ # Infer ControlNet only for the conditional batch.
542
+ control_model_input = latents
543
+ control_model_input = self.scheduler.scale_model_input(control_model_input, t)
544
+ controlnet_prompt_embeds = prompt_embeds.chunk(2)[1]
545
+ else:
546
+ control_model_input = latent_model_input
547
+ controlnet_prompt_embeds = prompt_embeds
548
+
549
+ if isinstance(controlnet_keep[i], list):
550
+ cond_scale = [c * s for c, s in zip(controlnet_conditioning_scale, controlnet_keep[i])]
551
+ else:
552
+ controlnet_cond_scale = controlnet_conditioning_scale
553
+ if isinstance(controlnet_cond_scale, list):
554
+ controlnet_cond_scale = controlnet_cond_scale[0]
555
+ cond_scale = controlnet_cond_scale * controlnet_keep[i]
556
+
557
+ down_block_res_samples, mid_block_res_sample = self.controlnet(
558
+ control_model_input,
559
+ t,
560
+ encoder_hidden_states=controlnet_prompt_embeds,
561
+ controlnet_cond=control_image,
562
+ conditioning_scale=cond_scale,
563
+ guess_mode=guess_mode,
564
+ return_dict=False,
565
+ )
566
+
567
+ if guess_mode and self.do_classifier_free_guidance:
568
+ # Infered ControlNet only for the conditional batch.
569
+ # To apply the output of ControlNet to both the unconditional and conditional batches,
570
+ # add 0 to the unconditional batch to keep it unchanged.
571
+ down_block_res_samples = [torch.cat([torch.zeros_like(d), d]) for d in down_block_res_samples]
572
+ mid_block_res_sample = torch.cat([torch.zeros_like(mid_block_res_sample), mid_block_res_sample])
573
+
574
+ # predict the noise residual
575
+ noise_pred = self.unet(
576
+ latent_model_input,
577
+ t,
578
+ encoder_hidden_states=prompt_embeds,
579
+ cross_attention_kwargs=self.cross_attention_kwargs,
580
+ down_block_additional_residuals=down_block_res_samples,
581
+ mid_block_additional_residual=mid_block_res_sample,
582
+ added_cond_kwargs=added_cond_kwargs,
583
+ return_dict=False,
584
+ )[0]
585
+
586
+ # perform guidance
587
+ if self.do_classifier_free_guidance:
588
+ noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
589
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
590
+
591
+ # compute the previous noisy sample x_t -> x_t-1
592
+ latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
593
+
594
+ if callback_on_step_end is not None:
595
+ callback_kwargs = {}
596
+ for k in callback_on_step_end_tensor_inputs:
597
+ callback_kwargs[k] = locals()[k]
598
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
599
+
600
+ latents = callback_outputs.pop("latents", latents)
601
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
602
+ negative_prompt_embeds = callback_outputs.pop("negative_prompt_embeds", negative_prompt_embeds)
603
+
604
+ # call the callback, if provided
605
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
606
+ progress_bar.update()
607
+ if callback is not None and i % callback_steps == 0:
608
+ step_idx = i // getattr(self.scheduler, "order", 1)
609
+ callback(step_idx, t, latents)
610
+
611
+ # If we do sequential model offloading, let's offload unet and controlnet
612
+ # manually for max memory savings
613
+ if hasattr(self, "final_offload_hook") and self.final_offload_hook is not None:
614
+ self.unet.to("cpu")
615
+ self.controlnet.to("cpu")
616
+ torch.cuda.empty_cache()
617
+
618
+ if not output_type == "latent":
619
+ image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False, generator=generator)[
620
+ 0
621
+ ]
622
+ image, has_nsfw_concept = self.run_safety_checker(image, device, prompt_embeds.dtype)
623
+ else:
624
+ image = latents
625
+ has_nsfw_concept = None
626
+
627
+ if has_nsfw_concept is None:
628
+ do_denormalize = [True] * image.shape[0]
629
+ else:
630
+ do_denormalize = [not has_nsfw for has_nsfw in has_nsfw_concept]
631
+
632
+ image = self.image_processor.postprocess(image, output_type=output_type, do_denormalize=do_denormalize)
633
+
634
+ # Offload all models
635
+ self.maybe_free_model_hooks()
636
+
637
+ if not return_dict:
638
+ return (image, has_nsfw_concept)
639
+
640
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)