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,267 @@
|
|
|
1
|
+
# adopted from
|
|
2
|
+
# https://github.com/openai/improved-diffusion/blob/main/improved_diffusion/gaussian_diffusion.py
|
|
3
|
+
# and
|
|
4
|
+
# https://github.com/lucidrains/denoising-diffusion-pytorch/blob/7706bdfc6f527f58d33f84b7b522e61e6e3164b3/denoising_diffusion_pytorch/denoising_diffusion_pytorch.py
|
|
5
|
+
# and
|
|
6
|
+
# https://github.com/openai/guided-diffusion/blob/0ba878e517b276c45d1195eb29f6f5f72659a05b/guided_diffusion/nn.py
|
|
7
|
+
#
|
|
8
|
+
# thanks!
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
import os
|
|
12
|
+
import math
|
|
13
|
+
import torch
|
|
14
|
+
import torch.nn as nn
|
|
15
|
+
import numpy as np
|
|
16
|
+
from einops import repeat
|
|
17
|
+
|
|
18
|
+
from ldm.util import instantiate_from_config
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def make_beta_schedule(schedule, n_timestep, linear_start=1e-4, linear_end=2e-2, cosine_s=8e-3):
|
|
22
|
+
if schedule == "linear":
|
|
23
|
+
betas = (
|
|
24
|
+
torch.linspace(linear_start ** 0.5, linear_end ** 0.5, n_timestep, dtype=torch.float64) ** 2
|
|
25
|
+
)
|
|
26
|
+
|
|
27
|
+
elif schedule == "cosine":
|
|
28
|
+
timesteps = (
|
|
29
|
+
torch.arange(n_timestep + 1, dtype=torch.float64) / n_timestep + cosine_s
|
|
30
|
+
)
|
|
31
|
+
alphas = timesteps / (1 + cosine_s) * np.pi / 2
|
|
32
|
+
alphas = torch.cos(alphas).pow(2)
|
|
33
|
+
alphas = alphas / alphas[0]
|
|
34
|
+
betas = 1 - alphas[1:] / alphas[:-1]
|
|
35
|
+
betas = np.clip(betas, a_min=0, a_max=0.999)
|
|
36
|
+
|
|
37
|
+
elif schedule == "sqrt_linear":
|
|
38
|
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64)
|
|
39
|
+
elif schedule == "sqrt":
|
|
40
|
+
betas = torch.linspace(linear_start, linear_end, n_timestep, dtype=torch.float64) ** 0.5
|
|
41
|
+
else:
|
|
42
|
+
raise ValueError(f"schedule '{schedule}' unknown.")
|
|
43
|
+
return betas.numpy()
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def make_ddim_timesteps(ddim_discr_method, num_ddim_timesteps, num_ddpm_timesteps, verbose=True):
|
|
47
|
+
if ddim_discr_method == 'uniform':
|
|
48
|
+
c = num_ddpm_timesteps // num_ddim_timesteps
|
|
49
|
+
ddim_timesteps = np.asarray(list(range(0, num_ddpm_timesteps, c)))
|
|
50
|
+
elif ddim_discr_method == 'quad':
|
|
51
|
+
ddim_timesteps = ((np.linspace(0, np.sqrt(num_ddpm_timesteps * .8), num_ddim_timesteps)) ** 2).astype(int)
|
|
52
|
+
else:
|
|
53
|
+
raise NotImplementedError(f'There is no ddim discretization method called "{ddim_discr_method}"')
|
|
54
|
+
|
|
55
|
+
# assert ddim_timesteps.shape[0] == num_ddim_timesteps
|
|
56
|
+
# add one to get the final alpha values right (the ones from first scale to data during sampling)
|
|
57
|
+
steps_out = ddim_timesteps + 1
|
|
58
|
+
if verbose:
|
|
59
|
+
print(f'Selected timesteps for ddim sampler: {steps_out}')
|
|
60
|
+
return steps_out
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def make_ddim_sampling_parameters(alphacums, ddim_timesteps, eta, verbose=True):
|
|
64
|
+
# select alphas for computing the variance schedule
|
|
65
|
+
alphas = alphacums[ddim_timesteps]
|
|
66
|
+
alphas_prev = np.asarray([alphacums[0]] + alphacums[ddim_timesteps[:-1]].tolist())
|
|
67
|
+
|
|
68
|
+
# according the the formula provided in https://arxiv.org/abs/2010.02502
|
|
69
|
+
sigmas = eta * np.sqrt((1 - alphas_prev) / (1 - alphas) * (1 - alphas / alphas_prev))
|
|
70
|
+
if verbose:
|
|
71
|
+
print(f'Selected alphas for ddim sampler: a_t: {alphas}; a_(t-1): {alphas_prev}')
|
|
72
|
+
print(f'For the chosen value of eta, which is {eta}, '
|
|
73
|
+
f'this results in the following sigma_t schedule for ddim sampler {sigmas}')
|
|
74
|
+
return sigmas, alphas, alphas_prev
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def betas_for_alpha_bar(num_diffusion_timesteps, alpha_bar, max_beta=0.999):
|
|
78
|
+
"""
|
|
79
|
+
Create a beta schedule that discretizes the given alpha_t_bar function,
|
|
80
|
+
which defines the cumulative product of (1-beta) over time from t = [0,1].
|
|
81
|
+
:param num_diffusion_timesteps: the number of betas to produce.
|
|
82
|
+
:param alpha_bar: a lambda that takes an argument t from 0 to 1 and
|
|
83
|
+
produces the cumulative product of (1-beta) up to that
|
|
84
|
+
part of the diffusion process.
|
|
85
|
+
:param max_beta: the maximum beta to use; use values lower than 1 to
|
|
86
|
+
prevent singularities.
|
|
87
|
+
"""
|
|
88
|
+
betas = []
|
|
89
|
+
for i in range(num_diffusion_timesteps):
|
|
90
|
+
t1 = i / num_diffusion_timesteps
|
|
91
|
+
t2 = (i + 1) / num_diffusion_timesteps
|
|
92
|
+
betas.append(min(1 - alpha_bar(t2) / alpha_bar(t1), max_beta))
|
|
93
|
+
return np.array(betas)
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def extract_into_tensor(a, t, x_shape):
|
|
97
|
+
b, *_ = t.shape
|
|
98
|
+
out = a.gather(-1, t)
|
|
99
|
+
return out.reshape(b, *((1,) * (len(x_shape) - 1)))
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
def checkpoint(func, inputs, params, flag):
|
|
103
|
+
"""
|
|
104
|
+
Evaluate a function without caching intermediate activations, allowing for
|
|
105
|
+
reduced memory at the expense of extra compute in the backward pass.
|
|
106
|
+
:param func: the function to evaluate.
|
|
107
|
+
:param inputs: the argument sequence to pass to `func`.
|
|
108
|
+
:param params: a sequence of parameters `func` depends on but does not
|
|
109
|
+
explicitly take as arguments.
|
|
110
|
+
:param flag: if False, disable gradient checkpointing.
|
|
111
|
+
"""
|
|
112
|
+
if flag:
|
|
113
|
+
args = tuple(inputs) + tuple(params)
|
|
114
|
+
return CheckpointFunction.apply(func, len(inputs), *args)
|
|
115
|
+
else:
|
|
116
|
+
return func(*inputs)
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class CheckpointFunction(torch.autograd.Function):
|
|
120
|
+
@staticmethod
|
|
121
|
+
def forward(ctx, run_function, length, *args):
|
|
122
|
+
ctx.run_function = run_function
|
|
123
|
+
ctx.input_tensors = list(args[:length])
|
|
124
|
+
ctx.input_params = list(args[length:])
|
|
125
|
+
|
|
126
|
+
with torch.no_grad():
|
|
127
|
+
output_tensors = ctx.run_function(*ctx.input_tensors)
|
|
128
|
+
return output_tensors
|
|
129
|
+
|
|
130
|
+
@staticmethod
|
|
131
|
+
def backward(ctx, *output_grads):
|
|
132
|
+
ctx.input_tensors = [x.detach().requires_grad_(True) for x in ctx.input_tensors]
|
|
133
|
+
with torch.enable_grad():
|
|
134
|
+
# Fixes a bug where the first op in run_function modifies the
|
|
135
|
+
# Tensor storage in place, which is not allowed for detach()'d
|
|
136
|
+
# Tensors.
|
|
137
|
+
shallow_copies = [x.view_as(x) for x in ctx.input_tensors]
|
|
138
|
+
output_tensors = ctx.run_function(*shallow_copies)
|
|
139
|
+
input_grads = torch.autograd.grad(
|
|
140
|
+
output_tensors,
|
|
141
|
+
ctx.input_tensors + ctx.input_params,
|
|
142
|
+
output_grads,
|
|
143
|
+
allow_unused=True,
|
|
144
|
+
)
|
|
145
|
+
del ctx.input_tensors
|
|
146
|
+
del ctx.input_params
|
|
147
|
+
del output_tensors
|
|
148
|
+
return (None, None) + input_grads
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def timestep_embedding(timesteps, dim, max_period=10000, repeat_only=False):
|
|
152
|
+
"""
|
|
153
|
+
Create sinusoidal timestep embeddings.
|
|
154
|
+
:param timesteps: a 1-D Tensor of N indices, one per batch element.
|
|
155
|
+
These may be fractional.
|
|
156
|
+
:param dim: the dimension of the output.
|
|
157
|
+
:param max_period: controls the minimum frequency of the embeddings.
|
|
158
|
+
:return: an [N x dim] Tensor of positional embeddings.
|
|
159
|
+
"""
|
|
160
|
+
if not repeat_only:
|
|
161
|
+
half = dim // 2
|
|
162
|
+
freqs = torch.exp(
|
|
163
|
+
-math.log(max_period) * torch.arange(start=0, end=half, dtype=torch.float32) / half
|
|
164
|
+
).to(device=timesteps.device)
|
|
165
|
+
args = timesteps[:, None].float() * freqs[None]
|
|
166
|
+
embedding = torch.cat([torch.cos(args), torch.sin(args)], dim=-1)
|
|
167
|
+
if dim % 2:
|
|
168
|
+
embedding = torch.cat([embedding, torch.zeros_like(embedding[:, :1])], dim=-1)
|
|
169
|
+
else:
|
|
170
|
+
embedding = repeat(timesteps, 'b -> b d', d=dim)
|
|
171
|
+
return embedding
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def zero_module(module):
|
|
175
|
+
"""
|
|
176
|
+
Zero out the parameters of a module and return it.
|
|
177
|
+
"""
|
|
178
|
+
for p in module.parameters():
|
|
179
|
+
p.detach().zero_()
|
|
180
|
+
return module
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def scale_module(module, scale):
|
|
184
|
+
"""
|
|
185
|
+
Scale the parameters of a module and return it.
|
|
186
|
+
"""
|
|
187
|
+
for p in module.parameters():
|
|
188
|
+
p.detach().mul_(scale)
|
|
189
|
+
return module
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def mean_flat(tensor):
|
|
193
|
+
"""
|
|
194
|
+
Take the mean over all non-batch dimensions.
|
|
195
|
+
"""
|
|
196
|
+
return tensor.mean(dim=list(range(1, len(tensor.shape))))
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def normalization(channels):
|
|
200
|
+
"""
|
|
201
|
+
Make a standard normalization layer.
|
|
202
|
+
:param channels: number of input channels.
|
|
203
|
+
:return: an nn.Module for normalization.
|
|
204
|
+
"""
|
|
205
|
+
return GroupNorm32(32, channels)
|
|
206
|
+
|
|
207
|
+
|
|
208
|
+
# PyTorch 1.7 has SiLU, but we support PyTorch 1.5.
|
|
209
|
+
class SiLU(nn.Module):
|
|
210
|
+
def forward(self, x):
|
|
211
|
+
return x * torch.sigmoid(x)
|
|
212
|
+
|
|
213
|
+
|
|
214
|
+
class GroupNorm32(nn.GroupNorm):
|
|
215
|
+
def forward(self, x):
|
|
216
|
+
return super().forward(x.float()).type(x.dtype)
|
|
217
|
+
|
|
218
|
+
def conv_nd(dims, *args, **kwargs):
|
|
219
|
+
"""
|
|
220
|
+
Create a 1D, 2D, or 3D convolution module.
|
|
221
|
+
"""
|
|
222
|
+
if dims == 1:
|
|
223
|
+
return nn.Conv1d(*args, **kwargs)
|
|
224
|
+
elif dims == 2:
|
|
225
|
+
return nn.Conv2d(*args, **kwargs)
|
|
226
|
+
elif dims == 3:
|
|
227
|
+
return nn.Conv3d(*args, **kwargs)
|
|
228
|
+
raise ValueError(f"unsupported dimensions: {dims}")
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def linear(*args, **kwargs):
|
|
232
|
+
"""
|
|
233
|
+
Create a linear module.
|
|
234
|
+
"""
|
|
235
|
+
return nn.Linear(*args, **kwargs)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def avg_pool_nd(dims, *args, **kwargs):
|
|
239
|
+
"""
|
|
240
|
+
Create a 1D, 2D, or 3D average pooling module.
|
|
241
|
+
"""
|
|
242
|
+
if dims == 1:
|
|
243
|
+
return nn.AvgPool1d(*args, **kwargs)
|
|
244
|
+
elif dims == 2:
|
|
245
|
+
return nn.AvgPool2d(*args, **kwargs)
|
|
246
|
+
elif dims == 3:
|
|
247
|
+
return nn.AvgPool3d(*args, **kwargs)
|
|
248
|
+
raise ValueError(f"unsupported dimensions: {dims}")
|
|
249
|
+
|
|
250
|
+
|
|
251
|
+
class HybridConditioner(nn.Module):
|
|
252
|
+
|
|
253
|
+
def __init__(self, c_concat_config, c_crossattn_config):
|
|
254
|
+
super().__init__()
|
|
255
|
+
self.concat_conditioner = instantiate_from_config(c_concat_config)
|
|
256
|
+
self.crossattn_conditioner = instantiate_from_config(c_crossattn_config)
|
|
257
|
+
|
|
258
|
+
def forward(self, c_concat, c_crossattn):
|
|
259
|
+
c_concat = self.concat_conditioner(c_concat)
|
|
260
|
+
c_crossattn = self.crossattn_conditioner(c_crossattn)
|
|
261
|
+
return {'c_concat': [c_concat], 'c_crossattn': [c_crossattn]}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def noise_like(shape, device, repeat=False):
|
|
265
|
+
repeat_noise = lambda: torch.randn((1, *shape[1:]), device=device).repeat(shape[0], *((1,) * (len(shape) - 1)))
|
|
266
|
+
noise = lambda: torch.randn(shape, device=device)
|
|
267
|
+
return repeat_noise() if repeat else noise()
|
|
File without changes
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import numpy as np
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class AbstractDistribution:
|
|
6
|
+
def sample(self):
|
|
7
|
+
raise NotImplementedError()
|
|
8
|
+
|
|
9
|
+
def mode(self):
|
|
10
|
+
raise NotImplementedError()
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class DiracDistribution(AbstractDistribution):
|
|
14
|
+
def __init__(self, value):
|
|
15
|
+
self.value = value
|
|
16
|
+
|
|
17
|
+
def sample(self):
|
|
18
|
+
return self.value
|
|
19
|
+
|
|
20
|
+
def mode(self):
|
|
21
|
+
return self.value
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class DiagonalGaussianDistribution(object):
|
|
25
|
+
def __init__(self, parameters, deterministic=False):
|
|
26
|
+
self.parameters = parameters
|
|
27
|
+
self.mean, self.logvar = torch.chunk(parameters, 2, dim=1)
|
|
28
|
+
self.logvar = torch.clamp(self.logvar, -30.0, 20.0)
|
|
29
|
+
self.deterministic = deterministic
|
|
30
|
+
self.std = torch.exp(0.5 * self.logvar)
|
|
31
|
+
self.var = torch.exp(self.logvar)
|
|
32
|
+
if self.deterministic:
|
|
33
|
+
self.var = self.std = torch.zeros_like(self.mean).to(device=self.parameters.device)
|
|
34
|
+
|
|
35
|
+
def sample(self):
|
|
36
|
+
x = self.mean + self.std * torch.randn(self.mean.shape).to(device=self.parameters.device)
|
|
37
|
+
return x
|
|
38
|
+
|
|
39
|
+
def kl(self, other=None):
|
|
40
|
+
if self.deterministic:
|
|
41
|
+
return torch.Tensor([0.])
|
|
42
|
+
else:
|
|
43
|
+
if other is None:
|
|
44
|
+
return 0.5 * torch.sum(torch.pow(self.mean, 2)
|
|
45
|
+
+ self.var - 1.0 - self.logvar,
|
|
46
|
+
dim=[1, 2, 3])
|
|
47
|
+
else:
|
|
48
|
+
return 0.5 * torch.sum(
|
|
49
|
+
torch.pow(self.mean - other.mean, 2) / other.var
|
|
50
|
+
+ self.var / other.var - 1.0 - self.logvar + other.logvar,
|
|
51
|
+
dim=[1, 2, 3])
|
|
52
|
+
|
|
53
|
+
def nll(self, sample, dims=[1,2,3]):
|
|
54
|
+
if self.deterministic:
|
|
55
|
+
return torch.Tensor([0.])
|
|
56
|
+
logtwopi = np.log(2.0 * np.pi)
|
|
57
|
+
return 0.5 * torch.sum(
|
|
58
|
+
logtwopi + self.logvar + torch.pow(sample - self.mean, 2) / self.var,
|
|
59
|
+
dim=dims)
|
|
60
|
+
|
|
61
|
+
def mode(self):
|
|
62
|
+
return self.mean
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def normal_kl(mean1, logvar1, mean2, logvar2):
|
|
66
|
+
"""
|
|
67
|
+
source: https://github.com/openai/guided-diffusion/blob/27c20a8fab9cb472df5d6bdd6c8d11c8f430b924/guided_diffusion/losses.py#L12
|
|
68
|
+
Compute the KL divergence between two gaussians.
|
|
69
|
+
Shapes are automatically broadcasted, so batches can be compared to
|
|
70
|
+
scalars, among other use cases.
|
|
71
|
+
"""
|
|
72
|
+
tensor = None
|
|
73
|
+
for obj in (mean1, logvar1, mean2, logvar2):
|
|
74
|
+
if isinstance(obj, torch.Tensor):
|
|
75
|
+
tensor = obj
|
|
76
|
+
break
|
|
77
|
+
assert tensor is not None, "at least one argument must be a Tensor"
|
|
78
|
+
|
|
79
|
+
# Force variances to be Tensors. Broadcasting helps convert scalars to
|
|
80
|
+
# Tensors, but it does not work for torch.exp().
|
|
81
|
+
logvar1, logvar2 = [
|
|
82
|
+
x if isinstance(x, torch.Tensor) else torch.tensor(x).to(tensor)
|
|
83
|
+
for x in (logvar1, logvar2)
|
|
84
|
+
]
|
|
85
|
+
|
|
86
|
+
return 0.5 * (
|
|
87
|
+
-1.0
|
|
88
|
+
+ logvar2
|
|
89
|
+
- logvar1
|
|
90
|
+
+ torch.exp(logvar1 - logvar2)
|
|
91
|
+
+ ((mean1 - mean2) ** 2) * torch.exp(-logvar2)
|
|
92
|
+
)
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
from torch import nn
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class LitEma(nn.Module):
|
|
6
|
+
def __init__(self, model, decay=0.9999, use_num_upates=True):
|
|
7
|
+
super().__init__()
|
|
8
|
+
if decay < 0.0 or decay > 1.0:
|
|
9
|
+
raise ValueError('Decay must be between 0 and 1')
|
|
10
|
+
|
|
11
|
+
self.m_name2s_name = {}
|
|
12
|
+
self.register_buffer('decay', torch.tensor(decay, dtype=torch.float32))
|
|
13
|
+
self.register_buffer('num_updates', torch.tensor(0,dtype=torch.int) if use_num_upates
|
|
14
|
+
else torch.tensor(-1,dtype=torch.int))
|
|
15
|
+
|
|
16
|
+
for name, p in model.named_parameters():
|
|
17
|
+
if p.requires_grad:
|
|
18
|
+
#remove as '.'-character is not allowed in buffers
|
|
19
|
+
s_name = name.replace('.','')
|
|
20
|
+
self.m_name2s_name.update({name:s_name})
|
|
21
|
+
self.register_buffer(s_name,p.clone().detach().data)
|
|
22
|
+
|
|
23
|
+
self.collected_params = []
|
|
24
|
+
|
|
25
|
+
def forward(self,model):
|
|
26
|
+
decay = self.decay
|
|
27
|
+
|
|
28
|
+
if self.num_updates >= 0:
|
|
29
|
+
self.num_updates += 1
|
|
30
|
+
decay = min(self.decay,(1 + self.num_updates) / (10 + self.num_updates))
|
|
31
|
+
|
|
32
|
+
one_minus_decay = 1.0 - decay
|
|
33
|
+
|
|
34
|
+
with torch.no_grad():
|
|
35
|
+
m_param = dict(model.named_parameters())
|
|
36
|
+
shadow_params = dict(self.named_buffers())
|
|
37
|
+
|
|
38
|
+
for key in m_param:
|
|
39
|
+
if m_param[key].requires_grad:
|
|
40
|
+
sname = self.m_name2s_name[key]
|
|
41
|
+
shadow_params[sname] = shadow_params[sname].type_as(m_param[key])
|
|
42
|
+
shadow_params[sname].sub_(one_minus_decay * (shadow_params[sname] - m_param[key]))
|
|
43
|
+
else:
|
|
44
|
+
assert not key in self.m_name2s_name
|
|
45
|
+
|
|
46
|
+
def copy_to(self, model):
|
|
47
|
+
m_param = dict(model.named_parameters())
|
|
48
|
+
shadow_params = dict(self.named_buffers())
|
|
49
|
+
for key in m_param:
|
|
50
|
+
if m_param[key].requires_grad:
|
|
51
|
+
m_param[key].data.copy_(shadow_params[self.m_name2s_name[key]].data)
|
|
52
|
+
else:
|
|
53
|
+
assert not key in self.m_name2s_name
|
|
54
|
+
|
|
55
|
+
def store(self, parameters):
|
|
56
|
+
"""
|
|
57
|
+
Save the current parameters for restoring later.
|
|
58
|
+
Args:
|
|
59
|
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
|
60
|
+
temporarily stored.
|
|
61
|
+
"""
|
|
62
|
+
self.collected_params = [param.clone() for param in parameters]
|
|
63
|
+
|
|
64
|
+
def restore(self, parameters):
|
|
65
|
+
"""
|
|
66
|
+
Restore the parameters stored with the `store` method.
|
|
67
|
+
Useful to validate the model with EMA parameters without affecting the
|
|
68
|
+
original optimization process. Store the parameters before the
|
|
69
|
+
`copy_to` method. After validation (or model saving), use this to
|
|
70
|
+
restore the former parameters.
|
|
71
|
+
Args:
|
|
72
|
+
parameters: Iterable of `torch.nn.Parameter`; the parameters to be
|
|
73
|
+
updated with the stored parameters.
|
|
74
|
+
"""
|
|
75
|
+
for c_param, param in zip(self.collected_params, parameters):
|
|
76
|
+
param.data.copy_(c_param.data)
|
|
File without changes
|
|
@@ -0,0 +1,190 @@
|
|
|
1
|
+
import torch
|
|
2
|
+
import torch.nn as nn
|
|
3
|
+
from functools import partial
|
|
4
|
+
import clip
|
|
5
|
+
from einops import rearrange, repeat
|
|
6
|
+
from transformers import CLIPTokenizer, CLIPTextModel,CLIPVisionModel,CLIPModel
|
|
7
|
+
import os,sys
|
|
8
|
+
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))))
|
|
9
|
+
from libcom.os_insert.source.ldm.modules.x_transformer import Encoder, TransformerWrapper
|
|
10
|
+
from libcom.os_insert.source.ldm.modules.encoders.xf import LayerNorm, Transformer
|
|
11
|
+
import math
|
|
12
|
+
|
|
13
|
+
class AbstractEncoder(nn.Module):
|
|
14
|
+
def __init__(self):
|
|
15
|
+
super().__init__()
|
|
16
|
+
|
|
17
|
+
def encode(self, *args, **kwargs):
|
|
18
|
+
raise NotImplementedError
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class ClassEmbedder(nn.Module):
|
|
23
|
+
def __init__(self, embed_dim, n_classes=1000, key='class'):
|
|
24
|
+
super().__init__()
|
|
25
|
+
self.key = key
|
|
26
|
+
self.embedding = nn.Embedding(n_classes, embed_dim)
|
|
27
|
+
|
|
28
|
+
def forward(self, batch, key=None):
|
|
29
|
+
if key is None:
|
|
30
|
+
key = self.key
|
|
31
|
+
# this is for use in crossattn
|
|
32
|
+
c = batch[key][:, None]
|
|
33
|
+
c = self.embedding(c)
|
|
34
|
+
return c
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class TransformerEmbedder(AbstractEncoder):
|
|
38
|
+
"""Some transformer encoder layers"""
|
|
39
|
+
def __init__(self, n_embed, n_layer, vocab_size, max_seq_len=77, device="cuda"):
|
|
40
|
+
super().__init__()
|
|
41
|
+
self.device = device
|
|
42
|
+
self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len,
|
|
43
|
+
attn_layers=Encoder(dim=n_embed, depth=n_layer))
|
|
44
|
+
|
|
45
|
+
def forward(self, tokens):
|
|
46
|
+
tokens = tokens.to(self.device) # meh
|
|
47
|
+
z = self.transformer(tokens, return_embeddings=True)
|
|
48
|
+
return z
|
|
49
|
+
|
|
50
|
+
def encode(self, x):
|
|
51
|
+
return self(x)
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
class BERTTokenizer(AbstractEncoder):
|
|
55
|
+
""" Uses a pretrained BERT tokenizer by huggingface. Vocab size: 30522 (?)"""
|
|
56
|
+
def __init__(self, device="cuda", vq_interface=True, max_length=77):
|
|
57
|
+
super().__init__()
|
|
58
|
+
from transformers import BertTokenizerFast # TODO: add to reuquirements
|
|
59
|
+
self.tokenizer = BertTokenizerFast.from_pretrained("bert-base-uncased")
|
|
60
|
+
self.device = device
|
|
61
|
+
self.vq_interface = vq_interface
|
|
62
|
+
self.max_length = max_length
|
|
63
|
+
|
|
64
|
+
def forward(self, text):
|
|
65
|
+
batch_encoding = self.tokenizer(text, truncation=True, max_length=self.max_length, return_length=True,
|
|
66
|
+
return_overflowing_tokens=False, padding="max_length", return_tensors="pt")
|
|
67
|
+
tokens = batch_encoding["input_ids"].to(self.device)
|
|
68
|
+
return tokens
|
|
69
|
+
|
|
70
|
+
@torch.no_grad()
|
|
71
|
+
def encode(self, text):
|
|
72
|
+
tokens = self(text)
|
|
73
|
+
if not self.vq_interface:
|
|
74
|
+
return tokens
|
|
75
|
+
return None, None, [None, None, tokens]
|
|
76
|
+
|
|
77
|
+
def decode(self, text):
|
|
78
|
+
return text
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
class BERTEmbedder(AbstractEncoder):
|
|
82
|
+
"""Uses the BERT tokenizr model and add some transformer encoder layers"""
|
|
83
|
+
def __init__(self, n_embed, n_layer, vocab_size=30522, max_seq_len=77,
|
|
84
|
+
device="cuda",use_tokenizer=True, embedding_dropout=0.0):
|
|
85
|
+
super().__init__()
|
|
86
|
+
self.use_tknz_fn = use_tokenizer
|
|
87
|
+
if self.use_tknz_fn:
|
|
88
|
+
self.tknz_fn = BERTTokenizer(vq_interface=False, max_length=max_seq_len)
|
|
89
|
+
self.device = device
|
|
90
|
+
self.transformer = TransformerWrapper(num_tokens=vocab_size, max_seq_len=max_seq_len,
|
|
91
|
+
attn_layers=Encoder(dim=n_embed, depth=n_layer),
|
|
92
|
+
emb_dropout=embedding_dropout)
|
|
93
|
+
|
|
94
|
+
def forward(self, text):
|
|
95
|
+
if self.use_tknz_fn:
|
|
96
|
+
tokens = self.tknz_fn(text)#.to(self.device)
|
|
97
|
+
else:
|
|
98
|
+
tokens = text
|
|
99
|
+
z = self.transformer(tokens, return_embeddings=True)
|
|
100
|
+
return z
|
|
101
|
+
|
|
102
|
+
def encode(self, text):
|
|
103
|
+
# output of length 77
|
|
104
|
+
return self(text)
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class SpatialRescaler(nn.Module):
|
|
108
|
+
def __init__(self,
|
|
109
|
+
n_stages=1,
|
|
110
|
+
method='bilinear',
|
|
111
|
+
multiplier=0.5,
|
|
112
|
+
in_channels=3,
|
|
113
|
+
out_channels=None,
|
|
114
|
+
bias=False):
|
|
115
|
+
super().__init__()
|
|
116
|
+
self.n_stages = n_stages
|
|
117
|
+
assert self.n_stages >= 0
|
|
118
|
+
assert method in ['nearest','linear','bilinear','trilinear','bicubic','area']
|
|
119
|
+
self.multiplier = multiplier
|
|
120
|
+
self.interpolator = partial(torch.nn.functional.interpolate, mode=method)
|
|
121
|
+
self.remap_output = out_channels is not None
|
|
122
|
+
if self.remap_output:
|
|
123
|
+
print(f'Spatial Rescaler mapping from {in_channels} to {out_channels} channels after resizing.')
|
|
124
|
+
self.channel_mapper = nn.Conv2d(in_channels,out_channels,1,bias=bias)
|
|
125
|
+
|
|
126
|
+
def forward(self,x):
|
|
127
|
+
for stage in range(self.n_stages):
|
|
128
|
+
x = self.interpolator(x, scale_factor=self.multiplier)
|
|
129
|
+
|
|
130
|
+
|
|
131
|
+
if self.remap_output:
|
|
132
|
+
x = self.channel_mapper(x)
|
|
133
|
+
return x
|
|
134
|
+
|
|
135
|
+
def encode(self, x):
|
|
136
|
+
return self(x)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class FrozenCLIPImageEmbedder(AbstractEncoder):
|
|
140
|
+
"""Uses the CLIP transformer encoder for text (from Hugging Face)"""
|
|
141
|
+
def __init__(self, version="openai/clip-vit-large-patch14"):
|
|
142
|
+
super().__init__()
|
|
143
|
+
self.transformer = CLIPVisionModel.from_pretrained(version)
|
|
144
|
+
self.final_ln = LayerNorm(1024)
|
|
145
|
+
self.mapper = Transformer(
|
|
146
|
+
1,
|
|
147
|
+
1024,
|
|
148
|
+
5,
|
|
149
|
+
1,
|
|
150
|
+
)
|
|
151
|
+
self.shallow_index = 12
|
|
152
|
+
self.freeze()
|
|
153
|
+
|
|
154
|
+
def freeze(self):
|
|
155
|
+
self.transformer = self.transformer.eval()
|
|
156
|
+
for param in self.parameters():
|
|
157
|
+
param.requires_grad = False
|
|
158
|
+
for param in self.mapper.parameters():
|
|
159
|
+
param.requires_grad = True
|
|
160
|
+
for param in self.final_ln.parameters():
|
|
161
|
+
param.requires_grad = True
|
|
162
|
+
|
|
163
|
+
def forward(self, image):
|
|
164
|
+
outputs = self.transformer(pixel_values=image,
|
|
165
|
+
output_hidden_states=True)
|
|
166
|
+
all_hidden = outputs.hidden_states
|
|
167
|
+
last_hidden = outputs.last_hidden_state # b,257,1024
|
|
168
|
+
global_emb = last_hidden
|
|
169
|
+
gz = self.transformer.vision_model.post_layernorm(global_emb)
|
|
170
|
+
gz = self.mapper(gz)
|
|
171
|
+
z = self.final_ln(gz) # b,257,1024
|
|
172
|
+
# get the outputs from shallow layer
|
|
173
|
+
# lz = all_hidden[self.shallow_index][:,1:] # b,256,1024
|
|
174
|
+
# z = torch.cat([gz, lz], dim=1)
|
|
175
|
+
return z
|
|
176
|
+
|
|
177
|
+
def encode(self, image):
|
|
178
|
+
return self(image)
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
if __name__ == "__main__":
|
|
182
|
+
from ldm.util import count_params
|
|
183
|
+
device = torch.device("cuda:0")
|
|
184
|
+
model = FrozenCLIPImageEmbedder().to(device)
|
|
185
|
+
count_params(model, verbose=True)
|
|
186
|
+
img = torch.randn(2, 3, 224, 224).to(device)
|
|
187
|
+
z = model(img)
|
|
188
|
+
print(z)
|
|
189
|
+
print(z.shape)
|
|
190
|
+
|