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