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
|
@@ -0,0 +1,1400 @@
|
|
|
1
|
+
"""
|
|
2
|
+
wild mixture of
|
|
3
|
+
https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
|
4
|
+
https://github.com/openai/improved-diffusion/blob/e94489283bb876ac1477d5dd7709bbbd2d9902ce/improved_diffusion/gaussian_diffusion.py
|
|
5
|
+
https://github.com/CompVis/taming-transformers
|
|
6
|
+
-- merci
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import torch
|
|
10
|
+
import torch.nn as nn
|
|
11
|
+
import numpy as np
|
|
12
|
+
import pytorch_lightning as pl
|
|
13
|
+
from torch.optim.lr_scheduler import LambdaLR
|
|
14
|
+
from einops import rearrange, repeat
|
|
15
|
+
from contextlib import contextmanager, nullcontext
|
|
16
|
+
from functools import partial
|
|
17
|
+
import itertools
|
|
18
|
+
from tqdm import tqdm
|
|
19
|
+
from torchvision.utils import make_grid
|
|
20
|
+
from pytorch_lightning.utilities import rank_zero_only
|
|
21
|
+
from omegaconf import ListConfig
|
|
22
|
+
|
|
23
|
+
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.util import log_txt_as_img, exists, default, ismap, isimage, mean_flat, count_params, instantiate_from_config
|
|
24
|
+
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.ema import LitEma
|
|
25
|
+
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.distributions.distributions import normal_kl, DiagonalGaussianDistribution
|
|
26
|
+
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.models.autoencoder import IdentityFirstStage, AutoencoderKL
|
|
27
|
+
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.modules.diffusionmodules.util import make_beta_schedule, extract_into_tensor, noise_like
|
|
28
|
+
from libcom.painterly_image_harmonization.source.PHDiffusion.ldm.models.diffusion.ddim import DDIMSampler
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
__conditioning_keys__ = {'concat': 'c_concat',
|
|
32
|
+
'crossattn': 'c_crossattn',
|
|
33
|
+
'adm': 'y'}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def disabled_train(self, mode=True):
|
|
37
|
+
"""Overwrite model.train with this function to make sure train/eval mode
|
|
38
|
+
does not change anymore."""
|
|
39
|
+
return self
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def uniform_on_device(r1, r2, shape, device):
|
|
43
|
+
return (r1 - r2) * torch.rand(*shape, device=device) + r2
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class DDPM(pl.LightningModule):
|
|
47
|
+
# classic DDPM with Gaussian diffusion, in image space
|
|
48
|
+
def __init__(self,
|
|
49
|
+
unet_config,
|
|
50
|
+
timesteps=1000,
|
|
51
|
+
beta_schedule="linear",
|
|
52
|
+
loss_type="l2",
|
|
53
|
+
ckpt_path=None,
|
|
54
|
+
ignore_keys=[],
|
|
55
|
+
load_only_unet=False,
|
|
56
|
+
monitor="val/loss",
|
|
57
|
+
use_ema=True,
|
|
58
|
+
first_stage_key="image",
|
|
59
|
+
image_size=512,
|
|
60
|
+
channels=3,
|
|
61
|
+
log_every_t=100,
|
|
62
|
+
clip_denoised=True,
|
|
63
|
+
linear_start=0.00085,
|
|
64
|
+
linear_end=0.012,
|
|
65
|
+
cosine_s=8e-3,
|
|
66
|
+
given_betas=None,
|
|
67
|
+
original_elbo_weight=0.,
|
|
68
|
+
v_posterior=0., # weight for choosing posterior variance as sigma = (1-v) * beta_tilde + v * beta
|
|
69
|
+
l_simple_weight=1.,
|
|
70
|
+
conditioning_key=None,
|
|
71
|
+
parameterization="eps", # all assuming fixed variance schedules
|
|
72
|
+
scheduler_config=None,
|
|
73
|
+
use_positional_encodings=False,
|
|
74
|
+
learn_logvar=False,
|
|
75
|
+
logvar_init=0.,
|
|
76
|
+
make_it_fit=False,
|
|
77
|
+
ucg_training=None,
|
|
78
|
+
reset_ema=False,
|
|
79
|
+
reset_num_ema_updates=False,
|
|
80
|
+
):
|
|
81
|
+
super().__init__()
|
|
82
|
+
assert parameterization in ["eps", "x0", "v"], 'currently only supporting "eps" and "x0" and "v"'
|
|
83
|
+
self.parameterization = parameterization
|
|
84
|
+
self.cond_stage_model = None
|
|
85
|
+
self.clip_denoised = clip_denoised
|
|
86
|
+
self.log_every_t = log_every_t
|
|
87
|
+
self.first_stage_key = first_stage_key
|
|
88
|
+
self.image_size = image_size # try conv?
|
|
89
|
+
self.channels = channels
|
|
90
|
+
self.use_positional_encodings = use_positional_encodings
|
|
91
|
+
self.model = DiffusionWrapper(unet_config, conditioning_key)
|
|
92
|
+
# count_params(self.model, verbose=True)
|
|
93
|
+
self.use_ema = use_ema
|
|
94
|
+
if self.use_ema:
|
|
95
|
+
self.model_ema = LitEma(self.model)
|
|
96
|
+
print(f"Keeping EMAs of {len(list(self.model_ema.buffers()))}.")
|
|
97
|
+
|
|
98
|
+
self.use_scheduler = scheduler_config is not None
|
|
99
|
+
if self.use_scheduler:
|
|
100
|
+
self.scheduler_config = scheduler_config
|
|
101
|
+
|
|
102
|
+
self.v_posterior = v_posterior
|
|
103
|
+
self.original_elbo_weight = original_elbo_weight
|
|
104
|
+
self.l_simple_weight = l_simple_weight
|
|
105
|
+
|
|
106
|
+
if monitor is not None:
|
|
107
|
+
self.monitor = monitor
|
|
108
|
+
self.make_it_fit = make_it_fit
|
|
109
|
+
if reset_ema: assert exists(ckpt_path)
|
|
110
|
+
if ckpt_path is not None:
|
|
111
|
+
self.init_from_ckpt(ckpt_path, ignore_keys=ignore_keys, only_model=load_only_unet)
|
|
112
|
+
if reset_ema:
|
|
113
|
+
assert self.use_ema
|
|
114
|
+
print(f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
|
|
115
|
+
self.model_ema = LitEma(self.model)
|
|
116
|
+
if reset_num_ema_updates:
|
|
117
|
+
print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
|
|
118
|
+
assert self.use_ema
|
|
119
|
+
self.model_ema.reset_num_updates()
|
|
120
|
+
|
|
121
|
+
self.register_schedule(given_betas=given_betas, beta_schedule=beta_schedule, timesteps=timesteps,
|
|
122
|
+
linear_start=linear_start, linear_end=linear_end, cosine_s=cosine_s)
|
|
123
|
+
|
|
124
|
+
self.loss_type = loss_type
|
|
125
|
+
|
|
126
|
+
self.learn_logvar = learn_logvar
|
|
127
|
+
self.logvar = torch.full(fill_value=logvar_init, size=(self.num_timesteps,))
|
|
128
|
+
if self.learn_logvar:
|
|
129
|
+
self.logvar = nn.Parameter(self.logvar, requires_grad=True)
|
|
130
|
+
|
|
131
|
+
self.ucg_training = ucg_training or dict()
|
|
132
|
+
if self.ucg_training:
|
|
133
|
+
self.ucg_prng = np.random.RandomState()
|
|
134
|
+
|
|
135
|
+
def register_schedule(self, given_betas=None, beta_schedule="linear", timesteps=1000,
|
|
136
|
+
linear_start=0.00085, linear_end=0.012, cosine_s=8e-3):
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
linear_start = 0.00085
|
|
140
|
+
linear_end = 0.012
|
|
141
|
+
# if exists(given_betas):
|
|
142
|
+
# betas = given_betas
|
|
143
|
+
# else:
|
|
144
|
+
betas = make_beta_schedule(beta_schedule, timesteps, linear_start=linear_start, linear_end=linear_end,
|
|
145
|
+
cosine_s=cosine_s)
|
|
146
|
+
alphas = 1. - betas
|
|
147
|
+
alphas_cumprod = np.cumprod(alphas, axis=0)
|
|
148
|
+
alphas_cumprod_prev = np.append(1., alphas_cumprod[:-1])
|
|
149
|
+
|
|
150
|
+
timesteps, = betas.shape
|
|
151
|
+
self.num_timesteps = int(timesteps)
|
|
152
|
+
self.linear_start = linear_start
|
|
153
|
+
self.linear_end = linear_end
|
|
154
|
+
assert alphas_cumprod.shape[0] == self.num_timesteps, 'alphas have to be defined for each timestep'
|
|
155
|
+
|
|
156
|
+
to_torch = partial(torch.tensor, dtype=torch.float32)
|
|
157
|
+
|
|
158
|
+
self.register_buffer('betas', to_torch(betas))
|
|
159
|
+
self.register_buffer('alphas_cumprod', to_torch(alphas_cumprod))
|
|
160
|
+
self.register_buffer('alphas_cumprod_prev', to_torch(alphas_cumprod_prev))
|
|
161
|
+
|
|
162
|
+
# calculations for diffusion q(x_t | x_{t-1}) and others
|
|
163
|
+
self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
|
164
|
+
self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
|
165
|
+
self.register_buffer('log_one_minus_alphas_cumprod', to_torch(np.log(1. - alphas_cumprod)))
|
|
166
|
+
self.register_buffer('sqrt_recip_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod)))
|
|
167
|
+
self.register_buffer('sqrt_recipm1_alphas_cumprod', to_torch(np.sqrt(1. / alphas_cumprod - 1)))
|
|
168
|
+
|
|
169
|
+
# calculations for posterior q(x_{t-1} | x_t, x_0)
|
|
170
|
+
posterior_variance = (1 - self.v_posterior) * betas * (1. - alphas_cumprod_prev) / (
|
|
171
|
+
1. - alphas_cumprod) + self.v_posterior * betas
|
|
172
|
+
# above: equal to 1. / (1. / (1. - alpha_cumprod_tm1) + alpha_t / beta_t)
|
|
173
|
+
self.register_buffer('posterior_variance', to_torch(posterior_variance))
|
|
174
|
+
# below: log calculation clipped because the posterior variance is 0 at the beginning of the diffusion chain
|
|
175
|
+
self.register_buffer('posterior_log_variance_clipped', to_torch(np.log(np.maximum(posterior_variance, 1e-20))))
|
|
176
|
+
self.register_buffer('posterior_mean_coef1', to_torch(
|
|
177
|
+
betas * np.sqrt(alphas_cumprod_prev) / (1. - alphas_cumprod)))
|
|
178
|
+
self.register_buffer('posterior_mean_coef2', to_torch(
|
|
179
|
+
(1. - alphas_cumprod_prev) * np.sqrt(alphas) / (1. - alphas_cumprod)))
|
|
180
|
+
|
|
181
|
+
if self.parameterization == "eps":
|
|
182
|
+
lvlb_weights = self.betas ** 2 / (
|
|
183
|
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod))
|
|
184
|
+
elif self.parameterization == "x0":
|
|
185
|
+
lvlb_weights = 0.5 * np.sqrt(torch.Tensor(alphas_cumprod)) / (2. * 1 - torch.Tensor(alphas_cumprod))
|
|
186
|
+
elif self.parameterization == "v":
|
|
187
|
+
lvlb_weights = torch.ones_like(self.betas ** 2 / (
|
|
188
|
+
2 * self.posterior_variance * to_torch(alphas) * (1 - self.alphas_cumprod)))
|
|
189
|
+
else:
|
|
190
|
+
raise NotImplementedError("mu not supported")
|
|
191
|
+
lvlb_weights[0] = lvlb_weights[1]
|
|
192
|
+
self.register_buffer('lvlb_weights', lvlb_weights, persistent=False)
|
|
193
|
+
assert not torch.isnan(self.lvlb_weights).all()
|
|
194
|
+
|
|
195
|
+
@contextmanager
|
|
196
|
+
def ema_scope(self, context=None):
|
|
197
|
+
if self.use_ema:
|
|
198
|
+
self.model_ema.store(self.model.parameters())
|
|
199
|
+
self.model_ema.copy_to(self.model)
|
|
200
|
+
if context is not None:
|
|
201
|
+
print(f"{context}: Switched to EMA weights")
|
|
202
|
+
try:
|
|
203
|
+
yield None
|
|
204
|
+
finally:
|
|
205
|
+
if self.use_ema:
|
|
206
|
+
self.model_ema.restore(self.model.parameters())
|
|
207
|
+
if context is not None:
|
|
208
|
+
print(f"{context}: Restored training weights")
|
|
209
|
+
|
|
210
|
+
@torch.no_grad()
|
|
211
|
+
def init_from_ckpt(self, path, ignore_keys=list(), only_model=False):
|
|
212
|
+
sd = torch.load(path, map_location="cpu")
|
|
213
|
+
if "state_dict" in list(sd.keys()):
|
|
214
|
+
sd = sd["state_dict"]
|
|
215
|
+
keys = list(sd.keys())
|
|
216
|
+
for k in keys:
|
|
217
|
+
for ik in ignore_keys:
|
|
218
|
+
if k.startswith(ik):
|
|
219
|
+
print("Deleting key {} from state_dict.".format(k))
|
|
220
|
+
del sd[k]
|
|
221
|
+
if self.make_it_fit:
|
|
222
|
+
n_params = len([name for name, _ in
|
|
223
|
+
itertools.chain(self.named_parameters(),
|
|
224
|
+
self.named_buffers())])
|
|
225
|
+
for name, param in tqdm(
|
|
226
|
+
itertools.chain(self.named_parameters(),
|
|
227
|
+
self.named_buffers()),
|
|
228
|
+
desc="Fitting old weights to new weights",
|
|
229
|
+
total=n_params
|
|
230
|
+
):
|
|
231
|
+
if not name in sd:
|
|
232
|
+
continue
|
|
233
|
+
old_shape = sd[name].shape
|
|
234
|
+
new_shape = param.shape
|
|
235
|
+
assert len(old_shape) == len(new_shape)
|
|
236
|
+
if len(new_shape) > 2:
|
|
237
|
+
# we only modify first two axes
|
|
238
|
+
assert new_shape[2:] == old_shape[2:]
|
|
239
|
+
# assumes first axis corresponds to output dim
|
|
240
|
+
if not new_shape == old_shape:
|
|
241
|
+
new_param = param.clone()
|
|
242
|
+
old_param = sd[name]
|
|
243
|
+
if len(new_shape) == 1:
|
|
244
|
+
for i in range(new_param.shape[0]):
|
|
245
|
+
new_param[i] = old_param[i % old_shape[0]]
|
|
246
|
+
elif len(new_shape) >= 2:
|
|
247
|
+
for i in range(new_param.shape[0]):
|
|
248
|
+
for j in range(new_param.shape[1]):
|
|
249
|
+
new_param[i, j] = old_param[i % old_shape[0], j % old_shape[1]]
|
|
250
|
+
|
|
251
|
+
n_used_old = torch.ones(old_shape[1])
|
|
252
|
+
for j in range(new_param.shape[1]):
|
|
253
|
+
n_used_old[j % old_shape[1]] += 1
|
|
254
|
+
n_used_new = torch.zeros(new_shape[1])
|
|
255
|
+
for j in range(new_param.shape[1]):
|
|
256
|
+
n_used_new[j] = n_used_old[j % old_shape[1]]
|
|
257
|
+
|
|
258
|
+
n_used_new = n_used_new[None, :]
|
|
259
|
+
while len(n_used_new.shape) < len(new_shape):
|
|
260
|
+
n_used_new = n_used_new.unsqueeze(-1)
|
|
261
|
+
new_param /= n_used_new
|
|
262
|
+
|
|
263
|
+
sd[name] = new_param
|
|
264
|
+
|
|
265
|
+
missing, unexpected = self.load_state_dict(sd, strict=False) if not only_model else self.model.load_state_dict(
|
|
266
|
+
sd, strict=False)
|
|
267
|
+
print(f"Restored from {path} with {len(missing)} missing and {len(unexpected)} unexpected keys")
|
|
268
|
+
if len(missing) > 0:
|
|
269
|
+
print(f"Missing Keys:\n {missing}")
|
|
270
|
+
if len(unexpected) > 0:
|
|
271
|
+
print(f"\nUnexpected Keys:\n {unexpected}")
|
|
272
|
+
|
|
273
|
+
def q_mean_variance(self, x_start, t):
|
|
274
|
+
"""
|
|
275
|
+
Get the distribution q(x_t | x_0).
|
|
276
|
+
:param x_start: the [N x C x ...] tensor of noiseless inputs.
|
|
277
|
+
:param t: the number of diffusion steps (minus 1). Here, 0 means one step.
|
|
278
|
+
:return: A tuple (mean, variance, log_variance), all of x_start's shape.
|
|
279
|
+
"""
|
|
280
|
+
mean = (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start)
|
|
281
|
+
variance = extract_into_tensor(1.0 - self.alphas_cumprod, t, x_start.shape)
|
|
282
|
+
log_variance = extract_into_tensor(self.log_one_minus_alphas_cumprod, t, x_start.shape)
|
|
283
|
+
return mean, variance, log_variance
|
|
284
|
+
|
|
285
|
+
def predict_start_from_noise(self, x_t, t, noise):
|
|
286
|
+
return (
|
|
287
|
+
extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t -
|
|
288
|
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape) * noise
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
def predict_start_from_z_and_v(self, x_t, t, v):
|
|
292
|
+
# self.register_buffer('sqrt_alphas_cumprod', to_torch(np.sqrt(alphas_cumprod)))
|
|
293
|
+
# self.register_buffer('sqrt_one_minus_alphas_cumprod', to_torch(np.sqrt(1. - alphas_cumprod)))
|
|
294
|
+
return (
|
|
295
|
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * x_t -
|
|
296
|
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * v
|
|
297
|
+
)
|
|
298
|
+
|
|
299
|
+
def predict_eps_from_z_and_v(self, x_t, t, v):
|
|
300
|
+
return (
|
|
301
|
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x_t.shape) * v +
|
|
302
|
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_t.shape) * x_t
|
|
303
|
+
)
|
|
304
|
+
|
|
305
|
+
def q_posterior(self, x_start, x_t, t):
|
|
306
|
+
posterior_mean = (
|
|
307
|
+
extract_into_tensor(self.posterior_mean_coef1, t, x_t.shape) * x_start +
|
|
308
|
+
extract_into_tensor(self.posterior_mean_coef2, t, x_t.shape) * x_t
|
|
309
|
+
)
|
|
310
|
+
posterior_variance = extract_into_tensor(self.posterior_variance, t, x_t.shape)
|
|
311
|
+
posterior_log_variance_clipped = extract_into_tensor(self.posterior_log_variance_clipped, t, x_t.shape)
|
|
312
|
+
return posterior_mean, posterior_variance, posterior_log_variance_clipped
|
|
313
|
+
|
|
314
|
+
def p_mean_variance(self, x, t, clip_denoised: bool):
|
|
315
|
+
model_out = self.model(x, t)
|
|
316
|
+
if self.parameterization == "eps":
|
|
317
|
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
|
318
|
+
elif self.parameterization == "x0":
|
|
319
|
+
x_recon = model_out
|
|
320
|
+
if clip_denoised:
|
|
321
|
+
x_recon.clamp_(-1., 1.)
|
|
322
|
+
|
|
323
|
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
|
324
|
+
return model_mean, posterior_variance, posterior_log_variance
|
|
325
|
+
|
|
326
|
+
@torch.no_grad()
|
|
327
|
+
def p_sample(self, x, t, clip_denoised=True, repeat_noise=False):
|
|
328
|
+
b, *_, device = *x.shape, x.device
|
|
329
|
+
model_mean, _, model_log_variance = self.p_mean_variance(x=x, t=t, clip_denoised=clip_denoised)
|
|
330
|
+
noise = noise_like(x.shape, device, repeat_noise)
|
|
331
|
+
# no noise when t == 0
|
|
332
|
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
|
333
|
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
|
334
|
+
|
|
335
|
+
@torch.no_grad()
|
|
336
|
+
def p_sample_loop(self, shape, return_intermediates=False):
|
|
337
|
+
device = self.betas.device
|
|
338
|
+
b = shape[0]
|
|
339
|
+
img = torch.randn(shape, device=device)
|
|
340
|
+
intermediates = [img]
|
|
341
|
+
for i in tqdm(reversed(range(0, self.num_timesteps)), desc='Sampling t', total=self.num_timesteps):
|
|
342
|
+
img = self.p_sample(img, torch.full((b,), i, device=device, dtype=torch.long),
|
|
343
|
+
clip_denoised=self.clip_denoised)
|
|
344
|
+
if i % self.log_every_t == 0 or i == self.num_timesteps - 1:
|
|
345
|
+
intermediates.append(img)
|
|
346
|
+
if return_intermediates:
|
|
347
|
+
return img, intermediates
|
|
348
|
+
return img
|
|
349
|
+
|
|
350
|
+
@torch.no_grad()
|
|
351
|
+
def sample(self, batch_size=16, return_intermediates=False):
|
|
352
|
+
image_size = self.image_size
|
|
353
|
+
channels = self.channels
|
|
354
|
+
return self.p_sample_loop((batch_size, channels, image_size, image_size),
|
|
355
|
+
return_intermediates=return_intermediates)
|
|
356
|
+
|
|
357
|
+
def q_sample(self, x_start, t, noise=None):
|
|
358
|
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
|
359
|
+
return (extract_into_tensor(self.sqrt_alphas_cumprod, t, x_start.shape) * x_start +
|
|
360
|
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x_start.shape) * noise)
|
|
361
|
+
|
|
362
|
+
def get_v(self, x, noise, t):
|
|
363
|
+
return (
|
|
364
|
+
extract_into_tensor(self.sqrt_alphas_cumprod, t, x.shape) * noise -
|
|
365
|
+
extract_into_tensor(self.sqrt_one_minus_alphas_cumprod, t, x.shape) * x
|
|
366
|
+
)
|
|
367
|
+
|
|
368
|
+
def get_loss(self, pred, target, mean=True):
|
|
369
|
+
if self.loss_type == 'l1':
|
|
370
|
+
loss = (target - pred).abs()
|
|
371
|
+
if mean:
|
|
372
|
+
loss = loss.mean()
|
|
373
|
+
elif self.loss_type == 'l2':
|
|
374
|
+
if mean:
|
|
375
|
+
loss = torch.nn.functional.mse_loss(target, pred)
|
|
376
|
+
else:
|
|
377
|
+
loss = torch.nn.functional.mse_loss(target, pred, reduction='none')
|
|
378
|
+
else:
|
|
379
|
+
raise NotImplementedError("unknown loss type '{loss_type}'")
|
|
380
|
+
|
|
381
|
+
return loss
|
|
382
|
+
|
|
383
|
+
def p_losses(self, x_start, t, noise=None):
|
|
384
|
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
|
385
|
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
|
386
|
+
model_out = self.model(x_noisy, t)
|
|
387
|
+
|
|
388
|
+
loss_dict = {}
|
|
389
|
+
if self.parameterization == "eps":
|
|
390
|
+
target = noise
|
|
391
|
+
elif self.parameterization == "x0":
|
|
392
|
+
target = x_start
|
|
393
|
+
elif self.parameterization == "v":
|
|
394
|
+
target = self.get_v(x_start, noise, t)
|
|
395
|
+
else:
|
|
396
|
+
raise NotImplementedError(f"Parameterization {self.parameterization} not yet supported")
|
|
397
|
+
|
|
398
|
+
loss = self.get_loss(model_out, target, mean=False).mean(dim=[1, 2, 3])
|
|
399
|
+
|
|
400
|
+
log_prefix = 'train' if self.training else 'val'
|
|
401
|
+
|
|
402
|
+
loss_dict.update({f'{log_prefix}/loss_simple': loss.mean()})
|
|
403
|
+
loss_simple = loss.mean() * self.l_simple_weight
|
|
404
|
+
|
|
405
|
+
loss_vlb = (self.lvlb_weights[t] * loss).mean()
|
|
406
|
+
loss_dict.update({f'{log_prefix}/loss_vlb': loss_vlb})
|
|
407
|
+
|
|
408
|
+
loss = loss_simple + self.original_elbo_weight * loss_vlb
|
|
409
|
+
|
|
410
|
+
loss_dict.update({f'{log_prefix}/loss': loss})
|
|
411
|
+
|
|
412
|
+
return loss, loss_dict
|
|
413
|
+
|
|
414
|
+
def forward(self, x, *args, **kwargs):
|
|
415
|
+
# b, c, h, w, device, img_size, = *x.shape, x.device, self.image_size
|
|
416
|
+
# assert h == img_size and w == img_size, f'height and width of image must be {img_size}'
|
|
417
|
+
t = torch.randint(0, self.num_timesteps, (x.shape[0],), device=self.device).long()
|
|
418
|
+
return self.p_losses(x, t, *args, **kwargs)
|
|
419
|
+
|
|
420
|
+
def get_input(self, batch, k):
|
|
421
|
+
x = batch[k]
|
|
422
|
+
# if len(x.shape) == 3:
|
|
423
|
+
# x = x[..., None]
|
|
424
|
+
# x = rearrange(x, 'b h w c -> b c h w')
|
|
425
|
+
# x = x.to(memory_format=torch.contiguous_format).float()
|
|
426
|
+
return x
|
|
427
|
+
|
|
428
|
+
def shared_step(self, batch):
|
|
429
|
+
x = self.get_input(batch, self.first_stage_key)
|
|
430
|
+
loss, loss_dict = self(x)
|
|
431
|
+
return loss, loss_dict
|
|
432
|
+
|
|
433
|
+
def training_step(self, batch, batch_idx):
|
|
434
|
+
loss, loss_dict = self.shared_step(batch)
|
|
435
|
+
|
|
436
|
+
self.log_dict(loss_dict, prog_bar=True,
|
|
437
|
+
logger=True, on_step=True, on_epoch=True)
|
|
438
|
+
|
|
439
|
+
self.log("global_step", self.global_step,
|
|
440
|
+
prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
|
441
|
+
|
|
442
|
+
if self.use_scheduler:
|
|
443
|
+
lr = self.optimizers().param_groups[0]['lr']
|
|
444
|
+
self.log('lr_abs', lr, prog_bar=True, logger=True, on_step=True, on_epoch=False)
|
|
445
|
+
|
|
446
|
+
return loss
|
|
447
|
+
|
|
448
|
+
@torch.no_grad()
|
|
449
|
+
def validation_step(self, batch, batch_idx):
|
|
450
|
+
_, loss_dict_no_ema = self.shared_step(batch)
|
|
451
|
+
with self.ema_scope():
|
|
452
|
+
_, loss_dict_ema = self.shared_step(batch)
|
|
453
|
+
loss_dict_ema = {key + '_ema': loss_dict_ema[key] for key in loss_dict_ema}
|
|
454
|
+
self.log_dict(loss_dict_no_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
|
455
|
+
self.log_dict(loss_dict_ema, prog_bar=False, logger=True, on_step=False, on_epoch=True)
|
|
456
|
+
|
|
457
|
+
def on_train_batch_end(self, *args, **kwargs):
|
|
458
|
+
if self.use_ema:
|
|
459
|
+
self.model_ema(self.model)
|
|
460
|
+
|
|
461
|
+
def _get_rows_from_list(self, samples):
|
|
462
|
+
n_imgs_per_row = len(samples)
|
|
463
|
+
denoise_grid = rearrange(samples, 'n b c h w -> b n c h w')
|
|
464
|
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
|
465
|
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
|
466
|
+
return denoise_grid
|
|
467
|
+
|
|
468
|
+
@torch.no_grad()
|
|
469
|
+
def log_images(self, batch, N=8, n_row=2, sample=True, return_keys=None, **kwargs):
|
|
470
|
+
log = dict()
|
|
471
|
+
x = self.get_input(batch, self.first_stage_key)
|
|
472
|
+
N = min(x.shape[0], N)
|
|
473
|
+
n_row = min(x.shape[0], n_row)
|
|
474
|
+
x = x.to(self.device)[:N]
|
|
475
|
+
log["inputs"] = x
|
|
476
|
+
|
|
477
|
+
# get diffusion row
|
|
478
|
+
diffusion_row = list()
|
|
479
|
+
x_start = x[:n_row]
|
|
480
|
+
|
|
481
|
+
for t in range(self.num_timesteps):
|
|
482
|
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
|
483
|
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
|
484
|
+
t = t.to(self.device).long()
|
|
485
|
+
noise = torch.randn_like(x_start)
|
|
486
|
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
|
487
|
+
diffusion_row.append(x_noisy)
|
|
488
|
+
|
|
489
|
+
log["diffusion_row"] = self._get_rows_from_list(diffusion_row)
|
|
490
|
+
|
|
491
|
+
if sample:
|
|
492
|
+
# get denoise row
|
|
493
|
+
with self.ema_scope("Plotting"):
|
|
494
|
+
samples, denoise_row = self.sample(batch_size=N, return_intermediates=True)
|
|
495
|
+
|
|
496
|
+
log["samples"] = samples
|
|
497
|
+
log["denoise_row"] = self._get_rows_from_list(denoise_row)
|
|
498
|
+
|
|
499
|
+
if return_keys:
|
|
500
|
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
|
501
|
+
return log
|
|
502
|
+
else:
|
|
503
|
+
return {key: log[key] for key in return_keys}
|
|
504
|
+
return log
|
|
505
|
+
|
|
506
|
+
def configure_optimizers(self):
|
|
507
|
+
lr = self.learning_rate
|
|
508
|
+
params = list(self.model.parameters())
|
|
509
|
+
if self.learn_logvar:
|
|
510
|
+
params = params + [self.logvar]
|
|
511
|
+
opt = torch.optim.AdamW(params, lr=lr)
|
|
512
|
+
return opt
|
|
513
|
+
|
|
514
|
+
|
|
515
|
+
class LatentDiffusion(DDPM):
|
|
516
|
+
"""main class"""
|
|
517
|
+
|
|
518
|
+
def __init__(self,
|
|
519
|
+
first_stage_config,
|
|
520
|
+
cond_stage_config,
|
|
521
|
+
num_timesteps_cond=None,
|
|
522
|
+
cond_stage_key="image",
|
|
523
|
+
cond_stage_trainable=False,
|
|
524
|
+
concat_mode=True,
|
|
525
|
+
cond_stage_forward=None,
|
|
526
|
+
conditioning_key=None,
|
|
527
|
+
scale_factor=1.0,
|
|
528
|
+
scale_by_std=False,
|
|
529
|
+
*args, **kwargs):
|
|
530
|
+
self.num_timesteps_cond = default(num_timesteps_cond, 1)
|
|
531
|
+
self.scale_by_std = scale_by_std
|
|
532
|
+
assert self.num_timesteps_cond <= kwargs['timesteps']
|
|
533
|
+
# for backwards compatibility after implementation of DiffusionWrapper
|
|
534
|
+
if conditioning_key is None:
|
|
535
|
+
conditioning_key = 'concat' if concat_mode else 'crossattn'
|
|
536
|
+
if cond_stage_config == '__is_unconditional__':
|
|
537
|
+
conditioning_key = None
|
|
538
|
+
ckpt_path = kwargs.pop("ckpt_path", None)
|
|
539
|
+
reset_ema = kwargs.pop("reset_ema", False)
|
|
540
|
+
reset_num_ema_updates = kwargs.pop("reset_num_ema_updates", False)
|
|
541
|
+
ignore_keys = kwargs.pop("ignore_keys", [])
|
|
542
|
+
super().__init__(conditioning_key=conditioning_key, *args, **kwargs)
|
|
543
|
+
self.concat_mode = concat_mode
|
|
544
|
+
self.cond_stage_trainable = cond_stage_trainable
|
|
545
|
+
self.cond_stage_key = cond_stage_key
|
|
546
|
+
try:
|
|
547
|
+
self.num_downs = len(first_stage_config.params.ddconfig.ch_mult) - 1
|
|
548
|
+
except:
|
|
549
|
+
self.num_downs = 0
|
|
550
|
+
if not scale_by_std:
|
|
551
|
+
self.scale_factor = scale_factor
|
|
552
|
+
else:
|
|
553
|
+
self.register_buffer('scale_factor', torch.tensor(scale_factor))
|
|
554
|
+
self.instantiate_first_stage(first_stage_config)
|
|
555
|
+
self.instantiate_cond_stage(cond_stage_config)
|
|
556
|
+
self.cond_stage_forward = cond_stage_forward
|
|
557
|
+
self.clip_denoised = False
|
|
558
|
+
self.bbox_tokenizer = None
|
|
559
|
+
|
|
560
|
+
self.restarted_from_ckpt = False
|
|
561
|
+
if ckpt_path is not None:
|
|
562
|
+
self.init_from_ckpt(ckpt_path, ignore_keys)
|
|
563
|
+
self.restarted_from_ckpt = True
|
|
564
|
+
if reset_ema:
|
|
565
|
+
assert self.use_ema
|
|
566
|
+
print(
|
|
567
|
+
f"Resetting ema to pure model weights. This is useful when restoring from an ema-only checkpoint.")
|
|
568
|
+
self.model_ema = LitEma(self.model)
|
|
569
|
+
if reset_num_ema_updates:
|
|
570
|
+
print(" +++++++++++ WARNING: RESETTING NUM_EMA UPDATES TO ZERO +++++++++++ ")
|
|
571
|
+
assert self.use_ema
|
|
572
|
+
self.model_ema.reset_num_updates()
|
|
573
|
+
|
|
574
|
+
def make_cond_schedule(self, ):
|
|
575
|
+
self.cond_ids = torch.full(size=(self.num_timesteps,), fill_value=self.num_timesteps - 1, dtype=torch.long)
|
|
576
|
+
ids = torch.round(torch.linspace(0, self.num_timesteps - 1, self.num_timesteps_cond)).long()
|
|
577
|
+
self.cond_ids[:self.num_timesteps_cond] = ids
|
|
578
|
+
|
|
579
|
+
def register_schedule(self,
|
|
580
|
+
given_betas=None, beta_schedule="linear", timesteps=1000,
|
|
581
|
+
linear_start=0.00085, linear_end=0.012, cosine_s=8e-3):
|
|
582
|
+
linear_start = 0.00085
|
|
583
|
+
linear_end = 0.012
|
|
584
|
+
super().register_schedule(given_betas, beta_schedule, timesteps, linear_start, linear_end, cosine_s)
|
|
585
|
+
|
|
586
|
+
self.shorten_cond_schedule = self.num_timesteps_cond > 1
|
|
587
|
+
if self.shorten_cond_schedule:
|
|
588
|
+
self.make_cond_schedule()
|
|
589
|
+
|
|
590
|
+
def instantiate_first_stage(self, config):
|
|
591
|
+
model = instantiate_from_config(config)
|
|
592
|
+
self.first_stage_model = model.eval()
|
|
593
|
+
self.first_stage_model.train = disabled_train
|
|
594
|
+
for param in self.first_stage_model.parameters():
|
|
595
|
+
param.requires_grad = False
|
|
596
|
+
|
|
597
|
+
def instantiate_cond_stage(self, config):
|
|
598
|
+
if not self.cond_stage_trainable:
|
|
599
|
+
if config == "__is_first_stage__":
|
|
600
|
+
print("Using first stage also as cond stage.")
|
|
601
|
+
self.cond_stage_model = self.first_stage_model
|
|
602
|
+
elif config == "__is_unconditional__":
|
|
603
|
+
print(f"Training {self.__class__.__name__} as an unconditional model.")
|
|
604
|
+
self.cond_stage_model = None
|
|
605
|
+
# self.be_unconditional = True
|
|
606
|
+
else:
|
|
607
|
+
model = instantiate_from_config(config)
|
|
608
|
+
self.cond_stage_model = model.eval()
|
|
609
|
+
self.cond_stage_model.train = disabled_train
|
|
610
|
+
for param in self.cond_stage_model.parameters():
|
|
611
|
+
param.requires_grad = False
|
|
612
|
+
else:
|
|
613
|
+
assert config != '__is_first_stage__'
|
|
614
|
+
assert config != '__is_unconditional__'
|
|
615
|
+
model = instantiate_from_config(config)
|
|
616
|
+
self.cond_stage_model = model
|
|
617
|
+
|
|
618
|
+
def _get_denoise_row_from_list(self, samples, desc='', force_no_decoder_quantization=False):
|
|
619
|
+
denoise_row = []
|
|
620
|
+
for zd in tqdm(samples, desc=desc):
|
|
621
|
+
denoise_row.append(self.decode_first_stage(zd.to(self.device),
|
|
622
|
+
force_not_quantize=force_no_decoder_quantization))
|
|
623
|
+
n_imgs_per_row = len(denoise_row)
|
|
624
|
+
denoise_row = torch.stack(denoise_row) # n_log_step, n_row, C, H, W
|
|
625
|
+
denoise_grid = rearrange(denoise_row, 'n b c h w -> b n c h w')
|
|
626
|
+
denoise_grid = rearrange(denoise_grid, 'b n c h w -> (b n) c h w')
|
|
627
|
+
denoise_grid = make_grid(denoise_grid, nrow=n_imgs_per_row)
|
|
628
|
+
return denoise_grid
|
|
629
|
+
|
|
630
|
+
def get_first_stage_encoding(self, encoder_posterior):
|
|
631
|
+
if isinstance(encoder_posterior, DiagonalGaussianDistribution):
|
|
632
|
+
z = encoder_posterior.sample()
|
|
633
|
+
elif isinstance(encoder_posterior, torch.Tensor):
|
|
634
|
+
z = encoder_posterior
|
|
635
|
+
else:
|
|
636
|
+
raise NotImplementedError(f"encoder_posterior of type '{type(encoder_posterior)}' not yet implemented")
|
|
637
|
+
|
|
638
|
+
return self.scale_factor * z
|
|
639
|
+
|
|
640
|
+
def get_learned_conditioning(self, c):
|
|
641
|
+
if self.cond_stage_forward is None:
|
|
642
|
+
if hasattr(self.cond_stage_model, 'encode') and callable(self.cond_stage_model.encode):
|
|
643
|
+
c = self.cond_stage_model.encode(c)
|
|
644
|
+
if isinstance(c, DiagonalGaussianDistribution):
|
|
645
|
+
c = c.mode()
|
|
646
|
+
else:
|
|
647
|
+
c = self.cond_stage_model(c)
|
|
648
|
+
else:
|
|
649
|
+
assert hasattr(self.cond_stage_model, self.cond_stage_forward)
|
|
650
|
+
c = getattr(self.cond_stage_model, self.cond_stage_forward)(c)
|
|
651
|
+
return c
|
|
652
|
+
|
|
653
|
+
def meshgrid(self, h, w):
|
|
654
|
+
y = torch.arange(0, h).view(h, 1, 1).repeat(1, w, 1)
|
|
655
|
+
x = torch.arange(0, w).view(1, w, 1).repeat(h, 1, 1)
|
|
656
|
+
|
|
657
|
+
arr = torch.cat([y, x], dim=-1)
|
|
658
|
+
return arr
|
|
659
|
+
|
|
660
|
+
def delta_border(self, h, w):
|
|
661
|
+
"""
|
|
662
|
+
:param h: height
|
|
663
|
+
:param w: width
|
|
664
|
+
:return: normalized distance to image border,
|
|
665
|
+
wtith min distance = 0 at border and max dist = 0.5 at image center
|
|
666
|
+
"""
|
|
667
|
+
lower_right_corner = torch.tensor([h - 1, w - 1]).view(1, 1, 2)
|
|
668
|
+
arr = self.meshgrid(h, w) / lower_right_corner
|
|
669
|
+
dist_left_up = torch.min(arr, dim=-1, keepdims=True)[0]
|
|
670
|
+
dist_right_down = torch.min(1 - arr, dim=-1, keepdims=True)[0]
|
|
671
|
+
edge_dist = torch.min(torch.cat([dist_left_up, dist_right_down], dim=-1), dim=-1)[0]
|
|
672
|
+
return edge_dist
|
|
673
|
+
|
|
674
|
+
def get_weighting(self, h, w, Ly, Lx, device):
|
|
675
|
+
weighting = self.delta_border(h, w)
|
|
676
|
+
weighting = torch.clip(weighting, self.split_input_params["clip_min_weight"],
|
|
677
|
+
self.split_input_params["clip_max_weight"], )
|
|
678
|
+
weighting = weighting.view(1, h * w, 1).repeat(1, 1, Ly * Lx).to(device)
|
|
679
|
+
|
|
680
|
+
if self.split_input_params["tie_braker"]:
|
|
681
|
+
L_weighting = self.delta_border(Ly, Lx)
|
|
682
|
+
L_weighting = torch.clip(L_weighting,
|
|
683
|
+
self.split_input_params["clip_min_tie_weight"],
|
|
684
|
+
self.split_input_params["clip_max_tie_weight"])
|
|
685
|
+
|
|
686
|
+
L_weighting = L_weighting.view(1, 1, Ly * Lx).to(device)
|
|
687
|
+
weighting = weighting * L_weighting
|
|
688
|
+
return weighting
|
|
689
|
+
|
|
690
|
+
def get_fold_unfold(self, x, kernel_size, stride, uf=1, df=1): # todo load once not every time, shorten code
|
|
691
|
+
"""
|
|
692
|
+
:param x: img of size (bs, c, h, w)
|
|
693
|
+
:return: n img crops of size (n, bs, c, kernel_size[0], kernel_size[1])
|
|
694
|
+
"""
|
|
695
|
+
bs, nc, h, w = x.shape
|
|
696
|
+
|
|
697
|
+
# number of crops in image
|
|
698
|
+
Ly = (h - kernel_size[0]) // stride[0] + 1
|
|
699
|
+
Lx = (w - kernel_size[1]) // stride[1] + 1
|
|
700
|
+
|
|
701
|
+
if uf == 1 and df == 1:
|
|
702
|
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
|
703
|
+
unfold = torch.nn.Unfold(**fold_params)
|
|
704
|
+
|
|
705
|
+
fold = torch.nn.Fold(output_size=x.shape[2:], **fold_params)
|
|
706
|
+
|
|
707
|
+
weighting = self.get_weighting(kernel_size[0], kernel_size[1], Ly, Lx, x.device).to(x.dtype)
|
|
708
|
+
normalization = fold(weighting).view(1, 1, h, w) # normalizes the overlap
|
|
709
|
+
weighting = weighting.view((1, 1, kernel_size[0], kernel_size[1], Ly * Lx))
|
|
710
|
+
|
|
711
|
+
elif uf > 1 and df == 1:
|
|
712
|
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
|
713
|
+
unfold = torch.nn.Unfold(**fold_params)
|
|
714
|
+
|
|
715
|
+
fold_params2 = dict(kernel_size=(kernel_size[0] * uf, kernel_size[0] * uf),
|
|
716
|
+
dilation=1, padding=0,
|
|
717
|
+
stride=(stride[0] * uf, stride[1] * uf))
|
|
718
|
+
fold = torch.nn.Fold(output_size=(x.shape[2] * uf, x.shape[3] * uf), **fold_params2)
|
|
719
|
+
|
|
720
|
+
weighting = self.get_weighting(kernel_size[0] * uf, kernel_size[1] * uf, Ly, Lx, x.device).to(x.dtype)
|
|
721
|
+
normalization = fold(weighting).view(1, 1, h * uf, w * uf) # normalizes the overlap
|
|
722
|
+
weighting = weighting.view((1, 1, kernel_size[0] * uf, kernel_size[1] * uf, Ly * Lx))
|
|
723
|
+
|
|
724
|
+
elif df > 1 and uf == 1:
|
|
725
|
+
fold_params = dict(kernel_size=kernel_size, dilation=1, padding=0, stride=stride)
|
|
726
|
+
unfold = torch.nn.Unfold(**fold_params)
|
|
727
|
+
|
|
728
|
+
fold_params2 = dict(kernel_size=(kernel_size[0] // df, kernel_size[0] // df),
|
|
729
|
+
dilation=1, padding=0,
|
|
730
|
+
stride=(stride[0] // df, stride[1] // df))
|
|
731
|
+
fold = torch.nn.Fold(output_size=(x.shape[2] // df, x.shape[3] // df), **fold_params2)
|
|
732
|
+
|
|
733
|
+
weighting = self.get_weighting(kernel_size[0] // df, kernel_size[1] // df, Ly, Lx, x.device).to(x.dtype)
|
|
734
|
+
normalization = fold(weighting).view(1, 1, h // df, w // df) # normalizes the overlap
|
|
735
|
+
weighting = weighting.view((1, 1, kernel_size[0] // df, kernel_size[1] // df, Ly * Lx))
|
|
736
|
+
|
|
737
|
+
else:
|
|
738
|
+
raise NotImplementedError
|
|
739
|
+
|
|
740
|
+
return fold, unfold, normalization, weighting
|
|
741
|
+
|
|
742
|
+
@torch.no_grad()
|
|
743
|
+
def get_input(self, batch, k, return_first_stage_outputs=False, force_c_encode=False,
|
|
744
|
+
cond_key=None, return_original_cond=False, bs=None):
|
|
745
|
+
x = super().get_input(batch, k)
|
|
746
|
+
if bs is not None:
|
|
747
|
+
x = x[:bs]
|
|
748
|
+
x = x.to(self.device)
|
|
749
|
+
encoder_posterior = self.encode_first_stage(x)
|
|
750
|
+
z = self.get_first_stage_encoding(encoder_posterior).detach()
|
|
751
|
+
|
|
752
|
+
if self.model.conditioning_key is not None:
|
|
753
|
+
if cond_key is None:
|
|
754
|
+
cond_key = self.cond_stage_key
|
|
755
|
+
if cond_key != self.first_stage_key:
|
|
756
|
+
if cond_key in ['caption', 'coordinates_bbox', "txt"]:
|
|
757
|
+
xc = batch[cond_key]
|
|
758
|
+
elif cond_key in ['class_label', 'cls']:
|
|
759
|
+
xc = batch
|
|
760
|
+
else:
|
|
761
|
+
xc = super().get_input(batch, cond_key).to(self.device)
|
|
762
|
+
else:
|
|
763
|
+
xc = x
|
|
764
|
+
if not self.cond_stage_trainable or force_c_encode:
|
|
765
|
+
if isinstance(xc, dict) or isinstance(xc, list):
|
|
766
|
+
# import pudb; pudb.set_trace()
|
|
767
|
+
c = self.get_learned_conditioning(xc)
|
|
768
|
+
else:
|
|
769
|
+
c = self.get_learned_conditioning(xc.to(self.device))
|
|
770
|
+
else:
|
|
771
|
+
c = xc
|
|
772
|
+
if bs is not None:
|
|
773
|
+
c = c[:bs]
|
|
774
|
+
|
|
775
|
+
if self.use_positional_encodings:
|
|
776
|
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
|
777
|
+
ckey = __conditioning_keys__[self.model.conditioning_key]
|
|
778
|
+
c = {ckey: c, 'pos_x': pos_x, 'pos_y': pos_y}
|
|
779
|
+
|
|
780
|
+
else:
|
|
781
|
+
c = None
|
|
782
|
+
xc = None
|
|
783
|
+
if self.use_positional_encodings:
|
|
784
|
+
pos_x, pos_y = self.compute_latent_shifts(batch)
|
|
785
|
+
c = {'pos_x': pos_x, 'pos_y': pos_y}
|
|
786
|
+
out = [z, c]
|
|
787
|
+
if return_first_stage_outputs:
|
|
788
|
+
xrec = self.decode_first_stage(z)
|
|
789
|
+
out.extend([x, xrec])
|
|
790
|
+
if return_original_cond:
|
|
791
|
+
out.append(xc)
|
|
792
|
+
return out
|
|
793
|
+
|
|
794
|
+
def decode_first_stage_training(self, z, predict_cids=False, force_not_quantize=False):
|
|
795
|
+
# print('decoding...')
|
|
796
|
+
#
|
|
797
|
+
# def print_message(grad):
|
|
798
|
+
# print('backward decoding')
|
|
799
|
+
#
|
|
800
|
+
# z.register_hook(print_message)
|
|
801
|
+
|
|
802
|
+
if predict_cids:
|
|
803
|
+
if z.dim() == 4:
|
|
804
|
+
z = torch.argmax(z.exp(), dim=1).long()
|
|
805
|
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
|
806
|
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
|
807
|
+
|
|
808
|
+
z = 1. / self.scale_factor * z
|
|
809
|
+
return self.first_stage_model.decode(z)
|
|
810
|
+
|
|
811
|
+
|
|
812
|
+
|
|
813
|
+
@torch.no_grad()
|
|
814
|
+
def decode_first_stage(self, z, predict_cids=False, force_not_quantize=False):
|
|
815
|
+
if predict_cids:
|
|
816
|
+
if z.dim() == 4:
|
|
817
|
+
z = torch.argmax(z.exp(), dim=1).long()
|
|
818
|
+
z = self.first_stage_model.quantize.get_codebook_entry(z, shape=None)
|
|
819
|
+
z = rearrange(z, 'b h w c -> b c h w').contiguous()
|
|
820
|
+
|
|
821
|
+
z = 1. / self.scale_factor * z
|
|
822
|
+
return self.first_stage_model.decode(z)
|
|
823
|
+
|
|
824
|
+
|
|
825
|
+
@torch.no_grad()
|
|
826
|
+
def encode_first_stage(self, x):
|
|
827
|
+
return self.first_stage_model.encode(x)
|
|
828
|
+
|
|
829
|
+
def shared_step(self, batch, **kwargs):
|
|
830
|
+
x, c = self.get_input(batch, self.first_stage_key)
|
|
831
|
+
loss = self(x, c, **kwargs)
|
|
832
|
+
return loss
|
|
833
|
+
|
|
834
|
+
def get_time_with_schedule(self, scheduler, bs):
|
|
835
|
+
if scheduler == 'linear':
|
|
836
|
+
t = torch.randint(0, self.num_timesteps, (bs,), device=self.device).long()
|
|
837
|
+
elif scheduler == 'cosine':
|
|
838
|
+
t = torch.rand((bs, ), device=self.device)
|
|
839
|
+
t = torch.cos(torch.pi / 2. * t) * self.num_timesteps
|
|
840
|
+
t = t.long()
|
|
841
|
+
elif scheduler == 'cubic':
|
|
842
|
+
t = torch.rand((bs,), device=self.device)
|
|
843
|
+
t = (1 - t ** 3) * self.num_timesteps
|
|
844
|
+
t = t.long()
|
|
845
|
+
else:
|
|
846
|
+
raise NotImplementedError
|
|
847
|
+
t = torch.clamp(t, min=0, max=self.num_timesteps-1)
|
|
848
|
+
return t
|
|
849
|
+
|
|
850
|
+
def forward(self, x,mask, c, *args, **kwargs):
|
|
851
|
+
if 't' not in kwargs:
|
|
852
|
+
t = torch.randint(0, self.num_timesteps, (x.shape[0], ), device=self.device).long()
|
|
853
|
+
else:
|
|
854
|
+
t = kwargs.pop('t')
|
|
855
|
+
|
|
856
|
+
return self.p_losses(x,mask, c, t, *args, **kwargs)
|
|
857
|
+
|
|
858
|
+
def apply_model(self, x_noisy, mask,t, cond, return_ids=False, **kwargs):
|
|
859
|
+
if isinstance(cond, dict):
|
|
860
|
+
# hybrid case, cond is expected to be a dict
|
|
861
|
+
pass
|
|
862
|
+
else:
|
|
863
|
+
if not isinstance(cond, list):
|
|
864
|
+
cond = [cond]
|
|
865
|
+
key = 'c_concat' if self.model.conditioning_key == 'concat' else 'c_crossattn'
|
|
866
|
+
cond = {key: cond}
|
|
867
|
+
|
|
868
|
+
|
|
869
|
+
x_recon = self.model(x_noisy, mask,t, **cond, **kwargs)
|
|
870
|
+
|
|
871
|
+
if isinstance(x_recon, tuple) and not return_ids:
|
|
872
|
+
return x_recon[0]
|
|
873
|
+
else:
|
|
874
|
+
return x_recon
|
|
875
|
+
|
|
876
|
+
def _predict_eps_from_xstart(self, x_t, t, pred_xstart):
|
|
877
|
+
return (extract_into_tensor(self.sqrt_recip_alphas_cumprod, t, x_t.shape) * x_t - pred_xstart) / \
|
|
878
|
+
extract_into_tensor(self.sqrt_recipm1_alphas_cumprod, t, x_t.shape)
|
|
879
|
+
|
|
880
|
+
def _prior_bpd(self, x_start):
|
|
881
|
+
"""
|
|
882
|
+
Get the prior KL term for the variational lower-bound, measured in
|
|
883
|
+
bits-per-dim.
|
|
884
|
+
This term can't be optimized, as it only depends on the encoder.
|
|
885
|
+
:param x_start: the [N x C x ...] tensor of inputs.
|
|
886
|
+
:return: a batch of [N] KL values (in bits), one per batch element.
|
|
887
|
+
"""
|
|
888
|
+
batch_size = x_start.shape[0]
|
|
889
|
+
t = torch.tensor([self.num_timesteps - 1] * batch_size, device=x_start.device)
|
|
890
|
+
qt_mean, _, qt_log_variance = self.q_mean_variance(x_start, t)
|
|
891
|
+
kl_prior = normal_kl(mean1=qt_mean, logvar1=qt_log_variance, mean2=0.0, logvar2=0.0)
|
|
892
|
+
return mean_flat(kl_prior) / np.log(2.0)
|
|
893
|
+
|
|
894
|
+
def p_losses(self, x_start, mask,cond, t, noise=None, **kwargs):
|
|
895
|
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
|
896
|
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
|
897
|
+
model_output = self.apply_model(x_noisy,mask, t, cond, **kwargs)
|
|
898
|
+
|
|
899
|
+
loss_dict = {}
|
|
900
|
+
prefix = 'train' if self.training else 'val'
|
|
901
|
+
|
|
902
|
+
# ops
|
|
903
|
+
|
|
904
|
+
if self.parameterization == "x0":
|
|
905
|
+
target = x_start
|
|
906
|
+
elif self.parameterization == "eps":
|
|
907
|
+
target = noise
|
|
908
|
+
elif self.parameterization == "v":
|
|
909
|
+
target = self.get_v(x_start, noise, t)
|
|
910
|
+
else:
|
|
911
|
+
raise NotImplementedError()
|
|
912
|
+
|
|
913
|
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
|
|
914
|
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
|
915
|
+
|
|
916
|
+
logvar_t = self.logvar[t].to(self.device)
|
|
917
|
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
|
918
|
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
|
919
|
+
if self.learn_logvar:
|
|
920
|
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
|
921
|
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
|
922
|
+
|
|
923
|
+
loss = self.l_simple_weight * loss.mean()
|
|
924
|
+
|
|
925
|
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
|
|
926
|
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
|
927
|
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
|
928
|
+
loss += (self.original_elbo_weight * loss_vlb)
|
|
929
|
+
loss_dict.update({f'{prefix}/loss': loss})
|
|
930
|
+
|
|
931
|
+
|
|
932
|
+
|
|
933
|
+
pred_x0 = self.predict_start_from_noise(x_t=x_noisy, t=t, noise=model_output)
|
|
934
|
+
|
|
935
|
+
|
|
936
|
+
return loss, loss_dict,pred_x0
|
|
937
|
+
|
|
938
|
+
def p_losses_origin(self, x_start, cond, t, noise=None, **kwargs):
|
|
939
|
+
noise = default(noise, lambda: torch.randn_like(x_start))
|
|
940
|
+
x_noisy = self.q_sample(x_start=x_start, t=t, noise=noise)
|
|
941
|
+
model_output = self.apply_model(x_noisy, t, cond, **kwargs)
|
|
942
|
+
|
|
943
|
+
loss_dict = {}
|
|
944
|
+
prefix = 'train' if self.training else 'val'
|
|
945
|
+
|
|
946
|
+
if self.parameterization == "x0":
|
|
947
|
+
target = x_start
|
|
948
|
+
elif self.parameterization == "eps":
|
|
949
|
+
target = noise
|
|
950
|
+
elif self.parameterization == "v":
|
|
951
|
+
target = self.get_v(x_start, noise, t)
|
|
952
|
+
else:
|
|
953
|
+
raise NotImplementedError()
|
|
954
|
+
|
|
955
|
+
loss_simple = self.get_loss(model_output, target, mean=False).mean([1, 2, 3])
|
|
956
|
+
loss_dict.update({f'{prefix}/loss_simple': loss_simple.mean()})
|
|
957
|
+
|
|
958
|
+
logvar_t = self.logvar[t].to(self.device)
|
|
959
|
+
loss = loss_simple / torch.exp(logvar_t) + logvar_t
|
|
960
|
+
# loss = loss_simple / torch.exp(self.logvar) + self.logvar
|
|
961
|
+
if self.learn_logvar:
|
|
962
|
+
loss_dict.update({f'{prefix}/loss_gamma': loss.mean()})
|
|
963
|
+
loss_dict.update({'logvar': self.logvar.data.mean()})
|
|
964
|
+
|
|
965
|
+
loss = self.l_simple_weight * loss.mean()
|
|
966
|
+
|
|
967
|
+
loss_vlb = self.get_loss(model_output, target, mean=False).mean(dim=(1, 2, 3))
|
|
968
|
+
loss_vlb = (self.lvlb_weights[t] * loss_vlb).mean()
|
|
969
|
+
loss_dict.update({f'{prefix}/loss_vlb': loss_vlb})
|
|
970
|
+
loss += (self.original_elbo_weight * loss_vlb)
|
|
971
|
+
loss_dict.update({f'{prefix}/loss': loss})
|
|
972
|
+
|
|
973
|
+
return loss, loss_dict
|
|
974
|
+
|
|
975
|
+
def p_mean_variance(self, x, c, t, clip_denoised: bool, return_codebook_ids=False, quantize_denoised=False,
|
|
976
|
+
return_x0=False, score_corrector=None, corrector_kwargs=None):
|
|
977
|
+
t_in = t
|
|
978
|
+
model_out = self.apply_model(x, t_in, c, return_ids=return_codebook_ids)
|
|
979
|
+
|
|
980
|
+
if score_corrector is not None:
|
|
981
|
+
assert self.parameterization == "eps"
|
|
982
|
+
model_out = score_corrector.modify_score(self, model_out, x, t, c, **corrector_kwargs)
|
|
983
|
+
|
|
984
|
+
if return_codebook_ids:
|
|
985
|
+
model_out, logits = model_out
|
|
986
|
+
|
|
987
|
+
if self.parameterization == "eps":
|
|
988
|
+
x_recon = self.predict_start_from_noise(x, t=t, noise=model_out)
|
|
989
|
+
elif self.parameterization == "x0":
|
|
990
|
+
x_recon = model_out
|
|
991
|
+
else:
|
|
992
|
+
raise NotImplementedError()
|
|
993
|
+
|
|
994
|
+
if clip_denoised:
|
|
995
|
+
x_recon.clamp_(-1., 1.)
|
|
996
|
+
if quantize_denoised:
|
|
997
|
+
x_recon, _, [_, _, indices] = self.first_stage_model.quantize(x_recon)
|
|
998
|
+
model_mean, posterior_variance, posterior_log_variance = self.q_posterior(x_start=x_recon, x_t=x, t=t)
|
|
999
|
+
if return_codebook_ids:
|
|
1000
|
+
return model_mean, posterior_variance, posterior_log_variance, logits
|
|
1001
|
+
elif return_x0:
|
|
1002
|
+
return model_mean, posterior_variance, posterior_log_variance, x_recon
|
|
1003
|
+
else:
|
|
1004
|
+
return model_mean, posterior_variance, posterior_log_variance
|
|
1005
|
+
|
|
1006
|
+
@torch.no_grad()
|
|
1007
|
+
def p_sample(self, x, c, t, clip_denoised=False, repeat_noise=False,
|
|
1008
|
+
return_codebook_ids=False, quantize_denoised=False, return_x0=False,
|
|
1009
|
+
temperature=1., noise_dropout=0., score_corrector=None, corrector_kwargs=None):
|
|
1010
|
+
b, *_, device = *x.shape, x.device
|
|
1011
|
+
outputs = self.p_mean_variance(x=x, c=c, t=t, clip_denoised=clip_denoised,
|
|
1012
|
+
return_codebook_ids=return_codebook_ids,
|
|
1013
|
+
quantize_denoised=quantize_denoised,
|
|
1014
|
+
return_x0=return_x0,
|
|
1015
|
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
|
1016
|
+
if return_codebook_ids:
|
|
1017
|
+
raise DeprecationWarning("Support dropped.")
|
|
1018
|
+
model_mean, _, model_log_variance, logits = outputs
|
|
1019
|
+
elif return_x0:
|
|
1020
|
+
model_mean, _, model_log_variance, x0 = outputs
|
|
1021
|
+
else:
|
|
1022
|
+
model_mean, _, model_log_variance = outputs
|
|
1023
|
+
|
|
1024
|
+
noise = noise_like(x.shape, device, repeat_noise) * temperature
|
|
1025
|
+
if noise_dropout > 0.:
|
|
1026
|
+
noise = torch.nn.functional.dropout(noise, p=noise_dropout)
|
|
1027
|
+
# no noise when t == 0
|
|
1028
|
+
nonzero_mask = (1 - (t == 0).float()).reshape(b, *((1,) * (len(x.shape) - 1)))
|
|
1029
|
+
|
|
1030
|
+
if return_codebook_ids:
|
|
1031
|
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, logits.argmax(dim=1)
|
|
1032
|
+
if return_x0:
|
|
1033
|
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise, x0
|
|
1034
|
+
else:
|
|
1035
|
+
return model_mean + nonzero_mask * (0.5 * model_log_variance).exp() * noise
|
|
1036
|
+
|
|
1037
|
+
@torch.no_grad()
|
|
1038
|
+
def progressive_denoising(self, cond, shape, verbose=True, callback=None, quantize_denoised=False,
|
|
1039
|
+
img_callback=None, mask=None, x0=None, temperature=1., noise_dropout=0.,
|
|
1040
|
+
score_corrector=None, corrector_kwargs=None, batch_size=None, x_T=None, start_T=None,
|
|
1041
|
+
log_every_t=None):
|
|
1042
|
+
if not log_every_t:
|
|
1043
|
+
log_every_t = self.log_every_t
|
|
1044
|
+
timesteps = self.num_timesteps
|
|
1045
|
+
if batch_size is not None:
|
|
1046
|
+
b = batch_size if batch_size is not None else shape[0]
|
|
1047
|
+
shape = [batch_size] + list(shape)
|
|
1048
|
+
else:
|
|
1049
|
+
b = batch_size = shape[0]
|
|
1050
|
+
if x_T is None:
|
|
1051
|
+
img = torch.randn(shape, device=self.device)
|
|
1052
|
+
else:
|
|
1053
|
+
img = x_T
|
|
1054
|
+
intermediates = []
|
|
1055
|
+
if cond is not None:
|
|
1056
|
+
if isinstance(cond, dict):
|
|
1057
|
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
|
1058
|
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
|
1059
|
+
else:
|
|
1060
|
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
|
1061
|
+
|
|
1062
|
+
if start_T is not None:
|
|
1063
|
+
timesteps = min(timesteps, start_T)
|
|
1064
|
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Progressive Generation',
|
|
1065
|
+
total=timesteps) if verbose else reversed(
|
|
1066
|
+
range(0, timesteps))
|
|
1067
|
+
if type(temperature) == float:
|
|
1068
|
+
temperature = [temperature] * timesteps
|
|
1069
|
+
|
|
1070
|
+
for i in iterator:
|
|
1071
|
+
ts = torch.full((b,), i, device=self.device, dtype=torch.long)
|
|
1072
|
+
if self.shorten_cond_schedule:
|
|
1073
|
+
assert self.model.conditioning_key != 'hybrid'
|
|
1074
|
+
tc = self.cond_ids[ts].to(cond.device)
|
|
1075
|
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
|
1076
|
+
|
|
1077
|
+
img, x0_partial = self.p_sample(img, cond, ts,
|
|
1078
|
+
clip_denoised=self.clip_denoised,
|
|
1079
|
+
quantize_denoised=quantize_denoised, return_x0=True,
|
|
1080
|
+
temperature=temperature[i], noise_dropout=noise_dropout,
|
|
1081
|
+
score_corrector=score_corrector, corrector_kwargs=corrector_kwargs)
|
|
1082
|
+
if mask is not None:
|
|
1083
|
+
assert x0 is not None
|
|
1084
|
+
img_orig = self.q_sample(x0, ts)
|
|
1085
|
+
img = img_orig * mask + (1. - mask) * img
|
|
1086
|
+
|
|
1087
|
+
if i % log_every_t == 0 or i == timesteps - 1:
|
|
1088
|
+
intermediates.append(x0_partial)
|
|
1089
|
+
if callback: callback(i)
|
|
1090
|
+
if img_callback: img_callback(img, i)
|
|
1091
|
+
return img, intermediates
|
|
1092
|
+
|
|
1093
|
+
@torch.no_grad()
|
|
1094
|
+
def p_sample_loop(self, cond, shape, return_intermediates=False,
|
|
1095
|
+
x_T=None, verbose=True, callback=None, timesteps=None, quantize_denoised=False,
|
|
1096
|
+
mask=None, x0=None, img_callback=None, start_T=None,
|
|
1097
|
+
log_every_t=None):
|
|
1098
|
+
|
|
1099
|
+
if not log_every_t:
|
|
1100
|
+
log_every_t = self.log_every_t
|
|
1101
|
+
device = self.betas.device
|
|
1102
|
+
b = shape[0]
|
|
1103
|
+
if x_T is None:
|
|
1104
|
+
img = torch.randn(shape, device=device)
|
|
1105
|
+
else:
|
|
1106
|
+
img = x_T
|
|
1107
|
+
|
|
1108
|
+
intermediates = [img]
|
|
1109
|
+
if timesteps is None:
|
|
1110
|
+
timesteps = self.num_timesteps
|
|
1111
|
+
|
|
1112
|
+
if start_T is not None:
|
|
1113
|
+
timesteps = min(timesteps, start_T)
|
|
1114
|
+
iterator = tqdm(reversed(range(0, timesteps)), desc='Sampling t', total=timesteps) if verbose else reversed(
|
|
1115
|
+
range(0, timesteps))
|
|
1116
|
+
|
|
1117
|
+
if mask is not None:
|
|
1118
|
+
assert x0 is not None
|
|
1119
|
+
assert x0.shape[2:3] == mask.shape[2:3] # spatial size has to match
|
|
1120
|
+
|
|
1121
|
+
for i in iterator:
|
|
1122
|
+
ts = torch.full((b,), i, device=device, dtype=torch.long)
|
|
1123
|
+
if self.shorten_cond_schedule:
|
|
1124
|
+
assert self.model.conditioning_key != 'hybrid'
|
|
1125
|
+
tc = self.cond_ids[ts].to(cond.device)
|
|
1126
|
+
cond = self.q_sample(x_start=cond, t=tc, noise=torch.randn_like(cond))
|
|
1127
|
+
|
|
1128
|
+
img = self.p_sample(img, cond, ts,
|
|
1129
|
+
clip_denoised=self.clip_denoised,
|
|
1130
|
+
quantize_denoised=quantize_denoised)
|
|
1131
|
+
if mask is not None:
|
|
1132
|
+
img_orig = self.q_sample(x0, ts)
|
|
1133
|
+
img = img_orig * mask + (1. - mask) * img
|
|
1134
|
+
|
|
1135
|
+
if i % log_every_t == 0 or i == timesteps - 1:
|
|
1136
|
+
intermediates.append(img)
|
|
1137
|
+
if callback: callback(i)
|
|
1138
|
+
if img_callback: img_callback(img, i)
|
|
1139
|
+
|
|
1140
|
+
if return_intermediates:
|
|
1141
|
+
return img, intermediates
|
|
1142
|
+
return img
|
|
1143
|
+
|
|
1144
|
+
@torch.no_grad()
|
|
1145
|
+
def sample(self, cond, batch_size=16, return_intermediates=False, x_T=None,
|
|
1146
|
+
verbose=True, timesteps=None, quantize_denoised=False,
|
|
1147
|
+
mask=None, x0=None, shape=None, **kwargs):
|
|
1148
|
+
if shape is None:
|
|
1149
|
+
shape = (batch_size, self.channels, self.image_size, self.image_size)
|
|
1150
|
+
if cond is not None:
|
|
1151
|
+
if isinstance(cond, dict):
|
|
1152
|
+
cond = {key: cond[key][:batch_size] if not isinstance(cond[key], list) else
|
|
1153
|
+
list(map(lambda x: x[:batch_size], cond[key])) for key in cond}
|
|
1154
|
+
else:
|
|
1155
|
+
cond = [c[:batch_size] for c in cond] if isinstance(cond, list) else cond[:batch_size]
|
|
1156
|
+
return self.p_sample_loop(cond,
|
|
1157
|
+
shape,
|
|
1158
|
+
return_intermediates=return_intermediates, x_T=x_T,
|
|
1159
|
+
verbose=verbose, timesteps=timesteps, quantize_denoised=quantize_denoised,
|
|
1160
|
+
mask=mask, x0=x0)
|
|
1161
|
+
|
|
1162
|
+
@torch.no_grad()
|
|
1163
|
+
def sample_log(self, cond, batch_size, ddim, ddim_steps, **kwargs):
|
|
1164
|
+
if ddim:
|
|
1165
|
+
ddim_sampler = DDIMSampler(self)
|
|
1166
|
+
shape = (self.channels, self.image_size, self.image_size)
|
|
1167
|
+
samples, intermediates = ddim_sampler.sample(ddim_steps, batch_size,
|
|
1168
|
+
shape, cond, verbose=False, **kwargs)
|
|
1169
|
+
|
|
1170
|
+
else:
|
|
1171
|
+
samples, intermediates = self.sample(cond=cond, batch_size=batch_size,
|
|
1172
|
+
return_intermediates=True, **kwargs)
|
|
1173
|
+
|
|
1174
|
+
return samples, intermediates
|
|
1175
|
+
|
|
1176
|
+
@torch.no_grad()
|
|
1177
|
+
def get_unconditional_conditioning(self, batch_size, null_label=None):
|
|
1178
|
+
if null_label is not None:
|
|
1179
|
+
xc = null_label
|
|
1180
|
+
if isinstance(xc, ListConfig):
|
|
1181
|
+
xc = list(xc)
|
|
1182
|
+
if isinstance(xc, dict) or isinstance(xc, list):
|
|
1183
|
+
c = self.get_learned_conditioning(xc)
|
|
1184
|
+
else:
|
|
1185
|
+
if hasattr(xc, "to"):
|
|
1186
|
+
xc = xc.to(self.device)
|
|
1187
|
+
c = self.get_learned_conditioning(xc)
|
|
1188
|
+
else:
|
|
1189
|
+
if self.cond_stage_key in ["class_label", "cls"]:
|
|
1190
|
+
xc = self.cond_stage_model.get_unconditional_conditioning(batch_size, device=self.device)
|
|
1191
|
+
return self.get_learned_conditioning(xc)
|
|
1192
|
+
else:
|
|
1193
|
+
raise NotImplementedError("todo")
|
|
1194
|
+
if isinstance(c, list): # in case the encoder gives us a list
|
|
1195
|
+
for i in range(len(c)):
|
|
1196
|
+
c[i] = repeat(c[i], '1 ... -> b ...', b=batch_size).to(self.device)
|
|
1197
|
+
else:
|
|
1198
|
+
c = repeat(c, '1 ... -> b ...', b=batch_size).to(self.device)
|
|
1199
|
+
return c
|
|
1200
|
+
|
|
1201
|
+
@torch.no_grad()
|
|
1202
|
+
def log_images(self, batch, N=8, n_row=4, sample=True, ddim_steps=50, ddim_eta=0., return_keys=None,
|
|
1203
|
+
quantize_denoised=True, inpaint=True, plot_denoise_rows=False, plot_progressive_rows=True,
|
|
1204
|
+
plot_diffusion_rows=True, unconditional_guidance_scale=1., unconditional_guidance_label=None,
|
|
1205
|
+
use_ema_scope=True,
|
|
1206
|
+
**kwargs):
|
|
1207
|
+
ema_scope = self.ema_scope if use_ema_scope else nullcontext
|
|
1208
|
+
use_ddim = ddim_steps is not None
|
|
1209
|
+
|
|
1210
|
+
log = dict()
|
|
1211
|
+
z, c, x, xrec, xc = self.get_input(batch, self.first_stage_key,
|
|
1212
|
+
return_first_stage_outputs=True,
|
|
1213
|
+
force_c_encode=True,
|
|
1214
|
+
return_original_cond=True,
|
|
1215
|
+
bs=N)
|
|
1216
|
+
N = min(x.shape[0], N)
|
|
1217
|
+
n_row = min(x.shape[0], n_row)
|
|
1218
|
+
log["inputs"] = x
|
|
1219
|
+
log["reconstruction"] = xrec
|
|
1220
|
+
if self.model.conditioning_key is not None:
|
|
1221
|
+
if hasattr(self.cond_stage_model, "decode"):
|
|
1222
|
+
xc = self.cond_stage_model.decode(c)
|
|
1223
|
+
log["conditioning"] = xc
|
|
1224
|
+
elif self.cond_stage_key in ["caption", "txt"]:
|
|
1225
|
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch[self.cond_stage_key], size=x.shape[2] // 25)
|
|
1226
|
+
log["conditioning"] = xc
|
|
1227
|
+
elif self.cond_stage_key in ['class_label', "cls"]:
|
|
1228
|
+
try:
|
|
1229
|
+
xc = log_txt_as_img((x.shape[2], x.shape[3]), batch["human_label"], size=x.shape[2] // 25)
|
|
1230
|
+
log['conditioning'] = xc
|
|
1231
|
+
except KeyError:
|
|
1232
|
+
# probably no "human_label" in batch
|
|
1233
|
+
pass
|
|
1234
|
+
elif isimage(xc):
|
|
1235
|
+
log["conditioning"] = xc
|
|
1236
|
+
if ismap(xc):
|
|
1237
|
+
log["original_conditioning"] = self.to_rgb(xc)
|
|
1238
|
+
|
|
1239
|
+
if plot_diffusion_rows:
|
|
1240
|
+
# get diffusion row
|
|
1241
|
+
diffusion_row = list()
|
|
1242
|
+
z_start = z[:n_row]
|
|
1243
|
+
for t in range(self.num_timesteps):
|
|
1244
|
+
if t % self.log_every_t == 0 or t == self.num_timesteps - 1:
|
|
1245
|
+
t = repeat(torch.tensor([t]), '1 -> b', b=n_row)
|
|
1246
|
+
t = t.to(self.device).long()
|
|
1247
|
+
noise = torch.randn_like(z_start)
|
|
1248
|
+
z_noisy = self.q_sample(x_start=z_start, t=t, noise=noise)
|
|
1249
|
+
diffusion_row.append(self.decode_first_stage(z_noisy))
|
|
1250
|
+
|
|
1251
|
+
diffusion_row = torch.stack(diffusion_row) # n_log_step, n_row, C, H, W
|
|
1252
|
+
diffusion_grid = rearrange(diffusion_row, 'n b c h w -> b n c h w')
|
|
1253
|
+
diffusion_grid = rearrange(diffusion_grid, 'b n c h w -> (b n) c h w')
|
|
1254
|
+
diffusion_grid = make_grid(diffusion_grid, nrow=diffusion_row.shape[0])
|
|
1255
|
+
log["diffusion_row"] = diffusion_grid
|
|
1256
|
+
|
|
1257
|
+
if sample:
|
|
1258
|
+
# get denoise row
|
|
1259
|
+
with ema_scope("Sampling"):
|
|
1260
|
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
|
1261
|
+
ddim_steps=ddim_steps, eta=ddim_eta)
|
|
1262
|
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True)
|
|
1263
|
+
x_samples = self.decode_first_stage(samples)
|
|
1264
|
+
log["samples"] = x_samples
|
|
1265
|
+
if plot_denoise_rows:
|
|
1266
|
+
denoise_grid = self._get_denoise_row_from_list(z_denoise_row)
|
|
1267
|
+
log["denoise_row"] = denoise_grid
|
|
1268
|
+
|
|
1269
|
+
if quantize_denoised and not isinstance(self.first_stage_model, AutoencoderKL) and not isinstance(
|
|
1270
|
+
self.first_stage_model, IdentityFirstStage):
|
|
1271
|
+
# also display when quantizing x0 while sampling
|
|
1272
|
+
with ema_scope("Plotting Quantized Denoised"):
|
|
1273
|
+
samples, z_denoise_row = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
|
1274
|
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
|
1275
|
+
quantize_denoised=True)
|
|
1276
|
+
# samples, z_denoise_row = self.sample(cond=c, batch_size=N, return_intermediates=True,
|
|
1277
|
+
# quantize_denoised=True)
|
|
1278
|
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
|
1279
|
+
log["samples_x0_quantized"] = x_samples
|
|
1280
|
+
|
|
1281
|
+
if unconditional_guidance_scale > 1.0:
|
|
1282
|
+
uc = self.get_unconditional_conditioning(N, unconditional_guidance_label)
|
|
1283
|
+
if self.model.conditioning_key == "crossattn-adm":
|
|
1284
|
+
uc = {"c_crossattn": [uc], "c_adm": c["c_adm"]}
|
|
1285
|
+
with ema_scope("Sampling with classifier-free guidance"):
|
|
1286
|
+
samples_cfg, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim,
|
|
1287
|
+
ddim_steps=ddim_steps, eta=ddim_eta,
|
|
1288
|
+
unconditional_guidance_scale=unconditional_guidance_scale,
|
|
1289
|
+
unconditional_conditioning=uc,
|
|
1290
|
+
)
|
|
1291
|
+
x_samples_cfg = self.decode_first_stage(samples_cfg)
|
|
1292
|
+
log[f"samples_cfg_scale_{unconditional_guidance_scale:.2f}"] = x_samples_cfg
|
|
1293
|
+
|
|
1294
|
+
if inpaint:
|
|
1295
|
+
# make a simple center square
|
|
1296
|
+
b, h, w = z.shape[0], z.shape[2], z.shape[3]
|
|
1297
|
+
mask = torch.ones(N, h, w).to(self.device)
|
|
1298
|
+
# zeros will be filled in
|
|
1299
|
+
mask[:, h // 4:3 * h // 4, w // 4:3 * w // 4] = 0.
|
|
1300
|
+
mask = mask[:, None, ...]
|
|
1301
|
+
with ema_scope("Plotting Inpaint"):
|
|
1302
|
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
|
|
1303
|
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
|
1304
|
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
|
1305
|
+
log["samples_inpainting"] = x_samples
|
|
1306
|
+
log["mask"] = mask
|
|
1307
|
+
|
|
1308
|
+
# outpaint
|
|
1309
|
+
mask = 1. - mask
|
|
1310
|
+
with ema_scope("Plotting Outpaint"):
|
|
1311
|
+
samples, _ = self.sample_log(cond=c, batch_size=N, ddim=use_ddim, eta=ddim_eta,
|
|
1312
|
+
ddim_steps=ddim_steps, x0=z[:N], mask=mask)
|
|
1313
|
+
x_samples = self.decode_first_stage(samples.to(self.device))
|
|
1314
|
+
log["samples_outpainting"] = x_samples
|
|
1315
|
+
|
|
1316
|
+
if plot_progressive_rows:
|
|
1317
|
+
with ema_scope("Plotting Progressives"):
|
|
1318
|
+
img, progressives = self.progressive_denoising(c,
|
|
1319
|
+
shape=(self.channels, self.image_size, self.image_size),
|
|
1320
|
+
batch_size=N)
|
|
1321
|
+
prog_row = self._get_denoise_row_from_list(progressives, desc="Progressive Generation")
|
|
1322
|
+
log["progressive_row"] = prog_row
|
|
1323
|
+
|
|
1324
|
+
if return_keys:
|
|
1325
|
+
if np.intersect1d(list(log.keys()), return_keys).shape[0] == 0:
|
|
1326
|
+
return log
|
|
1327
|
+
else:
|
|
1328
|
+
return {key: log[key] for key in return_keys}
|
|
1329
|
+
return log
|
|
1330
|
+
|
|
1331
|
+
def configure_optimizers(self):
|
|
1332
|
+
lr = self.learning_rate
|
|
1333
|
+
params = list(self.model.parameters())
|
|
1334
|
+
if self.cond_stage_trainable:
|
|
1335
|
+
print(f"{self.__class__.__name__}: Also optimizing conditioner params!")
|
|
1336
|
+
params = params + list(self.cond_stage_model.parameters())
|
|
1337
|
+
if self.learn_logvar:
|
|
1338
|
+
print('Diffusion model optimizing logvar')
|
|
1339
|
+
params.append(self.logvar)
|
|
1340
|
+
opt = torch.optim.AdamW(params, lr=lr)
|
|
1341
|
+
if self.use_scheduler:
|
|
1342
|
+
assert 'target' in self.scheduler_config
|
|
1343
|
+
scheduler = instantiate_from_config(self.scheduler_config)
|
|
1344
|
+
|
|
1345
|
+
print("Setting up LambdaLR scheduler...")
|
|
1346
|
+
scheduler = [
|
|
1347
|
+
{
|
|
1348
|
+
'scheduler': LambdaLR(opt, lr_lambda=scheduler.schedule),
|
|
1349
|
+
'interval': 'step',
|
|
1350
|
+
'frequency': 1
|
|
1351
|
+
}]
|
|
1352
|
+
return [opt], scheduler
|
|
1353
|
+
return opt
|
|
1354
|
+
|
|
1355
|
+
@torch.no_grad()
|
|
1356
|
+
def to_rgb(self, x):
|
|
1357
|
+
x = x.float()
|
|
1358
|
+
if not hasattr(self, "colorize"):
|
|
1359
|
+
self.colorize = torch.randn(3, x.shape[1], 1, 1).to(x)
|
|
1360
|
+
x = nn.functional.conv2d(x, weight=self.colorize)
|
|
1361
|
+
x = 2. * (x - x.min()) / (x.max() - x.min()) - 1.
|
|
1362
|
+
return x
|
|
1363
|
+
|
|
1364
|
+
|
|
1365
|
+
class DiffusionWrapper(pl.LightningModule):
|
|
1366
|
+
def __init__(self, diff_model_config, conditioning_key):
|
|
1367
|
+
super().__init__()
|
|
1368
|
+
self.diffusion_model = instantiate_from_config(diff_model_config)
|
|
1369
|
+
self.conditioning_key = conditioning_key
|
|
1370
|
+
assert self.conditioning_key in [None, 'concat', 'crossattn', 'hybrid', 'adm', 'hybrid-adm', 'crossattn-adm']
|
|
1371
|
+
|
|
1372
|
+
def forward(self, x,mask, t, c_concat: list = None, c_crossattn: list = None, c_adm=None, **kwargs):
|
|
1373
|
+
if self.conditioning_key is None:
|
|
1374
|
+
out = self.diffusion_model(x, t, **kwargs)
|
|
1375
|
+
elif self.conditioning_key == 'concat':
|
|
1376
|
+
xc = torch.cat([x] + c_concat, dim=1)
|
|
1377
|
+
out = self.diffusion_model(xc, t, **kwargs)
|
|
1378
|
+
elif self.conditioning_key == 'crossattn':
|
|
1379
|
+
cc = torch.cat(c_crossattn, 1)
|
|
1380
|
+
out = self.diffusion_model(x, mask,t, context=cc, **kwargs)
|
|
1381
|
+
elif self.conditioning_key == 'hybrid':
|
|
1382
|
+
xc = torch.cat([x] + c_concat, dim=1)
|
|
1383
|
+
cc = torch.cat(c_crossattn, 1)
|
|
1384
|
+
out = self.diffusion_model(xc, t, context=cc, **kwargs)
|
|
1385
|
+
elif self.conditioning_key == 'hybrid-adm':
|
|
1386
|
+
assert c_adm is not None
|
|
1387
|
+
xc = torch.cat([x] + c_concat, dim=1)
|
|
1388
|
+
cc = torch.cat(c_crossattn, 1)
|
|
1389
|
+
out = self.diffusion_model(xc, t, context=cc, y=c_adm, **kwargs)
|
|
1390
|
+
elif self.conditioning_key == 'crossattn-adm':
|
|
1391
|
+
assert c_adm is not None
|
|
1392
|
+
cc = torch.cat(c_crossattn, 1)
|
|
1393
|
+
out = self.diffusion_model(x, t, context=cc, y=c_adm, **kwargs)
|
|
1394
|
+
elif self.conditioning_key == 'adm':
|
|
1395
|
+
cc = c_crossattn[0]
|
|
1396
|
+
out = self.diffusion_model(x, t, y=cc, **kwargs)
|
|
1397
|
+
else:
|
|
1398
|
+
raise NotImplementedError()
|
|
1399
|
+
|
|
1400
|
+
return out
|