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.
- libcom/__init__.py +23 -0
- libcom/color_transfer/__init__.py +3 -0
- libcom/color_transfer/reinhard.py +57 -0
- libcom/fopa_heat_map/__init__.py +4 -0
- libcom/fopa_heat_map/fopa_heat_map.py +212 -0
- libcom/fopa_heat_map/source/__init__.py +0 -0
- libcom/fopa_heat_map/source/backbone/ResNet.py +229 -0
- libcom/fopa_heat_map/source/backbone/__init__.py +0 -0
- libcom/fopa_heat_map/source/data/OBdataset.py +292 -0
- libcom/fopa_heat_map/source/data/__init__.py +0 -0
- libcom/fopa_heat_map/source/data/all_transforms.py +25 -0
- libcom/fopa_heat_map/source/network/BaseBlocks.py +26 -0
- libcom/fopa_heat_map/source/network/DynamicModules.py +43 -0
- libcom/fopa_heat_map/source/network/ObPlaNet_simple.py +112 -0
- libcom/fopa_heat_map/source/network/__init__.py +1 -0
- libcom/fopa_heat_map/source/network/tensor_ops.py +37 -0
- libcom/fopa_heat_map/source/prepare_multi_fg_scales.py +85 -0
- libcom/fos_score/__init__.py +4 -0
- libcom/fos_score/fos_score_prediction.py +218 -0
- libcom/fos_score/source/__init__.py +0 -0
- libcom/fos_score/source/config/__init__.py +1 -0
- libcom/fos_score/source/config/config.py +68 -0
- libcom/fos_score/source/config/config.sfosd.yaml +43 -0
- libcom/fos_score/source/config/config_rfosd.yaml +43 -0
- libcom/fos_score/source/loss_function.py +118 -0
- libcom/fos_score/source/networks.py +355 -0
- libcom/harmony_score/__init__.py +3 -0
- libcom/harmony_score/harmony_score_prediction.py +119 -0
- libcom/harmony_score/source/__init__.py +0 -0
- libcom/harmony_score/source/bargainnet.py +226 -0
- libcom/image_harmonization/__init__.py +4 -0
- libcom/image_harmonization/image_harmonization.py +193 -0
- libcom/image_harmonization/source/__init__.py +0 -0
- libcom/image_harmonization/source/functions.py +747 -0
- libcom/image_harmonization/source/pct_net.py +85 -0
- libcom/image_harmonization/source/src/__init__.py +0 -0
- libcom/image_harmonization/source/src/lbm/__init__.py +0 -0
- libcom/image_harmonization/source/src/lbm/config.py +141 -0
- libcom/image_harmonization/source/src/lbm/data/__init__.py +62 -0
- libcom/image_harmonization/source/src/lbm/data/datasets/__init__.py +9 -0
- libcom/image_harmonization/source/src/lbm/data/datasets/collation_fn.py +41 -0
- libcom/image_harmonization/source/src/lbm/data/datasets/dataset.py +243 -0
- libcom/image_harmonization/source/src/lbm/data/datasets/datasets_config.py +42 -0
- libcom/image_harmonization/source/src/lbm/data/filters/__init__.py +12 -0
- libcom/image_harmonization/source/src/lbm/data/filters/base.py +21 -0
- libcom/image_harmonization/source/src/lbm/data/filters/filter_wrapper.py +36 -0
- libcom/image_harmonization/source/src/lbm/data/filters/filters.py +33 -0
- libcom/image_harmonization/source/src/lbm/data/filters/filters_config.py +32 -0
- libcom/image_harmonization/source/src/lbm/data/mappers/__init__.py +19 -0
- libcom/image_harmonization/source/src/lbm/data/mappers/base.py +26 -0
- libcom/image_harmonization/source/src/lbm/data/mappers/mappers.py +135 -0
- libcom/image_harmonization/source/src/lbm/data/mappers/mappers_config.py +109 -0
- libcom/image_harmonization/source/src/lbm/data/mappers/mappers_wrapper.py +31 -0
- libcom/image_harmonization/source/src/lbm/inference/__init__.py +4 -0
- libcom/image_harmonization/source/src/lbm/inference/inference.py +70 -0
- libcom/image_harmonization/source/src/lbm/inference/utils.py +222 -0
- libcom/image_harmonization/source/src/lbm/models/__init__.py +0 -0
- libcom/image_harmonization/source/src/lbm/models/base/__init__.py +4 -0
- libcom/image_harmonization/source/src/lbm/models/base/base_model.py +66 -0
- libcom/image_harmonization/source/src/lbm/models/base/model_config.py +8 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/__init__.py +4 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/base/__init__.py +4 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/base/base_conditioner.py +60 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/base/base_conditioner_config.py +27 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/conditioners_wrapper.py +114 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/__init__.py +4 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/latents_concat_embedder_config.py +31 -0
- libcom/image_harmonization/source/src/lbm/models/embedders/latents_concat/latents_concat_embedder_model.py +80 -0
- libcom/image_harmonization/source/src/lbm/models/lbm/__init__.py +4 -0
- libcom/image_harmonization/source/src/lbm/models/lbm/lbm_config.py +101 -0
- libcom/image_harmonization/source/src/lbm/models/lbm/lbm_model.py +359 -0
- libcom/image_harmonization/source/src/lbm/models/unets/__init__.py +14 -0
- libcom/image_harmonization/source/src/lbm/models/unets/unet.py +148 -0
- libcom/image_harmonization/source/src/lbm/models/utils.py +377 -0
- libcom/image_harmonization/source/src/lbm/models/vae/__init__.py +4 -0
- libcom/image_harmonization/source/src/lbm/models/vae/autoencoderKL.py +136 -0
- libcom/image_harmonization/source/src/lbm/models/vae/autoencoderKL_config.py +27 -0
- libcom/image_harmonization/source/src/lbm/trainer/__init__.py +85 -0
- libcom/image_harmonization/source/src/lbm/trainer/loggers.py +324 -0
- libcom/image_harmonization/source/src/lbm/trainer/trainer.py +199 -0
- libcom/image_harmonization/source/src/lbm/trainer/training_config.py +82 -0
- libcom/image_harmonization/source/src/lbm/trainer/utils.py +193 -0
- libcom/inharmonious_region_localization/__init__.py +4 -0
- libcom/inharmonious_region_localization/inharmonious_region_localization.py +97 -0
- libcom/inharmonious_region_localization/source/__init__.py +0 -0
- libcom/inharmonious_region_localization/source/blocks.py +368 -0
- libcom/inharmonious_region_localization/source/functions.py +679 -0
- libcom/inharmonious_region_localization/source/madis_net.py +79 -0
- libcom/kontext_blending_harmonization/__init__.py +3 -0
- libcom/kontext_blending_harmonization/kontext_blending_harmonization.py +148 -0
- libcom/kontext_blending_harmonization/source/__init__.py +0 -0
- libcom/kontext_blending_harmonization/source/pipeline.py +1135 -0
- libcom/naive_composition/__init__.py +3 -0
- libcom/naive_composition/generate_composite_image.py +116 -0
- libcom/opa_score/__init__.py +3 -0
- libcom/opa_score/opa_score_prediction.py +101 -0
- libcom/opa_score/source/__init__.py +3 -0
- libcom/opa_score/source/object_place_net.py +55 -0
- libcom/opa_score/source/oblect_place_config.py +66 -0
- libcom/opa_score/source/resnet_4ch.py +213 -0
- libcom/os_insert/__init__.py +3 -0
- libcom/os_insert/diffusers_osinsert/__init__.py +78 -0
- libcom/os_insert/diffusers_osinsert/_patched_pipeline_flux_fill.py +878 -0
- libcom/os_insert/os_insert.py +534 -0
- libcom/os_insert/source/__init__.py +1 -0
- libcom/os_insert/source/ia_utils.py +183 -0
- libcom/os_insert/source/insertanything_infer.py +529 -0
- libcom/os_insert/source/ldm/__init__.py +0 -0
- libcom/os_insert/source/ldm/data/__init__.py +0 -0
- libcom/os_insert/source/ldm/data/base.py +23 -0
- libcom/os_insert/source/ldm/data/datamodule.py +128 -0
- libcom/os_insert/source/ldm/data/imagenet.py +394 -0
- libcom/os_insert/source/ldm/data/lsun.py +92 -0
- libcom/os_insert/source/ldm/data/open_images.py +728 -0
- libcom/os_insert/source/ldm/lr_scheduler.py +98 -0
- libcom/os_insert/source/ldm/models/__init__.py +0 -0
- libcom/os_insert/source/ldm/models/autoencoder.py +443 -0
- libcom/os_insert/source/ldm/models/diffusion/__init__.py +0 -0
- libcom/os_insert/source/ldm/models/diffusion/classifier.py +267 -0
- libcom/os_insert/source/ldm/models/diffusion/ddim.py +263 -0
- libcom/os_insert/source/ldm/models/diffusion/ddpm.py +1417 -0
- libcom/os_insert/source/ldm/models/diffusion/plms.py +252 -0
- libcom/os_insert/source/ldm/modules/__init__.py +0 -0
- libcom/os_insert/source/ldm/modules/attention.py +261 -0
- libcom/os_insert/source/ldm/modules/diffusionmodules/__init__.py +0 -0
- libcom/os_insert/source/ldm/modules/diffusionmodules/model.py +835 -0
- libcom/os_insert/source/ldm/modules/diffusionmodules/openaimodel.py +1108 -0
- libcom/os_insert/source/ldm/modules/diffusionmodules/util.py +267 -0
- libcom/os_insert/source/ldm/modules/distributions/__init__.py +0 -0
- libcom/os_insert/source/ldm/modules/distributions/distributions.py +92 -0
- libcom/os_insert/source/ldm/modules/ema.py +76 -0
- libcom/os_insert/source/ldm/modules/encoders/__init__.py +0 -0
- libcom/os_insert/source/ldm/modules/encoders/modules.py +190 -0
- libcom/os_insert/source/ldm/modules/encoders/xf.py +130 -0
- libcom/os_insert/source/ldm/modules/losses/__init__.py +1 -0
- libcom/os_insert/source/ldm/modules/losses/contperceptual.py +111 -0
- libcom/os_insert/source/ldm/modules/losses/vqperceptual.py +167 -0
- libcom/os_insert/source/ldm/modules/x_transformer.py +641 -0
- libcom/os_insert/source/ldm/util.py +203 -0
- libcom/os_insert/source/objectstitch_data.py +66 -0
- libcom/os_insert/source/objectstitch_infer.py +618 -0
- libcom/os_insert/source/sam_on_objectstitch.py +253 -0
- libcom/os_insert/source/utils.py +41 -0
- libcom/os_insert/source/v1.yaml +108 -0
- libcom/painterly_image_harmonization/__init__.py +4 -0
- libcom/painterly_image_harmonization/painterly_image_harmonization.py +215 -0
- libcom/painterly_image_harmonization/source/PHDNet/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDNet/networks.py +202 -0
- libcom/painterly_image_harmonization/source/PHDNet/phdnet.py +47 -0
- libcom/painterly_image_harmonization/source/PHDNet/phdnet_config.py +18 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/inference_base.py +300 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/lr_scheduler.py +98 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/autoencoder.py +211 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/__init__.py +3 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/ddim.py +336 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/ddpm.py +1400 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/dpm_solver.py +1217 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/plms.py +243 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/scheduling_pndm.py +518 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/attention.py +378 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/model.py +857 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/openaimodel.py +823 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/diffusionmodules/util.py +270 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/distributions/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/distributions/distributions.py +92 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/ema.py +80 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/adapter.py +213 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/encoders/modules.py +82 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/__init__.py +1 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/api.py +269 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/api.py +175 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/base_model.py +16 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/blocks.py +342 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/dpt_depth.py +109 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/midas_net.py +76 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/midas_net_custom.py +128 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/transforms.py +234 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/midas/vit.py +491 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/midas/utils.py +189 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/model_edge.py +653 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/api.py +35 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/body.py +209 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/hand.py +75 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/model.py +178 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/openpose/util.py +203 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/extra_condition/utils.py +72 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/fusion/__init__.py +0 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/fusion/dual_encoder_fusion.py +93 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/__init__.py +2 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/bsrgan.py +730 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/bsrgan_light.py +651 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/modules/image_degradation/utils_image.py +916 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/ldm/util.py +200 -0
- libcom/painterly_image_harmonization/source/PHDiffusion/stable_diffusion.yaml +75 -0
- libcom/painterly_image_harmonization/source/__init__.py +0 -0
- libcom/reflection_generation/__init__.py +3 -0
- libcom/reflection_generation/reflection_generation.py +174 -0
- libcom/reflection_generation/source/PostProcessModel.py +513 -0
- libcom/reflection_generation/source/__init__.py +0 -0
- libcom/reflection_generation/source/cldm/__init__.py +0 -0
- libcom/reflection_generation/source/cldm/base_network.py +166 -0
- libcom/reflection_generation/source/cldm/cldm.py +509 -0
- libcom/reflection_generation/source/cldm/ddim_hacked.py +317 -0
- libcom/reflection_generation/source/cldm/hack.py +111 -0
- libcom/reflection_generation/source/cldm/logger.py +127 -0
- libcom/reflection_generation/source/cldm/model.py +26 -0
- libcom/reflection_generation/source/cldm_v15.yaml +81 -0
- libcom/reflection_generation/source/cluster_feature.py +109 -0
- libcom/reflection_generation/source/ldm/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/models/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/models/autoencoder.py +219 -0
- libcom/reflection_generation/source/ldm/models/diffusion/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/models/diffusion/attention_processor.py +188 -0
- libcom/reflection_generation/source/ldm/models/diffusion/ddim.py +340 -0
- libcom/reflection_generation/source/ldm/models/diffusion/ddpm.py +1892 -0
- libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
- libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
- libcom/reflection_generation/source/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
- libcom/reflection_generation/source/ldm/models/diffusion/ip_adapter.py +57 -0
- libcom/reflection_generation/source/ldm/models/diffusion/plms.py +244 -0
- libcom/reflection_generation/source/ldm/models/diffusion/sampling_util.py +22 -0
- libcom/reflection_generation/source/ldm/modules/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/modules/attention.py +341 -0
- libcom/reflection_generation/source/ldm/modules/diffusionmodules/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/modules/diffusionmodules/model.py +852 -0
- libcom/reflection_generation/source/ldm/modules/diffusionmodules/openaimodel.py +786 -0
- libcom/reflection_generation/source/ldm/modules/diffusionmodules/upscaling.py +81 -0
- libcom/reflection_generation/source/ldm/modules/diffusionmodules/util.py +280 -0
- libcom/reflection_generation/source/ldm/modules/distributions/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/modules/distributions/distributions.py +92 -0
- libcom/reflection_generation/source/ldm/modules/ema.py +80 -0
- libcom/reflection_generation/source/ldm/modules/encoders/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/modules/encoders/modules.py +214 -0
- libcom/reflection_generation/source/ldm/modules/image_degradation/__init__.py +0 -0
- libcom/reflection_generation/source/ldm/modules/image_degradation/bsrgan.py +730 -0
- libcom/reflection_generation/source/ldm/modules/image_degradation/bsrgan_light.py +651 -0
- libcom/reflection_generation/source/ldm/modules/image_degradation/utils_image.py +916 -0
- libcom/reflection_generation/source/ldm/util.py +198 -0
- libcom/reflection_generation/source/local_clip.py +749 -0
- libcom/reflection_generation/source/tool_add_control.py +49 -0
- libcom/shadow_generation/__init__.py +3 -0
- libcom/shadow_generation/shadow_generation.py +754 -0
- libcom/shadow_generation/source/PostProcessModel.py +511 -0
- libcom/shadow_generation/source/__init__.py +0 -0
- libcom/shadow_generation/source/attention_processor.py +234 -0
- libcom/shadow_generation/source/cldm/__init__.py +0 -0
- libcom/shadow_generation/source/cldm/base_network.py +166 -0
- libcom/shadow_generation/source/cldm/cldm.py +524 -0
- libcom/shadow_generation/source/cldm/model.py +28 -0
- libcom/shadow_generation/source/ldm/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/models/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/models/autoencoder.py +219 -0
- libcom/shadow_generation/source/ldm/models/diffusion/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/models/diffusion/attention_processor.py +188 -0
- libcom/shadow_generation/source/ldm/models/diffusion/ddim.py +340 -0
- libcom/shadow_generation/source/ldm/models/diffusion/ddpm.py +1893 -0
- libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/__init__.py +1 -0
- libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/dpm_solver.py +1154 -0
- libcom/shadow_generation/source/ldm/models/diffusion/dpm_solver/sampler.py +87 -0
- libcom/shadow_generation/source/ldm/models/diffusion/ip_adapter.py +57 -0
- libcom/shadow_generation/source/ldm/models/diffusion/plms.py +244 -0
- libcom/shadow_generation/source/ldm/models/diffusion/sampling_util.py +22 -0
- libcom/shadow_generation/source/ldm/modules/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/modules/attention.py +341 -0
- libcom/shadow_generation/source/ldm/modules/diffusionmodules/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/modules/diffusionmodules/model.py +852 -0
- libcom/shadow_generation/source/ldm/modules/diffusionmodules/openaimodel.py +786 -0
- libcom/shadow_generation/source/ldm/modules/diffusionmodules/upscaling.py +81 -0
- libcom/shadow_generation/source/ldm/modules/diffusionmodules/util.py +270 -0
- libcom/shadow_generation/source/ldm/modules/distributions/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/modules/distributions/distributions.py +92 -0
- libcom/shadow_generation/source/ldm/modules/ema.py +80 -0
- libcom/shadow_generation/source/ldm/modules/encoders/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/modules/encoders/modules.py +214 -0
- libcom/shadow_generation/source/ldm/modules/image_degradation/__init__.py +2 -0
- libcom/shadow_generation/source/ldm/modules/image_degradation/bsrgan.py +730 -0
- libcom/shadow_generation/source/ldm/modules/image_degradation/bsrgan_light.py +651 -0
- libcom/shadow_generation/source/ldm/modules/image_degradation/utils_image.py +916 -0
- libcom/shadow_generation/source/ldm/modules/midas/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/modules/midas/api.py +170 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/__init__.py +0 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/base_model.py +16 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/blocks.py +342 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/dpt_depth.py +109 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/midas_net.py +76 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/midas_net_custom.py +128 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/transforms.py +234 -0
- libcom/shadow_generation/source/ldm/modules/midas/midas/vit.py +491 -0
- libcom/shadow_generation/source/ldm/modules/midas/utils.py +189 -0
- libcom/shadow_generation/source/ldm/util.py +199 -0
- libcom/utils/__init__.py +0 -0
- libcom/utils/environment.py +12 -0
- libcom/utils/model_download.py +67 -0
- libcom/utils/process_image.py +108 -0
- libcom-0.1.8.dist-info/METADATA +157 -0
- libcom-0.1.8.dist-info/RECORD +310 -0
- libcom-0.1.8.dist-info/WHEEL +5 -0
- libcom-0.1.8.dist-info/licenses/LICENSE +201 -0
- libcom-0.1.8.dist-info/top_level.txt +1 -0
libcom/painterly_image_harmonization/source/PHDiffusion/ldm/models/diffusion/scheduling_pndm.py
ADDED
|
@@ -0,0 +1,518 @@
|
|
|
1
|
+
# Copyright 2023 Zhejiang University Team and 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
|
+
# DISCLAIMER: This file is strongly influenced by https://github.com/ermongroup/ddim
|
|
16
|
+
from collections import OrderedDict
|
|
17
|
+
from tqdm.auto import tqdm
|
|
18
|
+
import math
|
|
19
|
+
from typing import Any,List, Optional, Tuple, Union
|
|
20
|
+
from dataclasses import dataclass
|
|
21
|
+
import numpy as np
|
|
22
|
+
import torch
|
|
23
|
+
from dataclasses import fields
|
|
24
|
+
# Copied from diffusers.schedulers.scheduling_ddpm.betas_for_alpha_bar
|
|
25
|
+
def betas_for_alpha_bar(num_diffusion_timesteps, max_beta=0.999):
|
|
26
|
+
"""
|
|
27
|
+
Create a beta schedule that discretizes the given alpha_t_bar function, which defines the cumulative product of
|
|
28
|
+
(1-beta) over time from t = [0,1].
|
|
29
|
+
|
|
30
|
+
Contains a function alpha_bar that takes an argument t and transforms it to the cumulative product of (1-beta) up
|
|
31
|
+
to that part of the diffusion process.
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
num_diffusion_timesteps (`int`): the number of betas to produce.
|
|
36
|
+
max_beta (`float`): the maximum beta to use; use values lower than 1 to
|
|
37
|
+
prevent singularities.
|
|
38
|
+
|
|
39
|
+
Returns:
|
|
40
|
+
betas (`np.ndarray`): the betas used by the scheduler to step the model outputs
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
def alpha_bar(time_step):
|
|
44
|
+
return math.cos((time_step + 0.008) / 1.008 * math.pi / 2) ** 2
|
|
45
|
+
|
|
46
|
+
betas = []
|
|
47
|
+
for i in range(num_diffusion_timesteps):
|
|
48
|
+
t1 = i / num_diffusion_timesteps
|
|
49
|
+
t2 = (i + 1) / num_diffusion_timesteps
|
|
50
|
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
|
51
|
+
return torch.tensor(betas, dtype=torch.float32)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class BaseOutput(OrderedDict):
|
|
55
|
+
"""
|
|
56
|
+
Base class for all model outputs as dataclass. Has a `__getitem__` that allows indexing by integer or slice (like a
|
|
57
|
+
tuple) or strings (like a dictionary) that will ignore the `None` attributes. Otherwise behaves like a regular
|
|
58
|
+
python dictionary.
|
|
59
|
+
|
|
60
|
+
<Tip warning={true}>
|
|
61
|
+
|
|
62
|
+
You can't unpack a `BaseOutput` directly. Use the [`~utils.BaseOutput.to_tuple`] method to convert it to a tuple
|
|
63
|
+
before.
|
|
64
|
+
|
|
65
|
+
</Tip>
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
def __post_init__(self):
|
|
69
|
+
class_fields = fields(self)
|
|
70
|
+
|
|
71
|
+
# Safety and consistency checks
|
|
72
|
+
if not len(class_fields):
|
|
73
|
+
raise ValueError(f"{self.__class__.__name__} has no fields.")
|
|
74
|
+
|
|
75
|
+
first_field = getattr(self, class_fields[0].name)
|
|
76
|
+
other_fields_are_none = all(getattr(self, field.name) is None for field in class_fields[1:])
|
|
77
|
+
|
|
78
|
+
if other_fields_are_none and isinstance(first_field, dict):
|
|
79
|
+
for key, value in first_field.items():
|
|
80
|
+
self[key] = value
|
|
81
|
+
else:
|
|
82
|
+
for field in class_fields:
|
|
83
|
+
v = getattr(self, field.name)
|
|
84
|
+
if v is not None:
|
|
85
|
+
self[field.name] = v
|
|
86
|
+
|
|
87
|
+
def __delitem__(self, *args, **kwargs):
|
|
88
|
+
raise Exception(f"You cannot use ``__delitem__`` on a {self.__class__.__name__} instance.")
|
|
89
|
+
|
|
90
|
+
def setdefault(self, *args, **kwargs):
|
|
91
|
+
raise Exception(f"You cannot use ``setdefault`` on a {self.__class__.__name__} instance.")
|
|
92
|
+
|
|
93
|
+
def pop(self, *args, **kwargs):
|
|
94
|
+
raise Exception(f"You cannot use ``pop`` on a {self.__class__.__name__} instance.")
|
|
95
|
+
|
|
96
|
+
def update(self, *args, **kwargs):
|
|
97
|
+
raise Exception(f"You cannot use ``update`` on a {self.__class__.__name__} instance.")
|
|
98
|
+
|
|
99
|
+
def __getitem__(self, k):
|
|
100
|
+
if isinstance(k, str):
|
|
101
|
+
inner_dict = dict(self.items())
|
|
102
|
+
return inner_dict[k]
|
|
103
|
+
else:
|
|
104
|
+
return self.to_tuple()[k]
|
|
105
|
+
|
|
106
|
+
def __setattr__(self, name, value):
|
|
107
|
+
if name in self.keys() and value is not None:
|
|
108
|
+
# Don't call self.__setitem__ to avoid recursion errors
|
|
109
|
+
super().__setitem__(name, value)
|
|
110
|
+
super().__setattr__(name, value)
|
|
111
|
+
|
|
112
|
+
def __setitem__(self, key, value):
|
|
113
|
+
# Will raise a KeyException if needed
|
|
114
|
+
super().__setitem__(key, value)
|
|
115
|
+
# Don't call self.__setattr__ to avoid recursion errors
|
|
116
|
+
super().__setattr__(key, value)
|
|
117
|
+
|
|
118
|
+
def to_tuple(self) -> Tuple[Any]:
|
|
119
|
+
"""
|
|
120
|
+
Convert self to a tuple containing all the attributes/keys that are not `None`.
|
|
121
|
+
"""
|
|
122
|
+
return tuple(self[k] for k in self.keys())
|
|
123
|
+
|
|
124
|
+
|
|
125
|
+
@dataclass
|
|
126
|
+
class SchedulerOutput(BaseOutput):
|
|
127
|
+
"""
|
|
128
|
+
Base class for the scheduler's step function output.
|
|
129
|
+
|
|
130
|
+
Args:
|
|
131
|
+
prev_sample (`torch.FloatTensor` of shape `(batch_size, num_channels, height, width)` for images):
|
|
132
|
+
Computed sample (x_{t-1}) of previous timestep. `prev_sample` should be used as next model input in the
|
|
133
|
+
denoising loop.
|
|
134
|
+
"""
|
|
135
|
+
|
|
136
|
+
prev_sample: torch.FloatTensor
|
|
137
|
+
|
|
138
|
+
class PNDMScheduler(object):
|
|
139
|
+
"""
|
|
140
|
+
Pseudo numerical methods for diffusion models (PNDM) proposes using more advanced ODE integration techniques,
|
|
141
|
+
namely Runge-Kutta method and a linear multi-step method.
|
|
142
|
+
|
|
143
|
+
[`~ConfigMixin`] takes care of storing all config attributes that are passed in the scheduler's `__init__`
|
|
144
|
+
function, such as `num_train_timesteps`. They can be accessed via `scheduler.config.num_train_timesteps`.
|
|
145
|
+
[`SchedulerMixin`] provides general loading and saving functionality via the [`SchedulerMixin.save_pretrained`] and
|
|
146
|
+
[`~SchedulerMixin.from_pretrained`] functions.
|
|
147
|
+
|
|
148
|
+
For more details, see the original paper: https://arxiv.org/abs/2202.09778
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
num_train_timesteps (`int`): number of diffusion steps used to train the model.
|
|
152
|
+
beta_start (`float`): the starting `beta` value of inference.
|
|
153
|
+
beta_end (`float`): the final `beta` value.
|
|
154
|
+
beta_schedule (`str`):
|
|
155
|
+
the beta schedule, a mapping from a beta range to a sequence of betas for stepping the model. Choose from
|
|
156
|
+
`linear`, `scaled_linear`, or `squaredcos_cap_v2`.
|
|
157
|
+
trained_betas (`np.ndarray`, optional):
|
|
158
|
+
option to pass an array of betas directly to the constructor to bypass `beta_start`, `beta_end` etc.
|
|
159
|
+
skip_prk_steps (`bool`):
|
|
160
|
+
allows the scheduler to skip the Runge-Kutta steps that are defined in the original paper as being required
|
|
161
|
+
before plms steps; defaults to `False`.
|
|
162
|
+
set_alpha_to_one (`bool`, default `False`):
|
|
163
|
+
each diffusion step uses the value of alphas product at that step and at the previous one. For the final
|
|
164
|
+
step there is no previous alpha. When this option is `True` the previous alpha product is fixed to `1`,
|
|
165
|
+
otherwise it uses the value of alpha at step 0.
|
|
166
|
+
prediction_type (`str`, default `epsilon`, optional):
|
|
167
|
+
prediction type of the scheduler function, one of `epsilon` (predicting the noise of the diffusion process)
|
|
168
|
+
or `v_prediction` (see section 2.4 https://imagen.research.google/video/paper.pdf)
|
|
169
|
+
steps_offset (`int`, default `0`):
|
|
170
|
+
an offset added to the inference steps. You can use a combination of `offset=1` and
|
|
171
|
+
`set_alpha_to_one=False`, to make the last step use step 0 for the previous alpha product, as done in
|
|
172
|
+
stable diffusion.
|
|
173
|
+
|
|
174
|
+
"""
|
|
175
|
+
|
|
176
|
+
order = 1
|
|
177
|
+
|
|
178
|
+
def __init__(
|
|
179
|
+
self,
|
|
180
|
+
num_train_timesteps: int = 1000,
|
|
181
|
+
beta_start: float = 0.0001,
|
|
182
|
+
beta_end: float = 0.02,
|
|
183
|
+
beta_schedule: str = "linear",
|
|
184
|
+
trained_betas: Optional[Union[np.ndarray, List[float]]] = None,
|
|
185
|
+
skip_prk_steps: bool = False,
|
|
186
|
+
set_alpha_to_one: bool = False,
|
|
187
|
+
prediction_type: str = "epsilon",
|
|
188
|
+
steps_offset: int = 0,
|
|
189
|
+
):
|
|
190
|
+
self.num_train_timesteps = num_train_timesteps
|
|
191
|
+
self.skip_prk_steps = skip_prk_steps
|
|
192
|
+
self.beta_start = beta_start
|
|
193
|
+
self.beta_end = beta_end
|
|
194
|
+
self.beta_schedule = beta_schedule
|
|
195
|
+
self.trained_betas = trained_betas
|
|
196
|
+
self.set_alpha_to_one = set_alpha_to_one
|
|
197
|
+
self.prediction_type = prediction_type
|
|
198
|
+
self.steps_offset = steps_offset
|
|
199
|
+
|
|
200
|
+
if trained_betas is not None:
|
|
201
|
+
self.betas = torch.tensor(trained_betas, dtype=torch.float32)
|
|
202
|
+
elif beta_schedule == "linear":
|
|
203
|
+
self.betas = torch.linspace(beta_start, beta_end, num_train_timesteps, dtype=torch.float32)
|
|
204
|
+
elif beta_schedule == "scaled_linear":
|
|
205
|
+
# this schedule is very specific to the latent diffusion model.
|
|
206
|
+
self.betas = (
|
|
207
|
+
torch.linspace(beta_start**0.5, beta_end**0.5, num_train_timesteps, dtype=torch.float32) ** 2
|
|
208
|
+
)
|
|
209
|
+
elif beta_schedule == "squaredcos_cap_v2":
|
|
210
|
+
# Glide cosine schedule
|
|
211
|
+
self.betas = betas_for_alpha_bar(num_train_timesteps)
|
|
212
|
+
else:
|
|
213
|
+
raise NotImplementedError(f"{beta_schedule} does is not implemented for {self.__class__}")
|
|
214
|
+
|
|
215
|
+
self.alphas = 1.0 - self.betas
|
|
216
|
+
self.alphas_cumprod = torch.cumprod(self.alphas, dim=0)
|
|
217
|
+
|
|
218
|
+
self.final_alpha_cumprod = torch.tensor(1.0) if set_alpha_to_one else self.alphas_cumprod[0]
|
|
219
|
+
|
|
220
|
+
# standard deviation of the initial noise distribution
|
|
221
|
+
self.init_noise_sigma = 1.0
|
|
222
|
+
|
|
223
|
+
# For now we only support F-PNDM, i.e. the runge-kutta method
|
|
224
|
+
# For more information on the algorithm please take a look at the paper: https://arxiv.org/pdf/2202.09778.pdf
|
|
225
|
+
# mainly at formula (9), (12), (13) and the Algorithm 2.
|
|
226
|
+
self.pndm_order = 4
|
|
227
|
+
|
|
228
|
+
# running values
|
|
229
|
+
self.cur_model_output = 0
|
|
230
|
+
self.counter = 0
|
|
231
|
+
self.cur_sample = None
|
|
232
|
+
self.ets = []
|
|
233
|
+
|
|
234
|
+
# setable values
|
|
235
|
+
self.num_inference_steps = None
|
|
236
|
+
self._timesteps = np.arange(0, num_train_timesteps)[::-1].copy()
|
|
237
|
+
self.prk_timesteps = None
|
|
238
|
+
self.plms_timesteps = None
|
|
239
|
+
self.timesteps = None
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def set_timesteps(self, num_inference_steps: int, device: Union[str, torch.device] = None):
|
|
246
|
+
"""
|
|
247
|
+
Sets the discrete timesteps used for the diffusion chain. Supporting function to be run before inference.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
num_inference_steps (`int`):
|
|
251
|
+
the number of diffusion steps used when generating samples with a pre-trained model.
|
|
252
|
+
"""
|
|
253
|
+
|
|
254
|
+
self.num_inference_steps = num_inference_steps
|
|
255
|
+
step_ratio = self.num_train_timesteps // self.num_inference_steps
|
|
256
|
+
# creates integer timesteps by multiplying by ratio
|
|
257
|
+
# casting to int to avoid issues when num_inference_step is power of 3
|
|
258
|
+
self._timesteps = (np.arange(0, num_inference_steps) * step_ratio).round()
|
|
259
|
+
self._timesteps += self.steps_offset
|
|
260
|
+
|
|
261
|
+
if self.skip_prk_steps:
|
|
262
|
+
# for some models like stable diffusion the prk steps can/should be skipped to
|
|
263
|
+
# produce better results. When using PNDM with `self.config.skip_prk_steps` the implementation
|
|
264
|
+
# is based on crowsonkb's PLMS sampler implementation: https://github.com/CompVis/latent-diffusion/pull/51
|
|
265
|
+
self.prk_timesteps = np.array([])
|
|
266
|
+
self.plms_timesteps = np.concatenate([self._timesteps[:-1], self._timesteps[-2:-1], self._timesteps[-1:]])[
|
|
267
|
+
::-1
|
|
268
|
+
].copy()
|
|
269
|
+
else:
|
|
270
|
+
prk_timesteps = np.array(self._timesteps[-self.pndm_order :]).repeat(2) + np.tile(
|
|
271
|
+
np.array([0, self.num_train_timesteps // num_inference_steps // 2]), self.pndm_order
|
|
272
|
+
)
|
|
273
|
+
self.prk_timesteps = (prk_timesteps[:-1].repeat(2)[1:-1])[::-1].copy()
|
|
274
|
+
self.plms_timesteps = self._timesteps[:-3][
|
|
275
|
+
::-1
|
|
276
|
+
].copy() # we copy to avoid having negative strides which are not supported by torch.from_numpy
|
|
277
|
+
|
|
278
|
+
timesteps = np.concatenate([self.prk_timesteps, self.plms_timesteps]).astype(np.int64)
|
|
279
|
+
self.timesteps = torch.from_numpy(timesteps).to(device)
|
|
280
|
+
|
|
281
|
+
self.ets = []
|
|
282
|
+
self.counter = 0
|
|
283
|
+
self.cur_model_output = 0
|
|
284
|
+
|
|
285
|
+
def step(
|
|
286
|
+
self,
|
|
287
|
+
model_output: torch.FloatTensor,
|
|
288
|
+
timestep: int,
|
|
289
|
+
sample: torch.FloatTensor,
|
|
290
|
+
return_dict: bool = True,
|
|
291
|
+
) -> Union[SchedulerOutput, Tuple]:
|
|
292
|
+
"""
|
|
293
|
+
Predict the sample at the previous timestep by reversing the SDE. Core function to propagate the diffusion
|
|
294
|
+
process from the learned model outputs (most often the predicted noise).
|
|
295
|
+
|
|
296
|
+
This function calls `step_prk()` or `step_plms()` depending on the internal variable `counter`.
|
|
297
|
+
|
|
298
|
+
Args:
|
|
299
|
+
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
|
300
|
+
timestep (`int`): current discrete timestep in the diffusion chain.
|
|
301
|
+
sample (`torch.FloatTensor`):
|
|
302
|
+
current instance of sample being created by diffusion process.
|
|
303
|
+
return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
|
|
304
|
+
|
|
305
|
+
Returns:
|
|
306
|
+
[`~schedulers.scheduling_utils.SchedulerOutput`] or `tuple`:
|
|
307
|
+
[`~schedulers.scheduling_utils.SchedulerOutput`] if `return_dict` is True, otherwise a `tuple`. When
|
|
308
|
+
returning a tuple, the first element is the sample tensor.
|
|
309
|
+
|
|
310
|
+
"""
|
|
311
|
+
if self.counter < len(self.prk_timesteps) and not self.skip_prk_steps:
|
|
312
|
+
return self.step_prk(model_output=model_output, timestep=timestep, sample=sample, return_dict=return_dict)
|
|
313
|
+
else:
|
|
314
|
+
return self.step_plms(model_output=model_output, timestep=timestep, sample=sample, return_dict=return_dict)
|
|
315
|
+
|
|
316
|
+
def step_prk(
|
|
317
|
+
self,
|
|
318
|
+
model_output: torch.FloatTensor,
|
|
319
|
+
timestep: int,
|
|
320
|
+
sample: torch.FloatTensor,
|
|
321
|
+
return_dict: bool = True,
|
|
322
|
+
) -> Union[SchedulerOutput, Tuple]:
|
|
323
|
+
"""
|
|
324
|
+
Step function propagating the sample with the Runge-Kutta method. RK takes 4 forward passes to approximate the
|
|
325
|
+
solution to the differential equation.
|
|
326
|
+
|
|
327
|
+
Args:
|
|
328
|
+
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
|
329
|
+
timestep (`int`): current discrete timestep in the diffusion chain.
|
|
330
|
+
sample (`torch.FloatTensor`):
|
|
331
|
+
current instance of sample being created by diffusion process.
|
|
332
|
+
return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
|
|
333
|
+
|
|
334
|
+
Returns:
|
|
335
|
+
[`~scheduling_utils.SchedulerOutput`] or `tuple`: [`~scheduling_utils.SchedulerOutput`] if `return_dict` is
|
|
336
|
+
True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
|
|
337
|
+
|
|
338
|
+
"""
|
|
339
|
+
if self.num_inference_steps is None:
|
|
340
|
+
raise ValueError(
|
|
341
|
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
|
342
|
+
)
|
|
343
|
+
|
|
344
|
+
diff_to_prev = 0 if self.counter % 2 else self.num_train_timesteps // self.num_inference_steps // 2
|
|
345
|
+
prev_timestep = timestep - diff_to_prev
|
|
346
|
+
timestep = self.prk_timesteps[self.counter // 4 * 4]
|
|
347
|
+
|
|
348
|
+
if self.counter % 4 == 0:
|
|
349
|
+
self.cur_model_output += 1 / 6 * model_output
|
|
350
|
+
self.ets.append(model_output)
|
|
351
|
+
self.cur_sample = sample
|
|
352
|
+
elif (self.counter - 1) % 4 == 0:
|
|
353
|
+
self.cur_model_output += 1 / 3 * model_output
|
|
354
|
+
elif (self.counter - 2) % 4 == 0:
|
|
355
|
+
self.cur_model_output += 1 / 3 * model_output
|
|
356
|
+
elif (self.counter - 3) % 4 == 0:
|
|
357
|
+
model_output = self.cur_model_output + 1 / 6 * model_output
|
|
358
|
+
self.cur_model_output = 0
|
|
359
|
+
|
|
360
|
+
# cur_sample should not be `None`
|
|
361
|
+
cur_sample = self.cur_sample if self.cur_sample is not None else sample
|
|
362
|
+
|
|
363
|
+
prev_sample = self._get_prev_sample(cur_sample, timestep, prev_timestep, model_output)
|
|
364
|
+
self.counter += 1
|
|
365
|
+
|
|
366
|
+
if not return_dict:
|
|
367
|
+
return (prev_sample,)
|
|
368
|
+
|
|
369
|
+
return SchedulerOutput(prev_sample=prev_sample)
|
|
370
|
+
|
|
371
|
+
def step_plms(
|
|
372
|
+
self,
|
|
373
|
+
model_output: torch.FloatTensor,
|
|
374
|
+
timestep: int,
|
|
375
|
+
sample: torch.FloatTensor,
|
|
376
|
+
return_dict: bool = True,
|
|
377
|
+
) -> Union[SchedulerOutput, Tuple]:
|
|
378
|
+
"""
|
|
379
|
+
Step function propagating the sample with the linear multi-step method. This has one forward pass with multiple
|
|
380
|
+
times to approximate the solution.
|
|
381
|
+
|
|
382
|
+
Args:
|
|
383
|
+
model_output (`torch.FloatTensor`): direct output from learned diffusion model.
|
|
384
|
+
timestep (`int`): current discrete timestep in the diffusion chain.
|
|
385
|
+
sample (`torch.FloatTensor`):
|
|
386
|
+
current instance of sample being created by diffusion process.
|
|
387
|
+
return_dict (`bool`): option for returning tuple rather than SchedulerOutput class
|
|
388
|
+
|
|
389
|
+
Returns:
|
|
390
|
+
[`~scheduling_utils.SchedulerOutput`] or `tuple`: [`~scheduling_utils.SchedulerOutput`] if `return_dict` is
|
|
391
|
+
True, otherwise a `tuple`. When returning a tuple, the first element is the sample tensor.
|
|
392
|
+
|
|
393
|
+
"""
|
|
394
|
+
if self.num_inference_steps is None:
|
|
395
|
+
raise ValueError(
|
|
396
|
+
"Number of inference steps is 'None', you need to run 'set_timesteps' after creating the scheduler"
|
|
397
|
+
)
|
|
398
|
+
|
|
399
|
+
if not self.skip_prk_steps and len(self.ets) < 3:
|
|
400
|
+
raise ValueError(
|
|
401
|
+
f"{self.__class__} can only be run AFTER scheduler has been run "
|
|
402
|
+
"in 'prk' mode for at least 12 iterations "
|
|
403
|
+
"See: https://github.com/huggingface/diffusers/blob/main/src/diffusers/pipelines/pipeline_pndm.py "
|
|
404
|
+
"for more information."
|
|
405
|
+
)
|
|
406
|
+
|
|
407
|
+
prev_timestep = timestep - self.num_train_timesteps // self.num_inference_steps
|
|
408
|
+
|
|
409
|
+
if self.counter != 1:
|
|
410
|
+
self.ets = self.ets[-3:]
|
|
411
|
+
self.ets.append(model_output)
|
|
412
|
+
else:
|
|
413
|
+
prev_timestep = timestep
|
|
414
|
+
timestep = timestep + self.num_train_timesteps // self.num_inference_steps
|
|
415
|
+
|
|
416
|
+
if len(self.ets) == 1 and self.counter == 0:
|
|
417
|
+
model_output = model_output
|
|
418
|
+
self.cur_sample = sample
|
|
419
|
+
elif len(self.ets) == 1 and self.counter == 1:
|
|
420
|
+
model_output = (model_output + self.ets[-1]) / 2
|
|
421
|
+
sample = self.cur_sample
|
|
422
|
+
self.cur_sample = None
|
|
423
|
+
elif len(self.ets) == 2:
|
|
424
|
+
model_output = (3 * self.ets[-1] - self.ets[-2]) / 2
|
|
425
|
+
elif len(self.ets) == 3:
|
|
426
|
+
model_output = (23 * self.ets[-1] - 16 * self.ets[-2] + 5 * self.ets[-3]) / 12
|
|
427
|
+
else:
|
|
428
|
+
model_output = (1 / 24) * (55 * self.ets[-1] - 59 * self.ets[-2] + 37 * self.ets[-3] - 9 * self.ets[-4])
|
|
429
|
+
|
|
430
|
+
prev_sample = self._get_prev_sample(sample, timestep, prev_timestep, model_output)
|
|
431
|
+
self.counter += 1
|
|
432
|
+
|
|
433
|
+
if not return_dict:
|
|
434
|
+
return (prev_sample,)
|
|
435
|
+
|
|
436
|
+
return SchedulerOutput(prev_sample=prev_sample)
|
|
437
|
+
|
|
438
|
+
def scale_model_input(self, sample: torch.FloatTensor, *args, **kwargs) -> torch.FloatTensor:
|
|
439
|
+
"""
|
|
440
|
+
Ensures interchangeability with schedulers that need to scale the denoising model input depending on the
|
|
441
|
+
current timestep.
|
|
442
|
+
|
|
443
|
+
Args:
|
|
444
|
+
sample (`torch.FloatTensor`): input sample
|
|
445
|
+
|
|
446
|
+
Returns:
|
|
447
|
+
`torch.FloatTensor`: scaled input sample
|
|
448
|
+
"""
|
|
449
|
+
return sample
|
|
450
|
+
|
|
451
|
+
def _get_prev_sample(self, sample, timestep, prev_timestep, model_output):
|
|
452
|
+
# See formula (9) of PNDM paper https://arxiv.org/pdf/2202.09778.pdf
|
|
453
|
+
# this function computes x_(t−δ) using the formula of (9)
|
|
454
|
+
# Note that x_t needs to be added to both sides of the equation
|
|
455
|
+
|
|
456
|
+
# Notation (<variable name> -> <name in paper>
|
|
457
|
+
# alpha_prod_t -> α_t
|
|
458
|
+
# alpha_prod_t_prev -> α_(t−δ)
|
|
459
|
+
# beta_prod_t -> (1 - α_t)
|
|
460
|
+
# beta_prod_t_prev -> (1 - α_(t−δ))
|
|
461
|
+
# sample -> x_t
|
|
462
|
+
# model_output -> e_θ(x_t, t)
|
|
463
|
+
# prev_sample -> x_(t−δ)
|
|
464
|
+
alpha_prod_t = self.alphas_cumprod[timestep]
|
|
465
|
+
alpha_prod_t_prev = self.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else self.final_alpha_cumprod
|
|
466
|
+
beta_prod_t = 1 - alpha_prod_t
|
|
467
|
+
beta_prod_t_prev = 1 - alpha_prod_t_prev
|
|
468
|
+
|
|
469
|
+
if self.prediction_type == "v_prediction":
|
|
470
|
+
model_output = (alpha_prod_t**0.5) * model_output + (beta_prod_t**0.5) * sample
|
|
471
|
+
elif self.prediction_type != "epsilon":
|
|
472
|
+
raise ValueError(
|
|
473
|
+
f"prediction_type given as {self.prediction_type} must be one of `epsilon` or `v_prediction`"
|
|
474
|
+
)
|
|
475
|
+
|
|
476
|
+
# corresponds to (α_(t−δ) - α_t) divided by
|
|
477
|
+
# denominator of x_t in formula (9) and plus 1
|
|
478
|
+
# Note: (α_(t−δ) - α_t) / (sqrt(α_t) * (sqrt(α_(t−δ)) + sqr(α_t))) =
|
|
479
|
+
# sqrt(α_(t−δ)) / sqrt(α_t))
|
|
480
|
+
sample_coeff = (alpha_prod_t_prev / alpha_prod_t) ** (0.5)
|
|
481
|
+
|
|
482
|
+
# corresponds to denominator of e_θ(x_t, t) in formula (9)
|
|
483
|
+
model_output_denom_coeff = alpha_prod_t * beta_prod_t_prev ** (0.5) + (
|
|
484
|
+
alpha_prod_t * beta_prod_t * alpha_prod_t_prev
|
|
485
|
+
) ** (0.5)
|
|
486
|
+
|
|
487
|
+
# full formula (9)
|
|
488
|
+
prev_sample = (
|
|
489
|
+
sample_coeff * sample - (alpha_prod_t_prev - alpha_prod_t) * model_output / model_output_denom_coeff
|
|
490
|
+
)
|
|
491
|
+
|
|
492
|
+
return prev_sample
|
|
493
|
+
|
|
494
|
+
def add_noise(
|
|
495
|
+
self,
|
|
496
|
+
original_samples: torch.FloatTensor,
|
|
497
|
+
noise: torch.FloatTensor,
|
|
498
|
+
timesteps: torch.IntTensor,
|
|
499
|
+
) -> torch.Tensor:
|
|
500
|
+
# Make sure alphas_cumprod and timestep have same device and dtype as original_samples
|
|
501
|
+
self.alphas_cumprod = self.alphas_cumprod.to(device=original_samples.device, dtype=original_samples.dtype)
|
|
502
|
+
timesteps = timesteps.to(original_samples.device)
|
|
503
|
+
|
|
504
|
+
sqrt_alpha_prod = self.alphas_cumprod[timesteps] ** 0.5
|
|
505
|
+
sqrt_alpha_prod = sqrt_alpha_prod.flatten()
|
|
506
|
+
while len(sqrt_alpha_prod.shape) < len(original_samples.shape):
|
|
507
|
+
sqrt_alpha_prod = sqrt_alpha_prod.unsqueeze(-1)
|
|
508
|
+
|
|
509
|
+
sqrt_one_minus_alpha_prod = (1 - self.alphas_cumprod[timesteps]) ** 0.5
|
|
510
|
+
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.flatten()
|
|
511
|
+
while len(sqrt_one_minus_alpha_prod.shape) < len(original_samples.shape):
|
|
512
|
+
sqrt_one_minus_alpha_prod = sqrt_one_minus_alpha_prod.unsqueeze(-1)
|
|
513
|
+
|
|
514
|
+
noisy_samples = sqrt_alpha_prod * original_samples + sqrt_one_minus_alpha_prod * noise
|
|
515
|
+
return noisy_samples
|
|
516
|
+
|
|
517
|
+
def __len__(self):
|
|
518
|
+
return self.num_train_timesteps
|
|
File without changes
|