libcom 0.1.8__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.
Files changed (310) hide show
  1. libcom/__init__.py +23 -0
  2. libcom/color_transfer/__init__.py +3 -0
  3. libcom/color_transfer/reinhard.py +57 -0
  4. libcom/fopa_heat_map/__init__.py +4 -0
  5. libcom/fopa_heat_map/fopa_heat_map.py +212 -0
  6. libcom/fopa_heat_map/source/__init__.py +0 -0
  7. libcom/fopa_heat_map/source/backbone/ResNet.py +229 -0
  8. libcom/fopa_heat_map/source/backbone/__init__.py +0 -0
  9. libcom/fopa_heat_map/source/data/OBdataset.py +292 -0
  10. libcom/fopa_heat_map/source/data/__init__.py +0 -0
  11. libcom/fopa_heat_map/source/data/all_transforms.py +25 -0
  12. libcom/fopa_heat_map/source/network/BaseBlocks.py +26 -0
  13. libcom/fopa_heat_map/source/network/DynamicModules.py +43 -0
  14. libcom/fopa_heat_map/source/network/ObPlaNet_simple.py +112 -0
  15. libcom/fopa_heat_map/source/network/__init__.py +1 -0
  16. libcom/fopa_heat_map/source/network/tensor_ops.py +37 -0
  17. libcom/fopa_heat_map/source/prepare_multi_fg_scales.py +85 -0
  18. libcom/fos_score/__init__.py +4 -0
  19. libcom/fos_score/fos_score_prediction.py +218 -0
  20. libcom/fos_score/source/__init__.py +0 -0
  21. libcom/fos_score/source/config/__init__.py +1 -0
  22. libcom/fos_score/source/config/config.py +68 -0
  23. libcom/fos_score/source/config/config.sfosd.yaml +43 -0
  24. libcom/fos_score/source/config/config_rfosd.yaml +43 -0
  25. libcom/fos_score/source/loss_function.py +118 -0
  26. libcom/fos_score/source/networks.py +355 -0
  27. libcom/harmony_score/__init__.py +3 -0
  28. libcom/harmony_score/harmony_score_prediction.py +119 -0
  29. libcom/harmony_score/source/__init__.py +0 -0
  30. libcom/harmony_score/source/bargainnet.py +226 -0
  31. libcom/image_harmonization/__init__.py +4 -0
  32. libcom/image_harmonization/image_harmonization.py +193 -0
  33. libcom/image_harmonization/source/__init__.py +0 -0
  34. libcom/image_harmonization/source/functions.py +747 -0
  35. libcom/image_harmonization/source/pct_net.py +85 -0
  36. libcom/image_harmonization/source/src/__init__.py +0 -0
  37. libcom/image_harmonization/source/src/lbm/__init__.py +0 -0
  38. libcom/image_harmonization/source/src/lbm/config.py +141 -0
  39. libcom/image_harmonization/source/src/lbm/data/__init__.py +62 -0
  40. libcom/image_harmonization/source/src/lbm/data/datasets/__init__.py +9 -0
  41. libcom/image_harmonization/source/src/lbm/data/datasets/collation_fn.py +41 -0
  42. libcom/image_harmonization/source/src/lbm/data/datasets/dataset.py +243 -0
  43. libcom/image_harmonization/source/src/lbm/data/datasets/datasets_config.py +42 -0
  44. libcom/image_harmonization/source/src/lbm/data/filters/__init__.py +12 -0
  45. libcom/image_harmonization/source/src/lbm/data/filters/base.py +21 -0
  46. libcom/image_harmonization/source/src/lbm/data/filters/filter_wrapper.py +36 -0
  47. libcom/image_harmonization/source/src/lbm/data/filters/filters.py +33 -0
  48. libcom/image_harmonization/source/src/lbm/data/filters/filters_config.py +32 -0
  49. libcom/image_harmonization/source/src/lbm/data/mappers/__init__.py +19 -0
  50. libcom/image_harmonization/source/src/lbm/data/mappers/base.py +26 -0
  51. libcom/image_harmonization/source/src/lbm/data/mappers/mappers.py +135 -0
  52. libcom/image_harmonization/source/src/lbm/data/mappers/mappers_config.py +109 -0
  53. libcom/image_harmonization/source/src/lbm/data/mappers/mappers_wrapper.py +31 -0
  54. libcom/image_harmonization/source/src/lbm/inference/__init__.py +4 -0
  55. libcom/image_harmonization/source/src/lbm/inference/inference.py +70 -0
  56. libcom/image_harmonization/source/src/lbm/inference/utils.py +222 -0
  57. libcom/image_harmonization/source/src/lbm/models/__init__.py +0 -0
  58. libcom/image_harmonization/source/src/lbm/models/base/__init__.py +4 -0
  59. libcom/image_harmonization/source/src/lbm/models/base/base_model.py +66 -0
  60. libcom/image_harmonization/source/src/lbm/models/base/model_config.py +8 -0
  61. libcom/image_harmonization/source/src/lbm/models/embedders/__init__.py +4 -0
  62. libcom/image_harmonization/source/src/lbm/models/embedders/base/__init__.py +4 -0
  63. libcom/image_harmonization/source/src/lbm/models/embedders/base/base_conditioner.py +60 -0
  64. libcom/image_harmonization/source/src/lbm/models/embedders/base/base_conditioner_config.py +27 -0
  65. libcom/image_harmonization/source/src/lbm/models/embedders/conditioners_wrapper.py +114 -0
  66. libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/__init__.py +4 -0
  67. libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/latents_concat_embedder_config.py +31 -0
  68. libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/latents_concat_embedder_model.py +80 -0
  69. libcom/image_harmonization/source/src/lbm/models/lbm/__init__.py +4 -0
  70. libcom/image_harmonization/source/src/lbm/models/lbm/lbm_config.py +101 -0
  71. libcom/image_harmonization/source/src/lbm/models/lbm/lbm_model.py +359 -0
  72. libcom/image_harmonization/source/src/lbm/models/unets/__init__.py +14 -0
  73. libcom/image_harmonization/source/src/lbm/models/unets/unet.py +148 -0
  74. libcom/image_harmonization/source/src/lbm/models/utils.py +377 -0
  75. libcom/image_harmonization/source/src/lbm/models/vae/__init__.py +4 -0
  76. libcom/image_harmonization/source/src/lbm/models/vae/autoencoderKL.py +136 -0
  77. libcom/image_harmonization/source/src/lbm/models/vae/autoencoderKL_config.py +27 -0
  78. libcom/image_harmonization/source/src/lbm/trainer/__init__.py +85 -0
  79. libcom/image_harmonization/source/src/lbm/trainer/loggers.py +324 -0
  80. libcom/image_harmonization/source/src/lbm/trainer/trainer.py +199 -0
  81. libcom/image_harmonization/source/src/lbm/trainer/training_config.py +82 -0
  82. libcom/image_harmonization/source/src/lbm/trainer/utils.py +193 -0
  83. libcom/inharmonious_region_localization/__init__.py +4 -0
  84. libcom/inharmonious_region_localization/inharmonious_region_localization.py +97 -0
  85. libcom/inharmonious_region_localization/source/__init__.py +0 -0
  86. libcom/inharmonious_region_localization/source/blocks.py +368 -0
  87. libcom/inharmonious_region_localization/source/functions.py +679 -0
  88. libcom/inharmonious_region_localization/source/madis_net.py +79 -0
  89. libcom/kontext_blending_harmonization/__init__.py +3 -0
  90. libcom/kontext_blending_harmonization/kontext_blending_harmonization.py +148 -0
  91. libcom/kontext_blending_harmonization/source/__init__.py +0 -0
  92. libcom/kontext_blending_harmonization/source/pipeline.py +1135 -0
  93. libcom/naive_composition/__init__.py +3 -0
  94. libcom/naive_composition/generate_composite_image.py +116 -0
  95. libcom/opa_score/__init__.py +3 -0
  96. libcom/opa_score/opa_score_prediction.py +101 -0
  97. libcom/opa_score/source/__init__.py +3 -0
  98. libcom/opa_score/source/object_place_net.py +55 -0
  99. libcom/opa_score/source/oblect_place_config.py +66 -0
  100. libcom/opa_score/source/resnet_4ch.py +213 -0
  101. libcom/os_insert/__init__.py +3 -0
  102. libcom/os_insert/diffusers_osinsert/__init__.py +78 -0
  103. libcom/os_insert/diffusers_osinsert/_patched_pipeline_flux_fill.py +878 -0
  104. libcom/os_insert/os_insert.py +534 -0
  105. libcom/os_insert/source/__init__.py +1 -0
  106. libcom/os_insert/source/ia_utils.py +183 -0
  107. libcom/os_insert/source/insertanything_infer.py +529 -0
  108. libcom/os_insert/source/ldm/__init__.py +0 -0
  109. libcom/os_insert/source/ldm/data/__init__.py +0 -0
  110. libcom/os_insert/source/ldm/data/base.py +23 -0
  111. libcom/os_insert/source/ldm/data/datamodule.py +128 -0
  112. libcom/os_insert/source/ldm/data/imagenet.py +394 -0
  113. libcom/os_insert/source/ldm/data/lsun.py +92 -0
  114. libcom/os_insert/source/ldm/data/open_images.py +728 -0
  115. libcom/os_insert/source/ldm/lr_scheduler.py +98 -0
  116. libcom/os_insert/source/ldm/models/__init__.py +0 -0
  117. libcom/os_insert/source/ldm/models/autoencoder.py +443 -0
  118. libcom/os_insert/source/ldm/models/diffusion/__init__.py +0 -0
  119. libcom/os_insert/source/ldm/models/diffusion/classifier.py +267 -0
  120. libcom/os_insert/source/ldm/models/diffusion/ddim.py +263 -0
  121. libcom/os_insert/source/ldm/models/diffusion/ddpm.py +1417 -0
  122. libcom/os_insert/source/ldm/models/diffusion/plms.py +252 -0
  123. libcom/os_insert/source/ldm/modules/__init__.py +0 -0
  124. libcom/os_insert/source/ldm/modules/attention.py +261 -0
  125. libcom/os_insert/source/ldm/modules/diffusionmodules/__init__.py +0 -0
  126. libcom/os_insert/source/ldm/modules/diffusionmodules/model.py +835 -0
  127. libcom/os_insert/source/ldm/modules/diffusionmodules/openaimodel.py +1108 -0
  128. libcom/os_insert/source/ldm/modules/diffusionmodules/util.py +267 -0
  129. libcom/os_insert/source/ldm/modules/distributions/__init__.py +0 -0
  130. libcom/os_insert/source/ldm/modules/distributions/distributions.py +92 -0
  131. libcom/os_insert/source/ldm/modules/ema.py +76 -0
  132. libcom/os_insert/source/ldm/modules/encoders/__init__.py +0 -0
  133. libcom/os_insert/source/ldm/modules/encoders/modules.py +190 -0
  134. libcom/os_insert/source/ldm/modules/encoders/xf.py +130 -0
  135. libcom/os_insert/source/ldm/modules/losses/__init__.py +1 -0
  136. libcom/os_insert/source/ldm/modules/losses/contperceptual.py +111 -0
  137. libcom/os_insert/source/ldm/modules/losses/vqperceptual.py +167 -0
  138. libcom/os_insert/source/ldm/modules/x_transformer.py +641 -0
  139. libcom/os_insert/source/ldm/util.py +203 -0
  140. libcom/os_insert/source/objectstitch_data.py +66 -0
  141. libcom/os_insert/source/objectstitch_infer.py +618 -0
  142. libcom/os_insert/source/sam_on_objectstitch.py +253 -0
  143. libcom/os_insert/source/utils.py +41 -0
  144. libcom/os_insert/source/v1.yaml +108 -0
  145. libcom/painterly_image_harmonization/__init__.py +4 -0
  146. libcom/painterly_image_harmonization/painterly_image_harmonization.py +215 -0
  147. libcom/painterly_image_harmonization/source/PHDNet/__init__.py +0 -0
  148. libcom/painterly_image_harmonization/source/PHDNet/networks.py +202 -0
  149. libcom/painterly_image_harmonization/source/PHDNet/phdnet.py +47 -0
  150. libcom/painterly_image_harmonization/source/PHDNet/phdnet_config.py +18 -0
  151. libcom/painterly_image_harmonization/source/PHDiffusion/__init__.py +0 -0
  152. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/__init__.py +0 -0
  153. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/inference_base.py +300 -0
  154. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/lr_scheduler.py +98 -0
  155. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/__init__.py +0 -0
  156. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/autoencoder.py +211 -0
  157. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/__init__.py +3 -0
  158. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/ddim.py +336 -0
  159. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/ddpm.py +1400 -0
  160. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  161. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/dpm_solver.py +1217 -0
  162. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
  163. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/plms.py +243 -0
  164. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/scheduling_pndm.py +518 -0
  165. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/__init__.py +0 -0
  166. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/attention.py +378 -0
  167. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/__init__.py +0 -0
  168. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/model.py +857 -0
  169. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/openaimodel.py +823 -0
  170. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/util.py +270 -0
  171. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/distributions/__init__.py +0 -0
  172. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/distributions/distributions.py +92 -0
  173. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/ema.py +80 -0
  174. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/__init__.py +0 -0
  175. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/adapter.py +213 -0
  176. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/modules.py +82 -0
  177. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/__init__.py +1 -0
  178. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/api.py +269 -0
  179. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/__init__.py +0 -0
  180. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/api.py +175 -0
  181. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/__init__.py +0 -0
  182. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/base_model.py +16 -0
  183. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/blocks.py +342 -0
  184. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/dpt_depth.py +109 -0
  185. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/midas_net.py +76 -0
  186. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/midas_net_custom.py +128 -0
  187. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/transforms.py +234 -0
  188. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/vit.py +491 -0
  189. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/utils.py +189 -0
  190. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/model_edge.py +653 -0
  191. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/__init__.py +0 -0
  192. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/api.py +35 -0
  193. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/body.py +209 -0
  194. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/hand.py +75 -0
  195. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/model.py +178 -0
  196. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/util.py +203 -0
  197. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/utils.py +72 -0
  198. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/fusion/__init__.py +0 -0
  199. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/fusion/dual_encoder_fusion.py +93 -0
  200. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/__init__.py +2 -0
  201. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/bsrgan.py +730 -0
  202. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/bsrgan_light.py +651 -0
  203. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/utils_image.py +916 -0
  204. libcom/painterly_image_harmonization/source/PHDiffusion/ldm/util.py +200 -0
  205. libcom/painterly_image_harmonization/source/PHDiffusion/stable_diffusion.yaml +75 -0
  206. libcom/painterly_image_harmonization/source/__init__.py +0 -0
  207. libcom/reflection_generation/__init__.py +3 -0
  208. libcom/reflection_generation/reflection_generation.py +174 -0
  209. libcom/reflection_generation/source/PostProcessModel.py +513 -0
  210. libcom/reflection_generation/source/__init__.py +0 -0
  211. libcom/reflection_generation/source/cldm/__init__.py +0 -0
  212. libcom/reflection_generation/source/cldm/base_network.py +166 -0
  213. libcom/reflection_generation/source/cldm/cldm.py +509 -0
  214. libcom/reflection_generation/source/cldm/ddim_hacked.py +317 -0
  215. libcom/reflection_generation/source/cldm/hack.py +111 -0
  216. libcom/reflection_generation/source/cldm/logger.py +127 -0
  217. libcom/reflection_generation/source/cldm/model.py +26 -0
  218. libcom/reflection_generation/source/cldm_v15.yaml +81 -0
  219. libcom/reflection_generation/source/cluster_feature.py +109 -0
  220. libcom/reflection_generation/source/ldm/__init__.py +0 -0
  221. libcom/reflection_generation/source/ldm/models/__init__.py +0 -0
  222. libcom/reflection_generation/source/ldm/models/autoencoder.py +219 -0
  223. libcom/reflection_generation/source/ldm/models/diffusion/__init__.py +0 -0
  224. libcom/reflection_generation/source/ldm/models/diffusion/attention_processor.py +188 -0
  225. libcom/reflection_generation/source/ldm/models/diffusion/ddim.py +340 -0
  226. libcom/reflection_generation/source/ldm/models/diffusion/ddpm.py +1892 -0
  227. libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  228. libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
  229. libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
  230. libcom/reflection_generation/source/ldm/models/diffusion/ip_adapter.py +57 -0
  231. libcom/reflection_generation/source/ldm/models/diffusion/plms.py +244 -0
  232. libcom/reflection_generation/source/ldm/models/diffusion/sampling_util.py +22 -0
  233. libcom/reflection_generation/source/ldm/modules/__init__.py +0 -0
  234. libcom/reflection_generation/source/ldm/modules/attention.py +341 -0
  235. libcom/reflection_generation/source/ldm/modules/diffusionmodules/__init__.py +0 -0
  236. libcom/reflection_generation/source/ldm/modules/diffusionmodules/model.py +852 -0
  237. libcom/reflection_generation/source/ldm/modules/diffusionmodules/openaimodel.py +786 -0
  238. libcom/reflection_generation/source/ldm/modules/diffusionmodules/upscaling.py +81 -0
  239. libcom/reflection_generation/source/ldm/modules/diffusionmodules/util.py +280 -0
  240. libcom/reflection_generation/source/ldm/modules/distributions/__init__.py +0 -0
  241. libcom/reflection_generation/source/ldm/modules/distributions/distributions.py +92 -0
  242. libcom/reflection_generation/source/ldm/modules/ema.py +80 -0
  243. libcom/reflection_generation/source/ldm/modules/encoders/__init__.py +0 -0
  244. libcom/reflection_generation/source/ldm/modules/encoders/modules.py +214 -0
  245. libcom/reflection_generation/source/ldm/modules/image_degradation/__init__.py +0 -0
  246. libcom/reflection_generation/source/ldm/modules/image_degradation/bsrgan.py +730 -0
  247. libcom/reflection_generation/source/ldm/modules/image_degradation/bsrgan_light.py +651 -0
  248. libcom/reflection_generation/source/ldm/modules/image_degradation/utils_image.py +916 -0
  249. libcom/reflection_generation/source/ldm/util.py +198 -0
  250. libcom/reflection_generation/source/local_clip.py +749 -0
  251. libcom/reflection_generation/source/tool_add_control.py +49 -0
  252. libcom/shadow_generation/__init__.py +3 -0
  253. libcom/shadow_generation/shadow_generation.py +754 -0
  254. libcom/shadow_generation/source/PostProcessModel.py +511 -0
  255. libcom/shadow_generation/source/__init__.py +0 -0
  256. libcom/shadow_generation/source/attention_processor.py +234 -0
  257. libcom/shadow_generation/source/cldm/__init__.py +0 -0
  258. libcom/shadow_generation/source/cldm/base_network.py +166 -0
  259. libcom/shadow_generation/source/cldm/cldm.py +524 -0
  260. libcom/shadow_generation/source/cldm/model.py +28 -0
  261. libcom/shadow_generation/source/ldm/__init__.py +0 -0
  262. libcom/shadow_generation/source/ldm/models/__init__.py +0 -0
  263. libcom/shadow_generation/source/ldm/models/autoencoder.py +219 -0
  264. libcom/shadow_generation/source/ldm/models/diffusion/__init__.py +0 -0
  265. libcom/shadow_generation/source/ldm/models/diffusion/attention_processor.py +188 -0
  266. libcom/shadow_generation/source/ldm/models/diffusion/ddim.py +340 -0
  267. libcom/shadow_generation/source/ldm/models/diffusion/ddpm.py +1893 -0
  268. libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
  269. libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
  270. libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
  271. libcom/shadow_generation/source/ldm/models/diffusion/ip_adapter.py +57 -0
  272. libcom/shadow_generation/source/ldm/models/diffusion/plms.py +244 -0
  273. libcom/shadow_generation/source/ldm/models/diffusion/sampling_util.py +22 -0
  274. libcom/shadow_generation/source/ldm/modules/__init__.py +0 -0
  275. libcom/shadow_generation/source/ldm/modules/attention.py +341 -0
  276. libcom/shadow_generation/source/ldm/modules/diffusionmodules/__init__.py +0 -0
  277. libcom/shadow_generation/source/ldm/modules/diffusionmodules/model.py +852 -0
  278. libcom/shadow_generation/source/ldm/modules/diffusionmodules/openaimodel.py +786 -0
  279. libcom/shadow_generation/source/ldm/modules/diffusionmodules/upscaling.py +81 -0
  280. libcom/shadow_generation/source/ldm/modules/diffusionmodules/util.py +270 -0
  281. libcom/shadow_generation/source/ldm/modules/distributions/__init__.py +0 -0
  282. libcom/shadow_generation/source/ldm/modules/distributions/distributions.py +92 -0
  283. libcom/shadow_generation/source/ldm/modules/ema.py +80 -0
  284. libcom/shadow_generation/source/ldm/modules/encoders/__init__.py +0 -0
  285. libcom/shadow_generation/source/ldm/modules/encoders/modules.py +214 -0
  286. libcom/shadow_generation/source/ldm/modules/image_degradation/__init__.py +2 -0
  287. libcom/shadow_generation/source/ldm/modules/image_degradation/bsrgan.py +730 -0
  288. libcom/shadow_generation/source/ldm/modules/image_degradation/bsrgan_light.py +651 -0
  289. libcom/shadow_generation/source/ldm/modules/image_degradation/utils_image.py +916 -0
  290. libcom/shadow_generation/source/ldm/modules/midas/__init__.py +0 -0
  291. libcom/shadow_generation/source/ldm/modules/midas/api.py +170 -0
  292. libcom/shadow_generation/source/ldm/modules/midas/midas/__init__.py +0 -0
  293. libcom/shadow_generation/source/ldm/modules/midas/midas/base_model.py +16 -0
  294. libcom/shadow_generation/source/ldm/modules/midas/midas/blocks.py +342 -0
  295. libcom/shadow_generation/source/ldm/modules/midas/midas/dpt_depth.py +109 -0
  296. libcom/shadow_generation/source/ldm/modules/midas/midas/midas_net.py +76 -0
  297. libcom/shadow_generation/source/ldm/modules/midas/midas/midas_net_custom.py +128 -0
  298. libcom/shadow_generation/source/ldm/modules/midas/midas/transforms.py +234 -0
  299. libcom/shadow_generation/source/ldm/modules/midas/midas/vit.py +491 -0
  300. libcom/shadow_generation/source/ldm/modules/midas/utils.py +189 -0
  301. libcom/shadow_generation/source/ldm/util.py +199 -0
  302. libcom/utils/__init__.py +0 -0
  303. libcom/utils/environment.py +12 -0
  304. libcom/utils/model_download.py +67 -0
  305. libcom/utils/process_image.py +108 -0
  306. libcom-0.1.8.dist-info/METADATA +157 -0
  307. libcom-0.1.8.dist-info/RECORD +310 -0
  308. libcom-0.1.8.dist-info/WHEEL +5 -0
  309. libcom-0.1.8.dist-info/licenses/LICENSE +201 -0
  310. libcom-0.1.8.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1108 @@
1
+ from abc import abstractmethod
2
+ from functools import partial
3
+ import math
4
+ from typing import Iterable
5
+
6
+ import numpy as np
7
+ import torch as th
8
+ import torch.nn as nn
9
+ import torch.nn.functional as F
10
+
11
+ from ldm.modules.diffusionmodules.util import (
12
+ checkpoint,
13
+ conv_nd,
14
+ linear,
15
+ avg_pool_nd,
16
+ zero_module,
17
+ normalization,
18
+ timestep_embedding,
19
+ )
20
+ from ldm.modules.attention import SpatialTransformer
21
+
22
+
23
+ # dummy replace
24
+ def convert_module_to_f16(x):
25
+ pass
26
+
27
+ def convert_module_to_f32(x):
28
+ pass
29
+
30
+
31
+ ## go
32
+ class AttentionPool2d(nn.Module):
33
+ """
34
+ Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
35
+ """
36
+
37
+ def __init__(
38
+ self,
39
+ spacial_dim: int,
40
+ embed_dim: int,
41
+ num_heads_channels: int,
42
+ output_dim: int = None,
43
+ ):
44
+ super().__init__()
45
+ self.positional_embedding = nn.Parameter(th.randn(embed_dim, spacial_dim ** 2 + 1) / embed_dim ** 0.5)
46
+ self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
47
+ self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
48
+ self.num_heads = embed_dim // num_heads_channels
49
+ self.attention = QKVAttention(self.num_heads)
50
+
51
+ def forward(self, x):
52
+ b, c, *_spatial = x.shape
53
+ x = x.reshape(b, c, -1) # NC(HW)
54
+ x = th.cat([x.mean(dim=-1, keepdim=True), x], dim=-1) # NC(HW+1)
55
+ x = x + self.positional_embedding[None, :, :].to(x.dtype) # NC(HW+1)
56
+ x = self.qkv_proj(x)
57
+ x = self.attention(x)
58
+ x = self.c_proj(x)
59
+ return x[:, :, 0]
60
+
61
+
62
+ class TimestepBlock(nn.Module):
63
+ """
64
+ Any module where forward() takes timestep embeddings as a second argument.
65
+ """
66
+
67
+ @abstractmethod
68
+ def forward(self, x, emb):
69
+ """
70
+ Apply the module to `x` given `emb` timestep embeddings.
71
+ """
72
+
73
+
74
+ class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
75
+ """
76
+ A sequential module that passes timestep embeddings to the children that
77
+ support it as an extra input.
78
+ """
79
+
80
+ def forward(self, x, emb, context=None):
81
+ for layer in self:
82
+ if isinstance(layer, TimestepBlock):
83
+ x = layer(x, emb)
84
+ elif isinstance(layer, SpatialTransformer):
85
+ x = layer(x, context)
86
+ else:
87
+ x = layer(x)
88
+ return x
89
+
90
+
91
+ class Upsample(nn.Module):
92
+ """
93
+ An upsampling layer with an optional convolution.
94
+ :param channels: channels in the inputs and outputs.
95
+ :param use_conv: a bool determining if a convolution is applied.
96
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
97
+ upsampling occurs in the inner-two dimensions.
98
+ """
99
+
100
+ def __init__(self, channels, use_conv, dims=2, out_channels=None, padding=1):
101
+ super().__init__()
102
+ self.channels = channels
103
+ self.out_channels = out_channels or channels
104
+ self.use_conv = use_conv
105
+ self.dims = dims
106
+ if use_conv:
107
+ self.conv = conv_nd(dims, self.channels, self.out_channels, 3, padding=padding)
108
+
109
+ def forward(self, x):
110
+ assert x.shape[1] == self.channels
111
+ if self.dims == 3:
112
+ x = F.interpolate(
113
+ x, (x.shape[2], x.shape[3] * 2, x.shape[4] * 2), mode="nearest"
114
+ )
115
+ else:
116
+ x = F.interpolate(x, scale_factor=2, mode="nearest")
117
+ if self.use_conv:
118
+ x = self.conv(x)
119
+ return x
120
+
121
+ class TransposedUpsample(nn.Module):
122
+ 'Learned 2x upsampling without padding'
123
+ def __init__(self, channels, out_channels=None, ks=5):
124
+ super().__init__()
125
+ self.channels = channels
126
+ self.out_channels = out_channels or channels
127
+
128
+ self.up = nn.ConvTranspose2d(self.channels,self.out_channels,kernel_size=ks,stride=2)
129
+
130
+ def forward(self,x):
131
+ return self.up(x)
132
+
133
+
134
+ class Downsample(nn.Module):
135
+ """
136
+ A downsampling layer with an optional convolution.
137
+ :param channels: channels in the inputs and outputs.
138
+ :param use_conv: a bool determining if a convolution is applied.
139
+ :param dims: determines if the signal is 1D, 2D, or 3D. If 3D, then
140
+ downsampling occurs in the inner-two dimensions.
141
+ """
142
+
143
+ def __init__(self, channels, use_conv, dims=2, out_channels=None,padding=1):
144
+ super().__init__()
145
+ self.channels = channels
146
+ self.out_channels = out_channels or channels
147
+ self.use_conv = use_conv
148
+ self.dims = dims
149
+ stride = 2 if dims != 3 else (1, 2, 2)
150
+ if use_conv:
151
+ self.op = conv_nd(
152
+ dims, self.channels, self.out_channels, 3, stride=stride, padding=padding
153
+ )
154
+ else:
155
+ assert self.channels == self.out_channels
156
+ self.op = avg_pool_nd(dims, kernel_size=stride, stride=stride)
157
+
158
+ def forward(self, x):
159
+ assert x.shape[1] == self.channels
160
+ return self.op(x)
161
+
162
+
163
+ class ResBlock(TimestepBlock):
164
+ """
165
+ A residual block that can optionally change the number of channels.
166
+ :param channels: the number of input channels.
167
+ :param emb_channels: the number of timestep embedding channels.
168
+ :param dropout: the rate of dropout.
169
+ :param out_channels: if specified, the number of out channels.
170
+ :param use_conv: if True and out_channels is specified, use a spatial
171
+ convolution instead of a smaller 1x1 convolution to change the
172
+ channels in the skip connection.
173
+ :param dims: determines if the signal is 1D, 2D, or 3D.
174
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
175
+ :param up: if True, use this block for upsampling.
176
+ :param down: if True, use this block for downsampling.
177
+ """
178
+
179
+ def __init__(
180
+ self,
181
+ channels,
182
+ emb_channels,
183
+ dropout,
184
+ out_channels=None,
185
+ use_conv=False,
186
+ use_scale_shift_norm=False,
187
+ dims=2,
188
+ use_checkpoint=False,
189
+ up=False,
190
+ down=False,
191
+ ):
192
+ super().__init__()
193
+ self.channels = channels
194
+ self.emb_channels = emb_channels
195
+ self.dropout = dropout
196
+ self.out_channels = out_channels or channels
197
+ self.use_conv = use_conv
198
+ self.use_checkpoint = use_checkpoint
199
+ self.use_scale_shift_norm = use_scale_shift_norm
200
+
201
+ self.in_layers = nn.Sequential(
202
+ normalization(channels),
203
+ nn.SiLU(),
204
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
205
+ )
206
+
207
+ self.updown = up or down
208
+
209
+ if up:
210
+ self.h_upd = Upsample(channels, False, dims)
211
+ self.x_upd = Upsample(channels, False, dims)
212
+ elif down:
213
+ self.h_upd = Downsample(channels, False, dims)
214
+ self.x_upd = Downsample(channels, False, dims)
215
+ else:
216
+ self.h_upd = self.x_upd = nn.Identity()
217
+
218
+ self.emb_layers = nn.Sequential(
219
+ nn.SiLU(),
220
+ linear(
221
+ emb_channels,
222
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
223
+ ),
224
+ )
225
+ self.out_layers = nn.Sequential(
226
+ normalization(self.out_channels),
227
+ nn.SiLU(),
228
+ nn.Dropout(p=dropout),
229
+ zero_module(
230
+ conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)
231
+ ),
232
+ )
233
+
234
+ if self.out_channels == channels:
235
+ self.skip_connection = nn.Identity()
236
+ elif use_conv:
237
+ self.skip_connection = conv_nd(
238
+ dims, channels, self.out_channels, 3, padding=1
239
+ )
240
+ else:
241
+ self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
242
+
243
+ def forward(self, x, emb):
244
+ """
245
+ Apply the block to a Tensor, conditioned on a timestep embedding.
246
+ :param x: an [N x C x ...] Tensor of features.
247
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
248
+ :return: an [N x C x ...] Tensor of outputs.
249
+ """
250
+ return checkpoint(
251
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
252
+ )
253
+
254
+
255
+ def _forward(self, x, emb):
256
+ if self.updown:
257
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
258
+ h = in_rest(x)
259
+ h = self.h_upd(h)
260
+ x = self.x_upd(x)
261
+ h = in_conv(h)
262
+ else:
263
+ h = self.in_layers(x)
264
+ emb_out = self.emb_layers(emb).type(h.dtype)
265
+ while len(emb_out.shape) < len(h.shape):
266
+ emb_out = emb_out[..., None]
267
+ if self.use_scale_shift_norm:
268
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
269
+ scale, shift = th.chunk(emb_out, 2, dim=1)
270
+ h = out_norm(h) * (1 + scale) + shift
271
+ h = out_rest(h)
272
+ else:
273
+ h = h + emb_out
274
+ h = self.out_layers(h)
275
+ return self.skip_connection(x) + h
276
+
277
+
278
+ class My_ResBlock(TimestepBlock):
279
+ """
280
+ A residual block that can optionally change the number of channels.
281
+ :param channels: the number of input channels.
282
+ :param emb_channels: the number of timestep embedding channels.
283
+ :param dropout: the rate of dropout.
284
+ :param out_channels: if specified, the number of out channels.
285
+ :param use_conv: if True and out_channels is specified, use a spatial
286
+ convolution instead of a smaller 1x1 convolution to change the
287
+ channels in the skip connection.
288
+ :param dims: determines if the signal is 1D, 2D, or 3D.
289
+ :param use_checkpoint: if True, use gradient checkpointing on this module.
290
+ :param up: if True, use this block for upsampling.
291
+ :param down: if True, use this block for downsampling.
292
+ """
293
+
294
+ def __init__(
295
+ self,
296
+ channels,
297
+ emb_channels,
298
+ dropout,
299
+ out_channels=None,
300
+ use_conv=False,
301
+ use_scale_shift_norm=False,
302
+ dims=2,
303
+ use_checkpoint=False,
304
+ up=False,
305
+ down=False,
306
+ ):
307
+ super().__init__()
308
+ self.channels = channels
309
+ self.emb_channels = emb_channels
310
+ self.dropout = dropout
311
+ self.out_channels = out_channels or channels
312
+ self.use_conv = use_conv
313
+ self.use_checkpoint = use_checkpoint
314
+ self.use_scale_shift_norm = use_scale_shift_norm
315
+
316
+ self.in_layers = nn.Sequential(
317
+ normalization(channels),
318
+ nn.SiLU(),
319
+ conv_nd(dims, channels, self.out_channels, 3, padding=1),
320
+ )
321
+
322
+ self.updown = up or down
323
+
324
+ if up:
325
+ self.h_upd = Upsample(channels, False, dims)
326
+ self.x_upd = Upsample(channels, False, dims)
327
+ elif down:
328
+ self.h_upd = Downsample(channels, False, dims)
329
+ self.x_upd = Downsample(channels, False, dims)
330
+ else:
331
+ self.h_upd = self.x_upd = nn.Identity()
332
+
333
+ self.emb_layers = nn.Sequential(
334
+ nn.SiLU(),
335
+ linear(
336
+ emb_channels,
337
+ 2 * self.out_channels if use_scale_shift_norm else self.out_channels,
338
+ ),
339
+ )
340
+ self.out_layers = nn.Sequential(
341
+ normalization(self.out_channels),
342
+ nn.SiLU(),
343
+ nn.Dropout(p=dropout),
344
+ zero_module(
345
+ conv_nd(dims, self.out_channels, 4, 3, padding=1)
346
+ ),
347
+ )
348
+
349
+ if self.out_channels == channels:
350
+ self.skip_connection = nn.Identity()
351
+ elif use_conv:
352
+ self.skip_connection = conv_nd(
353
+ dims, channels, self.out_channels, 3, padding=1
354
+ )
355
+ else:
356
+ self.skip_connection = conv_nd(dims, channels, 4, 1)
357
+
358
+ def forward(self, x, emb):
359
+ """
360
+ Apply the block to a Tensor, conditioned on a timestep embedding.
361
+ :param x: an [N x C x ...] Tensor of features.
362
+ :param emb: an [N x emb_channels] Tensor of timestep embeddings.
363
+ :return: an [N x C x ...] Tensor of outputs.
364
+ """
365
+ return checkpoint(
366
+ self._forward, (x, emb), self.parameters(), self.use_checkpoint
367
+ )
368
+
369
+
370
+ def _forward(self, x, emb):
371
+ if self.updown:
372
+ in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
373
+ h = in_rest(x)
374
+ h = self.h_upd(h)
375
+ x = self.x_upd(x)
376
+ h = in_conv(h)
377
+ else:
378
+ h = self.in_layers(x)
379
+ emb_out = self.emb_layers(emb).type(h.dtype)
380
+ while len(emb_out.shape) < len(h.shape):
381
+ emb_out = emb_out[..., None]
382
+ if self.use_scale_shift_norm:
383
+ out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
384
+ scale, shift = th.chunk(emb_out, 2, dim=1)
385
+ h = out_norm(h) * (1 + scale) + shift
386
+ h = out_rest(h)
387
+ else:
388
+ h = h + emb_out
389
+ h = self.out_layers(h)
390
+ return h
391
+
392
+
393
+ class AttentionBlock(nn.Module):
394
+ """
395
+ An attention block that allows spatial positions to attend to each other.
396
+ Originally ported from here, but adapted to the N-d case.
397
+ https://github.com/hojonathanho/diffusion/blob/1e0dceb3b3495bbe19116a5e1b3596cd0706c543/diffusion_tf/models/unet.py#L66.
398
+ """
399
+
400
+ def __init__(
401
+ self,
402
+ channels,
403
+ num_heads=1,
404
+ num_head_channels=-1,
405
+ use_checkpoint=False,
406
+ use_new_attention_order=False,
407
+ ):
408
+ super().__init__()
409
+ self.channels = channels
410
+ if num_head_channels == -1:
411
+ self.num_heads = num_heads
412
+ else:
413
+ assert (
414
+ channels % num_head_channels == 0
415
+ ), f"q,k,v channels {channels} is not divisible by num_head_channels {num_head_channels}"
416
+ self.num_heads = channels // num_head_channels
417
+ self.use_checkpoint = use_checkpoint
418
+ self.norm = normalization(channels)
419
+ self.qkv = conv_nd(1, channels, channels * 3, 1)
420
+ if use_new_attention_order:
421
+ # split qkv before split heads
422
+ self.attention = QKVAttention(self.num_heads)
423
+ else:
424
+ # split heads before split qkv
425
+ self.attention = QKVAttentionLegacy(self.num_heads)
426
+
427
+ self.proj_out = zero_module(conv_nd(1, channels, channels, 1))
428
+
429
+ def forward(self, x):
430
+ return checkpoint(self._forward, (x,), self.parameters(), True) # TODO: check checkpoint usage, is True # TODO: fix the .half call!!!
431
+ #return pt_checkpoint(self._forward, x) # pytorch
432
+
433
+ def _forward(self, x):
434
+ b, c, *spatial = x.shape
435
+ x = x.reshape(b, c, -1)
436
+ qkv = self.qkv(self.norm(x))
437
+ h = self.attention(qkv)
438
+ h = self.proj_out(h)
439
+ return (x + h).reshape(b, c, *spatial)
440
+
441
+
442
+ def count_flops_attn(model, _x, y):
443
+ """
444
+ A counter for the `thop` package to count the operations in an
445
+ attention operation.
446
+ Meant to be used like:
447
+ macs, params = thop.profile(
448
+ model,
449
+ inputs=(inputs, timestamps),
450
+ custom_ops={QKVAttention: QKVAttention.count_flops},
451
+ )
452
+ """
453
+ b, c, *spatial = y[0].shape
454
+ num_spatial = int(np.prod(spatial))
455
+ # We perform two matmuls with the same number of ops.
456
+ # The first computes the weight matrix, the second computes
457
+ # the combination of the value vectors.
458
+ matmul_ops = 2 * b * (num_spatial ** 2) * c
459
+ model.total_ops += th.DoubleTensor([matmul_ops])
460
+
461
+
462
+ class QKVAttentionLegacy(nn.Module):
463
+ """
464
+ A module which performs QKV attention. Matches legacy QKVAttention + input/ouput heads shaping
465
+ """
466
+
467
+ def __init__(self, n_heads):
468
+ super().__init__()
469
+ self.n_heads = n_heads
470
+
471
+ def forward(self, qkv):
472
+ """
473
+ Apply QKV attention.
474
+ :param qkv: an [N x (H * 3 * C) x T] tensor of Qs, Ks, and Vs.
475
+ :return: an [N x (H * C) x T] tensor after attention.
476
+ """
477
+ bs, width, length = qkv.shape
478
+ assert width % (3 * self.n_heads) == 0
479
+ ch = width // (3 * self.n_heads)
480
+ q, k, v = qkv.reshape(bs * self.n_heads, ch * 3, length).split(ch, dim=1)
481
+ scale = 1 / math.sqrt(math.sqrt(ch))
482
+ weight = th.einsum(
483
+ "bct,bcs->bts", q * scale, k * scale
484
+ ) # More stable with f16 than dividing afterwards
485
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
486
+ a = th.einsum("bts,bcs->bct", weight, v)
487
+ return a.reshape(bs, -1, length)
488
+
489
+ @staticmethod
490
+ def count_flops(model, _x, y):
491
+ return count_flops_attn(model, _x, y)
492
+
493
+
494
+ class QKVAttention(nn.Module):
495
+ """
496
+ A module which performs QKV attention and splits in a different order.
497
+ """
498
+
499
+ def __init__(self, n_heads):
500
+ super().__init__()
501
+ self.n_heads = n_heads
502
+
503
+ def forward(self, qkv):
504
+ """
505
+ Apply QKV attention.
506
+ :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs.
507
+ :return: an [N x (H * C) x T] tensor after attention.
508
+ """
509
+ bs, width, length = qkv.shape
510
+ assert width % (3 * self.n_heads) == 0
511
+ ch = width // (3 * self.n_heads)
512
+ q, k, v = qkv.chunk(3, dim=1)
513
+ scale = 1 / math.sqrt(math.sqrt(ch))
514
+ weight = th.einsum(
515
+ "bct,bcs->bts",
516
+ (q * scale).view(bs * self.n_heads, ch, length),
517
+ (k * scale).view(bs * self.n_heads, ch, length),
518
+ ) # More stable with f16 than dividing afterwards
519
+ weight = th.softmax(weight.float(), dim=-1).type(weight.dtype)
520
+ a = th.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
521
+ return a.reshape(bs, -1, length)
522
+
523
+ @staticmethod
524
+ def count_flops(model, _x, y):
525
+ return count_flops_attn(model, _x, y)
526
+
527
+
528
+ class UNetModel(nn.Module):
529
+ """
530
+ The full UNet model with attention and timestep embedding.
531
+ :param in_channels: channels in the input Tensor.
532
+ :param model_channels: base channel count for the model.
533
+ :param out_channels: channels in the output Tensor.
534
+ :param num_res_blocks: number of residual blocks per downsample.
535
+ :param attention_resolutions: a collection of downsample rates at which
536
+ attention will take place. May be a set, list, or tuple.
537
+ For example, if this contains 4, then at 4x downsampling, attention
538
+ will be used.
539
+ :param dropout: the dropout probability.
540
+ :param channel_mult: channel multiplier for each level of the UNet.
541
+ :param conv_resample: if True, use learned convolutions for upsampling and
542
+ downsampling.
543
+ :param dims: determines if the signal is 1D, 2D, or 3D.
544
+ :param num_classes: if specified (as an int), then this model will be
545
+ class-conditional with `num_classes` classes.
546
+ :param use_checkpoint: use gradient checkpointing to reduce memory usage.
547
+ :param num_heads: the number of attention heads in each attention layer.
548
+ :param num_heads_channels: if specified, ignore num_heads and instead use
549
+ a fixed channel width per attention head.
550
+ :param num_heads_upsample: works with num_heads to set a different number
551
+ of heads for upsampling. Deprecated.
552
+ :param use_scale_shift_norm: use a FiLM-like conditioning mechanism.
553
+ :param resblock_updown: use residual blocks for up/downsampling.
554
+ :param use_new_attention_order: use a different attention pattern for potentially
555
+ increased efficiency.
556
+ """
557
+
558
+ def __init__(
559
+ self,
560
+ image_size,
561
+ in_channels,
562
+ model_channels,
563
+ out_channels,
564
+ num_res_blocks,
565
+ attention_resolutions,
566
+ dropout=0,
567
+ channel_mult=(1, 2, 4, 8),
568
+ conv_resample=True,
569
+ dims=2,
570
+ num_classes=None,
571
+ use_checkpoint=False,
572
+ use_fp16=False,
573
+ num_heads=-1,
574
+ num_head_channels=-1,
575
+ num_heads_upsample=-1,
576
+ use_scale_shift_norm=False,
577
+ resblock_updown=False,
578
+ use_new_attention_order=False,
579
+ use_spatial_transformer=False, # custom transformer support
580
+ transformer_depth=1, # custom transformer support
581
+ context_dim=None, # custom transformer support
582
+ n_embed=None, # custom support for prediction of discrete ids into codebook of first stage vq model
583
+ legacy=True,
584
+ add_conv_in_front_of_unet=False,
585
+ ):
586
+ super().__init__()
587
+ if use_spatial_transformer:
588
+ assert context_dim is not None, 'Fool!! You forgot to include the dimension of your cross-attention conditioning...'
589
+
590
+ if context_dim is not None:
591
+ assert use_spatial_transformer, 'Fool!! You forgot to use the spatial transformer for your cross-attention conditioning...'
592
+ from omegaconf.listconfig import ListConfig
593
+ if type(context_dim) == ListConfig:
594
+ context_dim = list(context_dim)
595
+
596
+ if num_heads_upsample == -1:
597
+ num_heads_upsample = num_heads
598
+
599
+ if num_heads == -1:
600
+ assert num_head_channels != -1, 'Either num_heads or num_head_channels has to be set'
601
+
602
+ if num_head_channels == -1:
603
+ assert num_heads != -1, 'Either num_heads or num_head_channels has to be set'
604
+
605
+ self.image_size = image_size
606
+ self.in_channels = in_channels
607
+ self.model_channels = model_channels
608
+ self.out_channels = out_channels
609
+ self.num_res_blocks = num_res_blocks
610
+ self.attention_resolutions = attention_resolutions
611
+ self.dropout = dropout
612
+ self.channel_mult = channel_mult
613
+ self.conv_resample = conv_resample
614
+ self.num_classes = num_classes
615
+ self.use_checkpoint = use_checkpoint
616
+ self.dtype = th.float16 if use_fp16 else th.float32
617
+ self.num_heads = num_heads
618
+ self.num_head_channels = num_head_channels
619
+ self.num_heads_upsample = num_heads_upsample
620
+ self.predict_codebook_ids = n_embed is not None
621
+ self.add_conv_in_front_of_unet=add_conv_in_front_of_unet
622
+
623
+ time_embed_dim = model_channels * 4
624
+ self.time_embed = nn.Sequential(
625
+ linear(model_channels, time_embed_dim),
626
+ nn.SiLU(),
627
+ linear(time_embed_dim, time_embed_dim),
628
+ )
629
+
630
+ if self.num_classes is not None:
631
+ self.label_emb = nn.Embedding(num_classes, time_embed_dim)
632
+
633
+
634
+ if self.add_conv_in_front_of_unet:
635
+ self.add_resbolck = nn.ModuleList(
636
+ [
637
+ TimestepEmbedSequential(
638
+ conv_nd(dims, 9, model_channels, 3, padding=1)
639
+ )
640
+ ]
641
+ )
642
+
643
+ add_layers = [
644
+ My_ResBlock(
645
+ model_channels,
646
+ time_embed_dim,
647
+ dropout,
648
+ out_channels=model_channels,
649
+ dims=dims,
650
+ use_checkpoint=use_checkpoint,
651
+ use_scale_shift_norm=use_scale_shift_norm,
652
+ )
653
+ ]
654
+
655
+ self.add_resbolck.append(TimestepEmbedSequential(*add_layers))
656
+
657
+
658
+ self.input_blocks = nn.ModuleList(
659
+ [
660
+ TimestepEmbedSequential(
661
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
662
+ )
663
+ ]
664
+ )
665
+ self._feature_size = model_channels
666
+ input_block_chans = [model_channels]
667
+ ch = model_channels
668
+ ds = 1
669
+ for level, mult in enumerate(channel_mult):
670
+ for _ in range(num_res_blocks):
671
+ layers = [
672
+ ResBlock(
673
+ ch,
674
+ time_embed_dim,
675
+ dropout,
676
+ out_channels=mult * model_channels,
677
+ dims=dims,
678
+ use_checkpoint=use_checkpoint,
679
+ use_scale_shift_norm=use_scale_shift_norm,
680
+ )
681
+ ]
682
+ ch = mult * model_channels
683
+ if ds in attention_resolutions:
684
+ if num_head_channels == -1:
685
+ dim_head = ch // num_heads
686
+ else:
687
+ num_heads = ch // num_head_channels
688
+ dim_head = num_head_channels
689
+ if legacy:
690
+ #num_heads = 1
691
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
692
+ layers.append(
693
+ AttentionBlock(
694
+ ch,
695
+ use_checkpoint=use_checkpoint,
696
+ num_heads=num_heads,
697
+ num_head_channels=dim_head,
698
+ use_new_attention_order=use_new_attention_order,
699
+ ) if not use_spatial_transformer else SpatialTransformer(
700
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
701
+ )
702
+ )
703
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
704
+ self._feature_size += ch
705
+ input_block_chans.append(ch)
706
+ if level != len(channel_mult) - 1:
707
+ out_ch = ch
708
+ self.input_blocks.append(
709
+ TimestepEmbedSequential(
710
+ ResBlock(
711
+ ch,
712
+ time_embed_dim,
713
+ dropout,
714
+ out_channels=out_ch,
715
+ dims=dims,
716
+ use_checkpoint=use_checkpoint,
717
+ use_scale_shift_norm=use_scale_shift_norm,
718
+ down=True,
719
+ )
720
+ if resblock_updown
721
+ else Downsample(
722
+ ch, conv_resample, dims=dims, out_channels=out_ch
723
+ )
724
+ )
725
+ )
726
+ ch = out_ch
727
+ input_block_chans.append(ch)
728
+ ds *= 2
729
+ self._feature_size += ch
730
+
731
+ if num_head_channels == -1:
732
+ dim_head = ch // num_heads
733
+ else:
734
+ num_heads = ch // num_head_channels
735
+ dim_head = num_head_channels
736
+ if legacy:
737
+ #num_heads = 1
738
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
739
+ self.middle_block = TimestepEmbedSequential(
740
+ ResBlock(
741
+ ch,
742
+ time_embed_dim,
743
+ dropout,
744
+ dims=dims,
745
+ use_checkpoint=use_checkpoint,
746
+ use_scale_shift_norm=use_scale_shift_norm,
747
+ ),
748
+ AttentionBlock(
749
+ ch,
750
+ use_checkpoint=use_checkpoint,
751
+ num_heads=num_heads,
752
+ num_head_channels=dim_head,
753
+ use_new_attention_order=use_new_attention_order,
754
+ ) if not use_spatial_transformer else SpatialTransformer(
755
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
756
+ ),
757
+ ResBlock(
758
+ ch,
759
+ time_embed_dim,
760
+ dropout,
761
+ dims=dims,
762
+ use_checkpoint=use_checkpoint,
763
+ use_scale_shift_norm=use_scale_shift_norm,
764
+ ),
765
+ )
766
+ self._feature_size += ch
767
+
768
+ self.output_blocks = nn.ModuleList([])
769
+ for level, mult in list(enumerate(channel_mult))[::-1]:
770
+ for i in range(num_res_blocks + 1):
771
+ ich = input_block_chans.pop()
772
+ layers = [
773
+ ResBlock(
774
+ ch + ich,
775
+ time_embed_dim,
776
+ dropout,
777
+ out_channels=model_channels * mult,
778
+ dims=dims,
779
+ use_checkpoint=use_checkpoint,
780
+ use_scale_shift_norm=use_scale_shift_norm,
781
+ )
782
+ ]
783
+ ch = model_channels * mult
784
+ if ds in attention_resolutions:
785
+ if num_head_channels == -1:
786
+ dim_head = ch // num_heads
787
+ else:
788
+ num_heads = ch // num_head_channels
789
+ dim_head = num_head_channels
790
+ if legacy:
791
+ #num_heads = 1
792
+ dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
793
+ layers.append(
794
+ AttentionBlock(
795
+ ch,
796
+ use_checkpoint=use_checkpoint,
797
+ num_heads=num_heads_upsample,
798
+ num_head_channels=dim_head,
799
+ use_new_attention_order=use_new_attention_order,
800
+ ) if not use_spatial_transformer else SpatialTransformer(
801
+ ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
802
+ )
803
+ )
804
+ if level and i == num_res_blocks:
805
+ out_ch = ch
806
+ layers.append(
807
+ ResBlock(
808
+ ch,
809
+ time_embed_dim,
810
+ dropout,
811
+ out_channels=out_ch,
812
+ dims=dims,
813
+ use_checkpoint=use_checkpoint,
814
+ use_scale_shift_norm=use_scale_shift_norm,
815
+ up=True,
816
+ )
817
+ if resblock_updown
818
+ else Upsample(ch, conv_resample, dims=dims, out_channels=out_ch)
819
+ )
820
+ ds //= 2
821
+ self.output_blocks.append(TimestepEmbedSequential(*layers))
822
+ self._feature_size += ch
823
+
824
+ self.out = nn.Sequential(
825
+ normalization(ch),
826
+ nn.SiLU(),
827
+ zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
828
+ )
829
+ if self.predict_codebook_ids:
830
+ self.id_predictor = nn.Sequential(
831
+ normalization(ch),
832
+ conv_nd(dims, model_channels, n_embed, 1),
833
+ #nn.LogSoftmax(dim=1) # change to cross_entropy and produce non-normalized logits
834
+ )
835
+
836
+ def convert_to_fp16(self):
837
+ """
838
+ Convert the torso of the model to float16.
839
+ """
840
+ self.input_blocks.apply(convert_module_to_f16)
841
+ self.middle_block.apply(convert_module_to_f16)
842
+ self.output_blocks.apply(convert_module_to_f16)
843
+
844
+ def convert_to_fp32(self):
845
+ """
846
+ Convert the torso of the model to float32.
847
+ """
848
+ self.input_blocks.apply(convert_module_to_f32)
849
+ self.middle_block.apply(convert_module_to_f32)
850
+ self.output_blocks.apply(convert_module_to_f32)
851
+
852
+ def forward(self, x, timesteps=None, context=None, y=None,**kwargs):
853
+ """
854
+ Apply the model to an input batch.
855
+ :param x: an [N x C x ...] Tensor of inputs.
856
+ :param timesteps: a 1-D batch of timesteps.
857
+ :param context: conditioning plugged in via crossattn
858
+ :param y: an [N] Tensor of labels, if class-conditional.
859
+ :return: an [N x C x ...] Tensor of outputs.
860
+ """
861
+ assert (y is not None) == (
862
+ self.num_classes is not None
863
+ ), "must specify y if and only if the model is class-conditional"
864
+ hs = []
865
+ t_emb = timestep_embedding(timesteps, self.model_channels, repeat_only=False)
866
+ emb = self.time_embed(t_emb)
867
+
868
+ if self.num_classes is not None:
869
+ assert y.shape == (x.shape[0],)
870
+ emb = emb + self.label_emb(y)
871
+
872
+ h = x.type(self.dtype)
873
+
874
+ if self.add_conv_in_front_of_unet:
875
+ for module in self.add_resbolck:
876
+ h = module(h, emb, context)
877
+
878
+ for module in self.input_blocks:
879
+ h = module(h, emb, context)
880
+ hs.append(h)
881
+ h = self.middle_block(h, emb, context)
882
+ for module in self.output_blocks:
883
+ h = th.cat([h, hs.pop()], dim=1)
884
+ h = module(h, emb, context)
885
+ h = h.type(x.dtype)
886
+ if self.predict_codebook_ids:
887
+ return self.id_predictor(h)
888
+ else:
889
+ return self.out(h)
890
+
891
+
892
+ class EncoderUNetModel(nn.Module):
893
+ """
894
+ The half UNet model with attention and timestep embedding.
895
+ For usage, see UNet.
896
+ """
897
+
898
+ def __init__(
899
+ self,
900
+ image_size,
901
+ in_channels,
902
+ model_channels,
903
+ out_channels,
904
+ num_res_blocks,
905
+ attention_resolutions,
906
+ dropout=0,
907
+ channel_mult=(1, 2, 4, 8),
908
+ conv_resample=True,
909
+ dims=2,
910
+ use_checkpoint=False,
911
+ use_fp16=False,
912
+ num_heads=1,
913
+ num_head_channels=-1,
914
+ num_heads_upsample=-1,
915
+ use_scale_shift_norm=False,
916
+ resblock_updown=False,
917
+ use_new_attention_order=False,
918
+ pool="adaptive",
919
+ *args,
920
+ **kwargs
921
+ ):
922
+ super().__init__()
923
+
924
+ if num_heads_upsample == -1:
925
+ num_heads_upsample = num_heads
926
+
927
+ self.in_channels = in_channels
928
+ self.model_channels = model_channels
929
+ self.out_channels = out_channels
930
+ self.num_res_blocks = num_res_blocks
931
+ self.attention_resolutions = attention_resolutions
932
+ self.dropout = dropout
933
+ self.channel_mult = channel_mult
934
+ self.conv_resample = conv_resample
935
+ self.use_checkpoint = use_checkpoint
936
+ self.dtype = th.float16 if use_fp16 else th.float32
937
+ self.num_heads = num_heads
938
+ self.num_head_channels = num_head_channels
939
+ self.num_heads_upsample = num_heads_upsample
940
+
941
+ time_embed_dim = model_channels * 4
942
+ self.time_embed = nn.Sequential(
943
+ linear(model_channels, time_embed_dim),
944
+ nn.SiLU(),
945
+ linear(time_embed_dim, time_embed_dim),
946
+ )
947
+
948
+ self.input_blocks = nn.ModuleList(
949
+ [
950
+ TimestepEmbedSequential(
951
+ conv_nd(dims, in_channels, model_channels, 3, padding=1)
952
+ )
953
+ ]
954
+ )
955
+ self._feature_size = model_channels
956
+ input_block_chans = [model_channels]
957
+ ch = model_channels
958
+ ds = 1
959
+ for level, mult in enumerate(channel_mult):
960
+ for _ in range(num_res_blocks):
961
+ layers = [
962
+ ResBlock(
963
+ ch,
964
+ time_embed_dim,
965
+ dropout,
966
+ out_channels=mult * model_channels,
967
+ dims=dims,
968
+ use_checkpoint=use_checkpoint,
969
+ use_scale_shift_norm=use_scale_shift_norm,
970
+ )
971
+ ]
972
+ ch = mult * model_channels
973
+ if ds in attention_resolutions:
974
+ layers.append(
975
+ AttentionBlock(
976
+ ch,
977
+ use_checkpoint=use_checkpoint,
978
+ num_heads=num_heads,
979
+ num_head_channels=num_head_channels,
980
+ use_new_attention_order=use_new_attention_order,
981
+ )
982
+ )
983
+ self.input_blocks.append(TimestepEmbedSequential(*layers))
984
+ self._feature_size += ch
985
+ input_block_chans.append(ch)
986
+ if level != len(channel_mult) - 1:
987
+ out_ch = ch
988
+ self.input_blocks.append(
989
+ TimestepEmbedSequential(
990
+ ResBlock(
991
+ ch,
992
+ time_embed_dim,
993
+ dropout,
994
+ out_channels=out_ch,
995
+ dims=dims,
996
+ use_checkpoint=use_checkpoint,
997
+ use_scale_shift_norm=use_scale_shift_norm,
998
+ down=True,
999
+ )
1000
+ if resblock_updown
1001
+ else Downsample(
1002
+ ch, conv_resample, dims=dims, out_channels=out_ch
1003
+ )
1004
+ )
1005
+ )
1006
+ ch = out_ch
1007
+ input_block_chans.append(ch)
1008
+ ds *= 2
1009
+ self._feature_size += ch
1010
+
1011
+ self.middle_block = TimestepEmbedSequential(
1012
+ ResBlock(
1013
+ ch,
1014
+ time_embed_dim,
1015
+ dropout,
1016
+ dims=dims,
1017
+ use_checkpoint=use_checkpoint,
1018
+ use_scale_shift_norm=use_scale_shift_norm,
1019
+ ),
1020
+ AttentionBlock(
1021
+ ch,
1022
+ use_checkpoint=use_checkpoint,
1023
+ num_heads=num_heads,
1024
+ num_head_channels=num_head_channels,
1025
+ use_new_attention_order=use_new_attention_order,
1026
+ ),
1027
+ ResBlock(
1028
+ ch,
1029
+ time_embed_dim,
1030
+ dropout,
1031
+ dims=dims,
1032
+ use_checkpoint=use_checkpoint,
1033
+ use_scale_shift_norm=use_scale_shift_norm,
1034
+ ),
1035
+ )
1036
+ self._feature_size += ch
1037
+ self.pool = pool
1038
+ if pool == "adaptive":
1039
+ self.out = nn.Sequential(
1040
+ normalization(ch),
1041
+ nn.SiLU(),
1042
+ nn.AdaptiveAvgPool2d((1, 1)),
1043
+ zero_module(conv_nd(dims, ch, out_channels, 1)),
1044
+ nn.Flatten(),
1045
+ )
1046
+ elif pool == "attention":
1047
+ assert num_head_channels != -1
1048
+ self.out = nn.Sequential(
1049
+ normalization(ch),
1050
+ nn.SiLU(),
1051
+ AttentionPool2d(
1052
+ (image_size // ds), ch, num_head_channels, out_channels
1053
+ ),
1054
+ )
1055
+ elif pool == "spatial":
1056
+ self.out = nn.Sequential(
1057
+ nn.Linear(self._feature_size, 2048),
1058
+ nn.ReLU(),
1059
+ nn.Linear(2048, self.out_channels),
1060
+ )
1061
+ elif pool == "spatial_v2":
1062
+ self.out = nn.Sequential(
1063
+ nn.Linear(self._feature_size, 2048),
1064
+ normalization(2048),
1065
+ nn.SiLU(),
1066
+ nn.Linear(2048, self.out_channels),
1067
+ )
1068
+ else:
1069
+ raise NotImplementedError(f"Unexpected {pool} pooling")
1070
+
1071
+ def convert_to_fp16(self):
1072
+ """
1073
+ Convert the torso of the model to float16.
1074
+ """
1075
+ self.input_blocks.apply(convert_module_to_f16)
1076
+ self.middle_block.apply(convert_module_to_f16)
1077
+
1078
+ def convert_to_fp32(self):
1079
+ """
1080
+ Convert the torso of the model to float32.
1081
+ """
1082
+ self.input_blocks.apply(convert_module_to_f32)
1083
+ self.middle_block.apply(convert_module_to_f32)
1084
+
1085
+ def forward(self, x, timesteps):
1086
+ """
1087
+ Apply the model to an input batch.
1088
+ :param x: an [N x C x ...] Tensor of inputs.
1089
+ :param timesteps: a 1-D batch of timesteps.
1090
+ :return: an [N x K] Tensor of outputs.
1091
+ """
1092
+ emb = self.time_embed(timestep_embedding(timesteps, self.model_channels))
1093
+
1094
+ results = []
1095
+ h = x.type(self.dtype)
1096
+ for module in self.input_blocks:
1097
+ h = module(h, emb)
1098
+ if self.pool.startswith("spatial"):
1099
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
1100
+ h = self.middle_block(h, emb)
1101
+ if self.pool.startswith("spatial"):
1102
+ results.append(h.type(x.dtype).mean(dim=(2, 3)))
1103
+ h = th.cat(results, axis=-1)
1104
+ return self.out(h)
1105
+ else:
1106
+ h = h.type(x.dtype)
1107
+ return self.out(h)
1108
+