hcpdiff 0.9.0__py3-none-any.whl → 2.1__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.
- hcpdiff/__init__.py +4 -4
- hcpdiff/ckpt_manager/__init__.py +4 -5
- hcpdiff/ckpt_manager/ckpt.py +24 -0
- hcpdiff/ckpt_manager/format/__init__.py +4 -0
- hcpdiff/ckpt_manager/format/diffusers.py +59 -0
- hcpdiff/ckpt_manager/format/emb.py +21 -0
- hcpdiff/ckpt_manager/format/lora_webui.py +244 -0
- hcpdiff/ckpt_manager/format/sd_single.py +41 -0
- hcpdiff/ckpt_manager/loader.py +64 -0
- hcpdiff/data/__init__.py +4 -28
- hcpdiff/data/cache/__init__.py +1 -0
- hcpdiff/data/cache/vae.py +102 -0
- hcpdiff/data/dataset.py +20 -0
- hcpdiff/data/handler/__init__.py +3 -0
- hcpdiff/data/handler/controlnet.py +18 -0
- hcpdiff/data/handler/diffusion.py +80 -0
- hcpdiff/data/handler/text.py +111 -0
- hcpdiff/data/source/__init__.py +1 -2
- hcpdiff/data/source/folder_class.py +12 -29
- hcpdiff/data/source/text2img.py +36 -74
- hcpdiff/data/source/text2img_cond.py +9 -15
- hcpdiff/diffusion/__init__.py +0 -0
- hcpdiff/diffusion/noise/__init__.py +2 -0
- hcpdiff/diffusion/noise/pyramid_noise.py +42 -0
- hcpdiff/diffusion/noise/zero_terminal.py +39 -0
- hcpdiff/diffusion/sampler/__init__.py +5 -0
- hcpdiff/diffusion/sampler/base.py +72 -0
- hcpdiff/diffusion/sampler/ddpm.py +20 -0
- hcpdiff/diffusion/sampler/diffusers.py +66 -0
- hcpdiff/diffusion/sampler/edm.py +22 -0
- hcpdiff/diffusion/sampler/sigma_scheduler/__init__.py +3 -0
- hcpdiff/diffusion/sampler/sigma_scheduler/base.py +14 -0
- hcpdiff/diffusion/sampler/sigma_scheduler/ddpm.py +197 -0
- hcpdiff/diffusion/sampler/sigma_scheduler/edm.py +48 -0
- hcpdiff/easy/__init__.py +2 -0
- hcpdiff/easy/cfg/__init__.py +3 -0
- hcpdiff/easy/cfg/sd15_train.py +201 -0
- hcpdiff/easy/cfg/sdxl_train.py +140 -0
- hcpdiff/easy/cfg/t2i.py +177 -0
- hcpdiff/easy/model/__init__.py +2 -0
- hcpdiff/easy/model/cnet.py +31 -0
- hcpdiff/easy/model/loader.py +79 -0
- hcpdiff/easy/sampler.py +46 -0
- hcpdiff/evaluate/__init__.py +1 -0
- hcpdiff/evaluate/previewer.py +60 -0
- hcpdiff/loss/__init__.py +4 -1
- hcpdiff/loss/base.py +41 -0
- hcpdiff/loss/gw.py +35 -0
- hcpdiff/loss/ssim.py +37 -0
- hcpdiff/loss/vlb.py +79 -0
- hcpdiff/loss/weighting.py +66 -0
- hcpdiff/models/__init__.py +2 -2
- hcpdiff/models/cfg_context.py +17 -14
- hcpdiff/models/compose/compose_hook.py +44 -23
- hcpdiff/models/compose/compose_tokenizer.py +21 -8
- hcpdiff/models/compose/sdxl_composer.py +4 -4
- hcpdiff/models/container.py +1 -1
- hcpdiff/models/controlnet.py +16 -16
- hcpdiff/models/lora_base_patch.py +14 -25
- hcpdiff/models/lora_layers.py +3 -9
- hcpdiff/models/lora_layers_patch.py +14 -24
- hcpdiff/models/text_emb_ex.py +84 -6
- hcpdiff/models/textencoder_ex.py +54 -18
- hcpdiff/models/wrapper/__init__.py +3 -0
- hcpdiff/models/wrapper/pixart.py +19 -0
- hcpdiff/models/wrapper/sd.py +218 -0
- hcpdiff/models/wrapper/utils.py +20 -0
- hcpdiff/parser/__init__.py +1 -0
- hcpdiff/parser/embpt.py +32 -0
- hcpdiff/tools/convert_caption_txt2json.py +1 -1
- hcpdiff/tools/dataset_generator.py +94 -0
- hcpdiff/tools/download_hf_model.py +24 -0
- hcpdiff/tools/embedding_convert.py +6 -2
- hcpdiff/tools/init_proj.py +3 -21
- hcpdiff/tools/lora_convert.py +19 -15
- hcpdiff/tools/save_model.py +12 -0
- hcpdiff/tools/sd2diffusers.py +1 -1
- hcpdiff/train_colo.py +1 -1
- hcpdiff/train_deepspeed.py +1 -1
- hcpdiff/trainer_ac.py +79 -0
- hcpdiff/trainer_ac_single.py +31 -0
- hcpdiff/utils/__init__.py +0 -2
- hcpdiff/utils/inpaint_pipe.py +790 -0
- hcpdiff/utils/net_utils.py +29 -6
- hcpdiff/utils/pipe_hook.py +46 -33
- hcpdiff/utils/utils.py +21 -4
- hcpdiff/workflow/__init__.py +15 -10
- hcpdiff/workflow/daam/__init__.py +1 -0
- hcpdiff/workflow/daam/act.py +66 -0
- hcpdiff/workflow/daam/hook.py +109 -0
- hcpdiff/workflow/diffusion.py +128 -136
- hcpdiff/workflow/fast.py +31 -0
- hcpdiff/workflow/flow.py +67 -0
- hcpdiff/workflow/io.py +36 -68
- hcpdiff/workflow/model.py +46 -43
- hcpdiff/workflow/text.py +84 -52
- hcpdiff/workflow/utils.py +32 -12
- hcpdiff/workflow/vae.py +37 -38
- hcpdiff-2.1.dist-info/METADATA +285 -0
- hcpdiff-2.1.dist-info/RECORD +114 -0
- {hcpdiff-0.9.0.dist-info → hcpdiff-2.1.dist-info}/WHEEL +1 -1
- hcpdiff-2.1.dist-info/entry_points.txt +5 -0
- hcpdiff/ckpt_manager/base.py +0 -16
- hcpdiff/ckpt_manager/ckpt_diffusers.py +0 -45
- hcpdiff/ckpt_manager/ckpt_pkl.py +0 -138
- hcpdiff/ckpt_manager/ckpt_safetensor.py +0 -60
- hcpdiff/ckpt_manager/ckpt_webui.py +0 -54
- hcpdiff/data/bucket.py +0 -358
- hcpdiff/data/caption_loader.py +0 -80
- hcpdiff/data/cond_dataset.py +0 -40
- hcpdiff/data/crop_info_dataset.py +0 -40
- hcpdiff/data/data_processor.py +0 -33
- hcpdiff/data/pair_dataset.py +0 -146
- hcpdiff/data/sampler.py +0 -54
- hcpdiff/data/source/base.py +0 -30
- hcpdiff/data/utils.py +0 -80
- hcpdiff/infer_workflow.py +0 -57
- hcpdiff/loggers/__init__.py +0 -13
- hcpdiff/loggers/base_logger.py +0 -76
- hcpdiff/loggers/cli_logger.py +0 -40
- hcpdiff/loggers/preview/__init__.py +0 -1
- hcpdiff/loggers/preview/image_previewer.py +0 -149
- hcpdiff/loggers/tensorboard_logger.py +0 -30
- hcpdiff/loggers/wandb_logger.py +0 -31
- hcpdiff/loggers/webui_logger.py +0 -9
- hcpdiff/loss/min_snr_loss.py +0 -52
- hcpdiff/models/layers.py +0 -81
- hcpdiff/models/plugin.py +0 -348
- hcpdiff/models/wrapper.py +0 -75
- hcpdiff/noise/__init__.py +0 -3
- hcpdiff/noise/noise_base.py +0 -16
- hcpdiff/noise/pyramid_noise.py +0 -50
- hcpdiff/noise/zero_terminal.py +0 -44
- hcpdiff/train_ac.py +0 -565
- hcpdiff/train_ac_single.py +0 -39
- hcpdiff/utils/caption_tools.py +0 -105
- hcpdiff/utils/cfg_net_tools.py +0 -321
- hcpdiff/utils/cfg_resolvers.py +0 -16
- hcpdiff/utils/ema.py +0 -52
- hcpdiff/utils/img_size_tool.py +0 -248
- hcpdiff/vis/__init__.py +0 -3
- hcpdiff/vis/base_interface.py +0 -12
- hcpdiff/vis/disk_interface.py +0 -48
- hcpdiff/vis/webui_interface.py +0 -17
- hcpdiff/visualizer.py +0 -258
- hcpdiff/visualizer_reloadable.py +0 -237
- hcpdiff/workflow/base.py +0 -59
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/anime/text2img_anime.yaml +0 -21
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/anime/text2img_anime_lora.yaml +0 -58
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/change_vae.yaml +0 -6
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/euler_a.yaml +0 -8
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/img2img.yaml +0 -10
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/img2img_controlnet.yaml +0 -19
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/inpaint.yaml +0 -11
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/load_lora.yaml +0 -26
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/load_unet_part.yaml +0 -18
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/offload_2GB.yaml +0 -6
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/save_model.yaml +0 -44
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/text2img.yaml +0 -53
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/text2img_DA++.yaml +0 -34
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/infer/text2img_sdxl.yaml +0 -9
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/plugins/plugin_controlnet.yaml +0 -17
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/te_struct.txt +0 -193
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/dataset/base_dataset.yaml +0 -29
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/dataset/regularization_dataset.yaml +0 -31
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/CustomDiffusion.yaml +0 -74
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/DreamArtist++.yaml +0 -135
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/DreamArtist.yaml +0 -45
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/DreamBooth.yaml +0 -62
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/FT_sdxl.yaml +0 -33
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/Lion_optimizer.yaml +0 -17
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/TextualInversion.yaml +0 -41
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/add_logger_tensorboard_wandb.yaml +0 -15
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/controlnet.yaml +0 -53
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/ema.yaml +0 -10
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/fine-tuning.yaml +0 -53
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/locon.yaml +0 -24
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/lora_anime_character.yaml +0 -77
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/lora_conventional.yaml +0 -56
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/lora_sdxl.yaml +0 -41
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/min_snr.yaml +0 -7
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples/preview_in_training.yaml +0 -6
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples_noob/DreamBooth.yaml +0 -70
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples_noob/TextualInversion.yaml +0 -45
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples_noob/fine-tuning.yaml +0 -45
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/examples_noob/lora.yaml +0 -63
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/train_base.yaml +0 -81
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/train/tuning_base.yaml +0 -42
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/unet_struct.txt +0 -932
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/workflow/highres_fix_latent.yaml +0 -86
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/workflow/highres_fix_pixel.yaml +0 -99
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/workflow/text2img.yaml +0 -57
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/workflow/text2img_lora.yaml +0 -70
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/zero2.json +0 -32
- hcpdiff-0.9.0.data/data/hcpdiff/cfgs/zero3.json +0 -39
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/caption.txt +0 -1
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/name.txt +0 -1
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/name_2pt_caption.txt +0 -1
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/name_caption.txt +0 -1
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/object.txt +0 -27
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/object_caption.txt +0 -27
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/style.txt +0 -19
- hcpdiff-0.9.0.data/data/hcpdiff/prompt_tuning_template/style_caption.txt +0 -19
- hcpdiff-0.9.0.dist-info/METADATA +0 -199
- hcpdiff-0.9.0.dist-info/RECORD +0 -155
- hcpdiff-0.9.0.dist-info/entry_points.txt +0 -2
- {hcpdiff-0.9.0.dist-info → hcpdiff-2.1.dist-info/licenses}/LICENSE +0 -0
- {hcpdiff-0.9.0.dist-info → hcpdiff-2.1.dist-info}/top_level.txt +0 -0
hcpdiff/easy/cfg/t2i.py
ADDED
@@ -0,0 +1,177 @@
|
|
1
|
+
import torch
|
2
|
+
from rainbowneko.infer.workflow import (Actions, PrepareAction, LoopAction, LoadModelAction)
|
3
|
+
from rainbowneko.parser import neko_cfg, disable_neko_cfg
|
4
|
+
from typing import Union, List
|
5
|
+
|
6
|
+
from hcpdiff.ckpt_manager import HCPLoraLoader
|
7
|
+
from hcpdiff.easy import Diffusers_SD, SD15_auto_loader, SDXL_auto_loader
|
8
|
+
from hcpdiff.workflow import (BuildModelsAction, PrepareDiffusionAction, XformersEnableAction, VaeOptimizeAction, TextHookAction,
|
9
|
+
AttnMultTextEncodeAction, SeedAction, MakeTimestepsAction, MakeLatentAction, DiffusionStepAction,
|
10
|
+
time_iter, DecodeAction, SaveImageAction, LatentResizeAction)
|
11
|
+
|
12
|
+
negative_prompt = 'lowres, bad anatomy, bad hands, text, error, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality, normal quality, jpeg artifacts, signature, watermark, username, blurry'
|
13
|
+
|
14
|
+
## Easy config
|
15
|
+
@neko_cfg
|
16
|
+
def build_model(pretrained_model='ckpts/any5', noise_sampler=Diffusers_SD.dpmpp_2m_karras) -> Actions:
|
17
|
+
return Actions([
|
18
|
+
PrepareAction(device='cuda', dtype=torch.float16),
|
19
|
+
BuildModelsAction(
|
20
|
+
model_loader=SD15_auto_loader(
|
21
|
+
_partial_=True,
|
22
|
+
ckpt_path=pretrained_model,
|
23
|
+
noise_sampler=noise_sampler
|
24
|
+
)
|
25
|
+
),
|
26
|
+
])
|
27
|
+
|
28
|
+
@neko_cfg
|
29
|
+
def load_lora(info: List[List]) -> Actions:
|
30
|
+
lora_acts = []
|
31
|
+
for i, item in enumerate(info):
|
32
|
+
lora_unet = LoadModelAction(cfg={
|
33
|
+
f'lora_unet_{i}':HCPLoraLoader(
|
34
|
+
path=item[0],
|
35
|
+
state_prefix='denoiser.',
|
36
|
+
alpha=item[1],
|
37
|
+
)
|
38
|
+
}, key_map_in=('denoiser -> model', 'in_preview -> in_preview'))
|
39
|
+
lora_TE = LoadModelAction(cfg={
|
40
|
+
f'lora_unet_{i}':HCPLoraLoader(
|
41
|
+
path=item[0],
|
42
|
+
state_prefix='TE.',
|
43
|
+
alpha=item[1],
|
44
|
+
)
|
45
|
+
}, key_map_in=('TE -> model', 'in_preview -> in_preview'))
|
46
|
+
|
47
|
+
with disable_neko_cfg:
|
48
|
+
lora_acts.append(lora_unet)
|
49
|
+
lora_acts.append(lora_TE)
|
50
|
+
|
51
|
+
return Actions(lora_acts)
|
52
|
+
|
53
|
+
@neko_cfg
|
54
|
+
def optimize_model() -> Actions:
|
55
|
+
return Actions([
|
56
|
+
PrepareDiffusionAction(),
|
57
|
+
XformersEnableAction(),
|
58
|
+
VaeOptimizeAction(slicing=True),
|
59
|
+
])
|
60
|
+
|
61
|
+
@neko_cfg
|
62
|
+
def text(prompt, negative_prompt=negative_prompt, bs=4) -> Actions:
|
63
|
+
return Actions([
|
64
|
+
TextHookAction(N_repeats=1, layer_skip=1),
|
65
|
+
AttnMultTextEncodeAction(
|
66
|
+
prompt=prompt,
|
67
|
+
negative_prompt=negative_prompt,
|
68
|
+
bs=bs
|
69
|
+
),
|
70
|
+
])
|
71
|
+
|
72
|
+
@neko_cfg
|
73
|
+
def build_model_SDXL(pretrained_model='ckpts/any5', noise_sampler=Diffusers_SD.dpmpp_2m_karras) -> Actions:
|
74
|
+
return Actions([
|
75
|
+
PrepareAction(device='cuda', dtype=torch.float16),
|
76
|
+
## Easy config
|
77
|
+
BuildModelsAction(
|
78
|
+
model_loader=SDXL_auto_loader(
|
79
|
+
_partial_=True,
|
80
|
+
ckpt_path=pretrained_model,
|
81
|
+
noise_sampler=noise_sampler
|
82
|
+
)
|
83
|
+
),
|
84
|
+
])
|
85
|
+
|
86
|
+
@neko_cfg
|
87
|
+
def text_SDXL(prompt, negative_prompt=negative_prompt, bs=4) -> Actions:
|
88
|
+
return Actions([
|
89
|
+
TextHookAction(N_repeats=1, layer_skip=1, TE_final_norm=False),
|
90
|
+
AttnMultTextEncodeAction(
|
91
|
+
prompt=prompt,
|
92
|
+
negative_prompt=negative_prompt,
|
93
|
+
bs=bs
|
94
|
+
),
|
95
|
+
])
|
96
|
+
|
97
|
+
@neko_cfg
|
98
|
+
def config_diffusion(width=512, height=512, seed=None, N_steps=20, strength: float = None) -> Actions:
|
99
|
+
return Actions([
|
100
|
+
SeedAction(seed),
|
101
|
+
MakeTimestepsAction(N_steps=N_steps, strength=strength),
|
102
|
+
MakeLatentAction(width=width, height=height)
|
103
|
+
])
|
104
|
+
|
105
|
+
@neko_cfg
|
106
|
+
def diffusion(guidance_scale=7.0) -> Actions:
|
107
|
+
return Actions([
|
108
|
+
LoopAction(
|
109
|
+
iterator=time_iter,
|
110
|
+
actions=[
|
111
|
+
DiffusionStepAction(guidance_scale=guidance_scale)
|
112
|
+
]
|
113
|
+
)
|
114
|
+
])
|
115
|
+
|
116
|
+
@neko_cfg
|
117
|
+
def decode(save_root='output_pipe/') -> Actions:
|
118
|
+
return Actions([
|
119
|
+
DecodeAction(),
|
120
|
+
SaveImageAction(save_root=save_root, image_type='png'),
|
121
|
+
])
|
122
|
+
|
123
|
+
@neko_cfg
|
124
|
+
def resize(width=1024, height=1024):
|
125
|
+
return Actions([
|
126
|
+
LatentResizeAction(width=width, height=height)
|
127
|
+
])
|
128
|
+
|
129
|
+
@neko_cfg
|
130
|
+
def SD15_t2i(pretrained_model, prompt, negative_prompt=negative_prompt, noise_sampler=Diffusers_SD.dpmpp_2m_karras, bs=4, width=512, height=512,
|
131
|
+
seed=None, N_steps=20, guidance_scale=7.0, save_root='output_pipe/'):
|
132
|
+
return dict(workflow=Actions(actions=[
|
133
|
+
build_model(pretrained_model=pretrained_model, noise_sampler=noise_sampler),
|
134
|
+
optimize_model(),
|
135
|
+
text(prompt=prompt, negative_prompt=negative_prompt, bs=bs),
|
136
|
+
config_diffusion(width=width, height=height, seed=seed, N_steps=N_steps),
|
137
|
+
diffusion(guidance_scale=guidance_scale),
|
138
|
+
decode(save_root=save_root)
|
139
|
+
]))
|
140
|
+
|
141
|
+
@neko_cfg
|
142
|
+
def SD15_t2i_lora(pretrained_model, lora_info, prompt, negative_prompt=negative_prompt, noise_sampler=Diffusers_SD.dpmpp_2m_karras, bs=4,
|
143
|
+
width=512, height=512, seed=None, N_steps=20, guidance_scale=7.0, save_root='output_pipe/'):
|
144
|
+
return dict(workflow=Actions(actions=[
|
145
|
+
build_model(pretrained_model=pretrained_model, noise_sampler=noise_sampler),
|
146
|
+
load_lora(info=lora_info),
|
147
|
+
optimize_model(),
|
148
|
+
text(prompt=prompt, negative_prompt=negative_prompt, bs=bs),
|
149
|
+
config_diffusion(width=width, height=height, seed=seed, N_steps=N_steps),
|
150
|
+
diffusion(guidance_scale=guidance_scale),
|
151
|
+
decode(save_root=save_root)
|
152
|
+
]))
|
153
|
+
|
154
|
+
@neko_cfg
|
155
|
+
def SDXL_t2i(pretrained_model, prompt, negative_prompt=negative_prompt, noise_sampler=Diffusers_SD.dpmpp_2m_karras, bs=4, width=1024, height=1024,
|
156
|
+
seed=None, N_steps=20, guidance_scale=7.0, save_root='output_pipe/'):
|
157
|
+
return dict(workflow=Actions(actions=[
|
158
|
+
build_model_SDXL(pretrained_model=pretrained_model, noise_sampler=noise_sampler),
|
159
|
+
optimize_model(),
|
160
|
+
text_SDXL(prompt=prompt, negative_prompt=negative_prompt, bs=bs),
|
161
|
+
config_diffusion(width=width, height=height, seed=seed, N_steps=N_steps),
|
162
|
+
diffusion(guidance_scale=guidance_scale),
|
163
|
+
decode(save_root=save_root)
|
164
|
+
]))
|
165
|
+
|
166
|
+
@neko_cfg
|
167
|
+
def SDXL_t2i_lora(pretrained_model, lora_info, prompt, negative_prompt=negative_prompt, noise_sampler=Diffusers_SD.dpmpp_2m_karras, bs=4,
|
168
|
+
width=1024, height=1024, seed=None, N_steps=20, guidance_scale=7.0, save_root='output_pipe/'):
|
169
|
+
return dict(workflow=Actions(actions=[
|
170
|
+
build_model_SDXL(pretrained_model=pretrained_model, noise_sampler=noise_sampler),
|
171
|
+
load_lora(info=lora_info),
|
172
|
+
optimize_model(),
|
173
|
+
text_SDXL(prompt=prompt, negative_prompt=negative_prompt, bs=bs),
|
174
|
+
config_diffusion(width=width, height=height, seed=seed, N_steps=N_steps),
|
175
|
+
diffusion(guidance_scale=guidance_scale),
|
176
|
+
decode(save_root=save_root)
|
177
|
+
]))
|
@@ -0,0 +1,31 @@
|
|
1
|
+
from hcpdiff.data.handler import ControlNetHandler, StableDiffusionHandler
|
2
|
+
from hcpdiff.models import ControlNetPlugin
|
3
|
+
from rainbowneko.data import SyncHandler
|
4
|
+
from rainbowneko.parser import neko_cfg
|
5
|
+
|
6
|
+
@neko_cfg
|
7
|
+
def ControlNet_SD15(lr=1e-4):
|
8
|
+
return ControlNetPlugin(
|
9
|
+
_partial_=True,
|
10
|
+
lr=lr,
|
11
|
+
from_layers=[
|
12
|
+
'pre_hook:',
|
13
|
+
'pre_hook:conv_in', # to make forward inside autocast
|
14
|
+
],
|
15
|
+
to_layers=[
|
16
|
+
'down_blocks.0',
|
17
|
+
'down_blocks.1',
|
18
|
+
'down_blocks.2',
|
19
|
+
'down_blocks.3',
|
20
|
+
'mid_block',
|
21
|
+
'pre_hook:up_blocks.3.resnets.2',
|
22
|
+
]
|
23
|
+
)
|
24
|
+
|
25
|
+
@neko_cfg
|
26
|
+
def make_controlnet_handler(bucket=None, encoder_attention_mask=False, erase=0.15, dropout=0.0, shuffle=0.0, word_names={}):
|
27
|
+
return SyncHandler(
|
28
|
+
diffusion=StableDiffusionHandler(bucket=bucket, encoder_attention_mask=encoder_attention_mask, erase=erase, dropout=dropout, shuffle=shuffle,
|
29
|
+
word_names=word_names),
|
30
|
+
cnet=ControlNetHandler(bucket=bucket)
|
31
|
+
)
|
@@ -0,0 +1,79 @@
|
|
1
|
+
import torch
|
2
|
+
from hcpdiff.ckpt_manager import DiffusersSD15Format, DiffusersSDXLFormat, DiffusersPixArtFormat, OfficialSD15Format, OfficialSDXLFormat
|
3
|
+
from rainbowneko.ckpt_manager import NekoLoader, LocalCkptSource
|
4
|
+
from hcpdiff.utils import auto_tokenizer_cls, auto_text_encoder_cls, get_pipe_name
|
5
|
+
from hcpdiff.models.wrapper import SDXLWrapper, SD15Wrapper, PixArtWrapper
|
6
|
+
from hcpdiff.models.compose import SDXLTextEncoder
|
7
|
+
from diffusers import StableDiffusionPipeline, StableDiffusionXLPipeline
|
8
|
+
|
9
|
+
def SD15_auto_loader(ckpt_path, denoiser=None, TE=None, vae=None, noise_sampler=None,
|
10
|
+
tokenizer=None, revision=None, dtype=torch.float32, **kwargs):
|
11
|
+
try:
|
12
|
+
try_diffusers = StableDiffusionPipeline.load_config(ckpt_path)
|
13
|
+
loader = NekoLoader(
|
14
|
+
format=DiffusersSD15Format(),
|
15
|
+
source=LocalCkptSource(),
|
16
|
+
)
|
17
|
+
except EnvironmentError:
|
18
|
+
loader = NekoLoader(
|
19
|
+
format=OfficialSD15Format(),
|
20
|
+
source=LocalCkptSource(),
|
21
|
+
)
|
22
|
+
models = loader.load(ckpt_path, denoiser=denoiser, TE=TE, vae=vae, noise_sampler=noise_sampler, tokenizer=tokenizer, revision=revision,
|
23
|
+
dtype=dtype, **kwargs)
|
24
|
+
return models
|
25
|
+
|
26
|
+
def SDXL_auto_loader(ckpt_path, denoiser=None, TE=None, vae=None, noise_sampler=None,
|
27
|
+
tokenizer=None, revision=None, dtype=torch.float32, **kwargs):
|
28
|
+
try:
|
29
|
+
try_diffusers = StableDiffusionXLPipeline.load_config(ckpt_path)
|
30
|
+
loader = NekoLoader(
|
31
|
+
format=DiffusersSDXLFormat(),
|
32
|
+
source=LocalCkptSource(),
|
33
|
+
)
|
34
|
+
except EnvironmentError:
|
35
|
+
loader = NekoLoader(
|
36
|
+
format=OfficialSDXLFormat(),
|
37
|
+
source=LocalCkptSource(),
|
38
|
+
)
|
39
|
+
models = loader.load(ckpt_path, denoiser=denoiser, TE=TE, vae=vae, noise_sampler=noise_sampler, tokenizer=tokenizer, revision=revision,
|
40
|
+
dtype=dtype, **kwargs)
|
41
|
+
return models
|
42
|
+
|
43
|
+
def PixArt_auto_loader(ckpt_path, denoiser=None, TE=None, vae=None, noise_sampler=None,
|
44
|
+
tokenizer=None, revision=None, dtype=torch.float32, **kwargs):
|
45
|
+
loader = NekoLoader(
|
46
|
+
format=DiffusersPixArtFormat(),
|
47
|
+
source=LocalCkptSource(),
|
48
|
+
)
|
49
|
+
models = loader.load(ckpt_path, denoiser=denoiser, TE=TE, vae=vae, noise_sampler=noise_sampler, tokenizer=tokenizer, revision=revision,
|
50
|
+
dtype=dtype, **kwargs)
|
51
|
+
return models
|
52
|
+
|
53
|
+
def auto_load_wrapper(pretrained_model, denoiser=None, TE=None, vae=None, noise_sampler=None, tokenizer=None, revision=None,
|
54
|
+
dtype=torch.float32, **kwargs):
|
55
|
+
if TE is not None:
|
56
|
+
text_encoder_cls = type(TE)
|
57
|
+
else:
|
58
|
+
text_encoder_cls = auto_text_encoder_cls(pretrained_model, revision)
|
59
|
+
|
60
|
+
pipe_name = get_pipe_name(pretrained_model)
|
61
|
+
|
62
|
+
if text_encoder_cls == SDXLTextEncoder:
|
63
|
+
wrapper_cls = SDXLWrapper
|
64
|
+
format = DiffusersSDXLFormat()
|
65
|
+
elif 'PixArt' in pipe_name:
|
66
|
+
wrapper_cls = PixArtWrapper
|
67
|
+
format = DiffusersPixArtFormat()
|
68
|
+
else:
|
69
|
+
wrapper_cls = SD15Wrapper
|
70
|
+
format = DiffusersSD15Format()
|
71
|
+
|
72
|
+
loader = NekoLoader(
|
73
|
+
format=format,
|
74
|
+
source=LocalCkptSource(),
|
75
|
+
)
|
76
|
+
models = loader.load(pretrained_model, denoiser=denoiser, TE=TE, vae=vae, noise_sampler=noise_sampler, tokenizer=tokenizer, revision=revision,
|
77
|
+
dtype=dtype)
|
78
|
+
|
79
|
+
return wrapper_cls.build_from_pretrained(models, **kwargs)
|
hcpdiff/easy/sampler.py
ADDED
@@ -0,0 +1,46 @@
|
|
1
|
+
from hcpdiff.diffusion.sampler import DiffusersSampler
|
2
|
+
from diffusers import DPMSolverMultistepScheduler, DDIMScheduler, EulerDiscreteScheduler, EulerAncestralDiscreteScheduler
|
3
|
+
|
4
|
+
class Diffusers_SD:
|
5
|
+
dpmpp_2m = DiffusersSampler(
|
6
|
+
DPMSolverMultistepScheduler(
|
7
|
+
beta_start=0.00085,
|
8
|
+
beta_end=0.012,
|
9
|
+
beta_schedule='scaled_linear',
|
10
|
+
algorithm_type='dpmsolver++',
|
11
|
+
)
|
12
|
+
)
|
13
|
+
|
14
|
+
dpmpp_2m_karras = DiffusersSampler(
|
15
|
+
DPMSolverMultistepScheduler(
|
16
|
+
beta_start=0.00085,
|
17
|
+
beta_end=0.012,
|
18
|
+
beta_schedule='scaled_linear',
|
19
|
+
algorithm_type='dpmsolver++',
|
20
|
+
use_karras_sigmas=True,
|
21
|
+
)
|
22
|
+
)
|
23
|
+
|
24
|
+
ddim = DiffusersSampler(
|
25
|
+
DDIMScheduler(
|
26
|
+
beta_start=0.00085,
|
27
|
+
beta_end=0.012,
|
28
|
+
beta_schedule='scaled_linear',
|
29
|
+
)
|
30
|
+
)
|
31
|
+
|
32
|
+
euler = DiffusersSampler(
|
33
|
+
EulerDiscreteScheduler(
|
34
|
+
beta_start=0.00085,
|
35
|
+
beta_end=0.012,
|
36
|
+
beta_schedule='scaled_linear',
|
37
|
+
)
|
38
|
+
)
|
39
|
+
|
40
|
+
euler_a = DiffusersSampler(
|
41
|
+
EulerAncestralDiscreteScheduler(
|
42
|
+
beta_start=0.00085,
|
43
|
+
beta_end=0.012,
|
44
|
+
beta_schedule='scaled_linear',
|
45
|
+
)
|
46
|
+
)
|
@@ -0,0 +1 @@
|
|
1
|
+
from .previewer import HCPPreviewer
|
@@ -0,0 +1,60 @@
|
|
1
|
+
from pathlib import Path
|
2
|
+
|
3
|
+
import torch
|
4
|
+
from rainbowneko.evaluate.preview import WorkflowPreviewer
|
5
|
+
from rainbowneko.utils import to_cuda
|
6
|
+
|
7
|
+
from hcpdiff.models.wrapper import SD15Wrapper
|
8
|
+
from accelerate.hooks import remove_hook_from_module
|
9
|
+
|
10
|
+
class HCPPreviewer(WorkflowPreviewer):
|
11
|
+
|
12
|
+
@torch.no_grad()
|
13
|
+
def evaluate(self, step: int, model: SD15Wrapper, prefix='eval/'):
|
14
|
+
if step%self.interval != 0 or not self.trainer.is_local_main_process:
|
15
|
+
return
|
16
|
+
|
17
|
+
# record training layers
|
18
|
+
training_layers = [layer for layer in model.modules() if layer.training]
|
19
|
+
|
20
|
+
model.eval()
|
21
|
+
self.trainer.loggers.info(f'Preview')
|
22
|
+
|
23
|
+
N_repeats = model.text_enc_hook.N_repeats
|
24
|
+
clip_skip = model.text_enc_hook.clip_skip
|
25
|
+
clip_final_norm = model.text_enc_hook.clip_final_norm
|
26
|
+
use_attention_mask = model.text_enc_hook.use_attention_mask
|
27
|
+
|
28
|
+
preview_root = Path(self.trainer.exp_dir)/'imgs'
|
29
|
+
preview_root.mkdir(parents=True, exist_ok=True)
|
30
|
+
|
31
|
+
states = self.workflow_runner.run(model=model, in_preview=True, te_hook=model.text_enc_hook,
|
32
|
+
device=self.device, dtype=self.dtype, preview_root=preview_root, preview_step=step,
|
33
|
+
world_size=self.trainer.world_size, local_rank=self.trainer.local_rank,
|
34
|
+
emb_hook=self.trainer.cfgs.emb_pt.embedding_hook if self.trainer.pt_trainable else None)
|
35
|
+
|
36
|
+
# restore model states
|
37
|
+
if model.vae is not None:
|
38
|
+
model.vae.disable_tiling()
|
39
|
+
model.vae.disable_slicing()
|
40
|
+
remove_hook_from_module(model.vae, recurse=True)
|
41
|
+
if 'vae_encode_raw' in states:
|
42
|
+
model.vae.encode = states['vae_encode_raw']
|
43
|
+
model.vae.decode = states['vae_decode_raw']
|
44
|
+
|
45
|
+
if 'emb_hook' in states and not self.trainer.pt_trainable:
|
46
|
+
states['emb_hook'].remove()
|
47
|
+
|
48
|
+
if self.trainer.pt_trainable:
|
49
|
+
self.trainer.cfgs.emb_pt.embedding_hook.N_repeats = N_repeats
|
50
|
+
|
51
|
+
model.tokenizer.N_repeats = N_repeats
|
52
|
+
model.text_enc_hook.N_repeats = N_repeats
|
53
|
+
model.text_enc_hook.clip_skip = clip_skip
|
54
|
+
model.text_enc_hook.clip_final_norm = clip_final_norm
|
55
|
+
model.text_enc_hook.use_attention_mask = use_attention_mask
|
56
|
+
|
57
|
+
to_cuda(model)
|
58
|
+
|
59
|
+
for layer in training_layers:
|
60
|
+
layer.train()
|
hcpdiff/loss/__init__.py
CHANGED
hcpdiff/loss/base.py
ADDED
@@ -0,0 +1,41 @@
|
|
1
|
+
from rainbowneko.train.loss import LossContainer
|
2
|
+
from typing import Dict, Any
|
3
|
+
from torch import Tensor
|
4
|
+
|
5
|
+
class DiffusionLossContainer(LossContainer):
|
6
|
+
def __init__(self, loss, weight=1.0, key_map=None):
|
7
|
+
key_map = key_map or getattr(loss, '_key_map', None) or ('pred.model_pred -> 0', 'pred.target -> 1')
|
8
|
+
super().__init__(loss, weight, key_map)
|
9
|
+
self.target_type = getattr(loss, 'target_type', 'eps')
|
10
|
+
|
11
|
+
def get_target(self, pred_type, model_pred, x_0, noise, x_t, sigma, noise_sampler, **kwargs):
|
12
|
+
# Get target
|
13
|
+
if self.target_type == "eps":
|
14
|
+
target = noise
|
15
|
+
elif self.target_type == "x0":
|
16
|
+
target = x_0
|
17
|
+
elif self.target_type == "velocity":
|
18
|
+
target = noise_sampler.eps_to_velocity(noise, x_t, sigma)
|
19
|
+
else:
|
20
|
+
raise ValueError(f"Unsupport target_type {self.target_type}")
|
21
|
+
|
22
|
+
# TODO: put in wrapper
|
23
|
+
# # remove pred vars
|
24
|
+
# if model_pred.shape[1] == target.shape[1]*2:
|
25
|
+
# model_pred, _ = model_pred.chunk(2, dim=1)
|
26
|
+
|
27
|
+
# Convert pred_type to target_type
|
28
|
+
if pred_type != self.target_type:
|
29
|
+
cvt_func = getattr(noise_sampler, f'{pred_type}_to_{self.target_type}', None)
|
30
|
+
if cvt_func is None:
|
31
|
+
raise ValueError(f"Unsupport pred_type {pred_type} with target_type {self.target_type}")
|
32
|
+
else:
|
33
|
+
model_pred = cvt_func(model_pred, x_t, sigma)
|
34
|
+
return model_pred, target
|
35
|
+
|
36
|
+
def forward(self, pred:Dict[str,Any], inputs:Dict[str,Any]) -> Tensor:
|
37
|
+
model_pred, target = self.get_target(**pred)
|
38
|
+
pred['model_pred'] = model_pred
|
39
|
+
pred['target'] = target
|
40
|
+
loss = super().forward(pred, inputs) * self.weight # [B,*,*,*]
|
41
|
+
return loss.mean()
|
hcpdiff/loss/gw.py
ADDED
@@ -0,0 +1,35 @@
|
|
1
|
+
import torch
|
2
|
+
from torch import nn
|
3
|
+
from torch.nn import functional as F
|
4
|
+
|
5
|
+
class GWLoss(nn.Module):
|
6
|
+
def __init__(self):
|
7
|
+
super().__init__()
|
8
|
+
|
9
|
+
sobel_x = [[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]
|
10
|
+
sobel_y = [[-1, -2, -1], [0, 0, 0], [1, 2, 1]]
|
11
|
+
self.sobel_x = torch.FloatTensor(sobel_x)
|
12
|
+
self.sobel_y = torch.FloatTensor(sobel_y)
|
13
|
+
self.register_buffer('sobel_x', self.sobel_x)
|
14
|
+
self.register_buffer('sobel_y', self.sobel_y)
|
15
|
+
|
16
|
+
def forward(self, pred, target):
|
17
|
+
'''
|
18
|
+
|
19
|
+
:param pred: [B,C,H,W]
|
20
|
+
:param target: [B,C,H,W]
|
21
|
+
:return: [B,C,H,W]
|
22
|
+
'''
|
23
|
+
b, c, w, h = pred.shape
|
24
|
+
|
25
|
+
sobel_x = self.sobel_x.expand(c, 1, 3, 3).to(pred.device)
|
26
|
+
sobel_y = self.sobel_y.expand(c, 1, 3, 3).to(pred.device)
|
27
|
+
Ix1 = F.conv2d(pred, sobel_x, stride=1, padding=1, groups=c)
|
28
|
+
Ix2 = F.conv2d(target, sobel_x, stride=1, padding=1, groups=c)
|
29
|
+
Iy1 = F.conv2d(pred, sobel_y, stride=1, padding=1, groups=c)
|
30
|
+
Iy2 = F.conv2d(target, sobel_y, stride=1, padding=1, groups=c)
|
31
|
+
|
32
|
+
dx = torch.abs(Ix1 - Ix2)
|
33
|
+
dy = torch.abs(Iy1 - Iy2)
|
34
|
+
loss = (1 + 4 * dx) * (1 + 4 * dy) * torch.abs(pred - target)
|
35
|
+
return loss
|
hcpdiff/loss/ssim.py
ADDED
@@ -0,0 +1,37 @@
|
|
1
|
+
from pytorch_msssim import SSIM, MS_SSIM
|
2
|
+
from torch.nn.modules.loss import _Loss
|
3
|
+
import torch
|
4
|
+
|
5
|
+
class SSIMLoss(_Loss):
|
6
|
+
target_type = 'x0'
|
7
|
+
|
8
|
+
def __init__(self, size_average=None, reduce=None, reduction: str = 'mean'):
|
9
|
+
super().__init__(size_average=size_average, reduce=reduce, reduction=reduction)
|
10
|
+
self.ssim = SSIM(data_range=1., size_average=False, channel=4)
|
11
|
+
|
12
|
+
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
13
|
+
'''
|
14
|
+
|
15
|
+
:param input: [B,C,H,W]
|
16
|
+
:param target: [B,C,H,W]
|
17
|
+
:return: [B,1,1,1]
|
18
|
+
'''
|
19
|
+
input = (input+1)/2
|
20
|
+
target = (target+1)/2
|
21
|
+
return 1-self.ssim(input, target).view(-1,1,1,1)
|
22
|
+
|
23
|
+
class MS_SSIMLoss(_Loss):
|
24
|
+
def __init__(self, size_average=None, reduce=None, reduction: str = 'mean'):
|
25
|
+
super().__init__(size_average=size_average, reduce=reduce, reduction=reduction)
|
26
|
+
self.ssim = MS_SSIM(data_range=1., size_average=False, channel=4)
|
27
|
+
|
28
|
+
def forward(self, input: torch.Tensor, target: torch.Tensor) -> torch.Tensor:
|
29
|
+
'''
|
30
|
+
|
31
|
+
:param input: [B,C,H,W]
|
32
|
+
:param target: [B,C,H,W]
|
33
|
+
:return: [B,1,1,1]
|
34
|
+
'''
|
35
|
+
input = (input+1)/2
|
36
|
+
target = (target+1)/2
|
37
|
+
return 1-self.ssim(input, target).view(-1,1,1,1)
|
hcpdiff/loss/vlb.py
ADDED
@@ -0,0 +1,79 @@
|
|
1
|
+
import torch
|
2
|
+
from torch import nn
|
3
|
+
import numpy as np
|
4
|
+
|
5
|
+
class VLBLoss(nn.Module):
|
6
|
+
need_sigma = True
|
7
|
+
need_timesteps = True
|
8
|
+
need_sampler = True
|
9
|
+
var_pred = True
|
10
|
+
|
11
|
+
def __init__(self, loss, weight: float = 1.):
|
12
|
+
super().__init__()
|
13
|
+
self.loss = loss
|
14
|
+
self.weight = weight
|
15
|
+
|
16
|
+
def normal_kl(self, mean1, logvar1, mean2, logvar2):
|
17
|
+
"""
|
18
|
+
Compute the KL divergence between two gaussians.
|
19
|
+
"""
|
20
|
+
|
21
|
+
return 0.5*(-1.0+logvar2-logvar1+(logvar1-logvar2).exp()+((mean1-mean2)**2)*(-logvar2).exp())
|
22
|
+
|
23
|
+
def forward(self, input: torch.Tensor, target: torch.Tensor, sigma, timesteps: torch.Tensor, x_t: torch.Tensor, sampler):
|
24
|
+
eps_pred, var_pred = input.chunk(2, dim=1)
|
25
|
+
x0_pred = sampler.eps_to_x0(eps_pred, x_t, sigma)
|
26
|
+
|
27
|
+
true_mean = sampler.sigma_scheduler.get_post_mean(timesteps, target, x_t)
|
28
|
+
true_logvar = sampler.sigma_scheduler.get_post_log_var(timesteps)
|
29
|
+
|
30
|
+
pred_mean = sampler.sigma_scheduler.get_post_mean(timesteps, x0_pred, x_t)
|
31
|
+
pred_logvar = sampler.sigma_scheduler.get_post_log_var(timesteps, x_t_var=var_pred)
|
32
|
+
|
33
|
+
kl = self.normal_kl(true_mean, true_logvar, pred_mean, pred_logvar)
|
34
|
+
kl = kl.mean(dim=(1,2,3))/np.log(2.0)
|
35
|
+
|
36
|
+
decoder_nll = -self.discretized_gaussian_log_likelihood(target, means=pred_mean, log_scales=0.5*pred_logvar)
|
37
|
+
assert decoder_nll.shape == target.shape
|
38
|
+
decoder_nll = decoder_nll.mean(dim=(1,2,3))/np.log(2.0)
|
39
|
+
|
40
|
+
# At the first timestep return the decoder NLL,
|
41
|
+
# otherwise return KL(q(x_{t-1}|x_t,x_0) || p(x_{t-1}|x_t))
|
42
|
+
output = torch.where((timesteps == 0), decoder_nll, kl)
|
43
|
+
|
44
|
+
return self.weight*output
|
45
|
+
|
46
|
+
def approx_standard_normal_cdf(self, x):
|
47
|
+
"""
|
48
|
+
A fast approximation of the cumulative distribution function of the
|
49
|
+
standard normal.
|
50
|
+
"""
|
51
|
+
return 0.5*(1.0+torch.tanh(np.sqrt(2.0/np.pi)*(x+0.044715*torch.pow(x, 3))))
|
52
|
+
|
53
|
+
def discretized_gaussian_log_likelihood(self, x, *, means, log_scales):
|
54
|
+
"""
|
55
|
+
Compute the log-likelihood of a Gaussian distribution discretizing to a
|
56
|
+
given image.
|
57
|
+
:param x: the target images. It is assumed that this was uint8 values,
|
58
|
+
rescaled to the range [-1, 1].
|
59
|
+
:param means: the Gaussian mean Tensor.
|
60
|
+
:param log_scales: the Gaussian log stddev Tensor.
|
61
|
+
:return: a tensor like x of log probabilities (in nats).
|
62
|
+
"""
|
63
|
+
assert x.shape == means.shape == log_scales.shape
|
64
|
+
centered_x = x-means
|
65
|
+
inv_stdv = torch.exp(-log_scales)
|
66
|
+
plus_in = inv_stdv*(centered_x+1.0/255.0)
|
67
|
+
cdf_plus = self.approx_standard_normal_cdf(plus_in)
|
68
|
+
min_in = inv_stdv*(centered_x-1.0/255.0)
|
69
|
+
cdf_min = self.approx_standard_normal_cdf(min_in)
|
70
|
+
log_cdf_plus = torch.log(cdf_plus.clamp(min=1e-12))
|
71
|
+
log_one_minus_cdf_min = torch.log((1.0-cdf_min).clamp(min=1e-12))
|
72
|
+
cdf_delta = cdf_plus-cdf_min
|
73
|
+
log_probs = torch.where(
|
74
|
+
x<-0.999,
|
75
|
+
log_cdf_plus,
|
76
|
+
torch.where(x>0.999, log_one_minus_cdf_min, torch.log(cdf_delta.clamp(min=1e-12))),
|
77
|
+
)
|
78
|
+
assert log_probs.shape == x.shape
|
79
|
+
return log_probs
|
@@ -0,0 +1,66 @@
|
|
1
|
+
from torch import nn
|
2
|
+
|
3
|
+
from .base import DiffusionLossContainer
|
4
|
+
|
5
|
+
class LossWeight(nn.Module):
|
6
|
+
def __init__(self, loss: DiffusionLossContainer):
|
7
|
+
super().__init__()
|
8
|
+
self.loss = loss
|
9
|
+
|
10
|
+
def get_weight(self, pred, inputs):
|
11
|
+
'''
|
12
|
+
|
13
|
+
:param input: [B,C,H,W]
|
14
|
+
:param target: [B,C,H,W]
|
15
|
+
:return: [B,1,1,1] or [B,C,H,W]
|
16
|
+
'''
|
17
|
+
raise NotImplementedError
|
18
|
+
|
19
|
+
def forward(self, pred, inputs):
|
20
|
+
'''
|
21
|
+
weight: [B,1,1,1] or [B,C,H,W]
|
22
|
+
loss: [B,*,*,*]
|
23
|
+
'''
|
24
|
+
return self.get_weight(pred, inputs)*self.loss(pred, inputs)
|
25
|
+
|
26
|
+
class SNRWeight(LossWeight):
|
27
|
+
def get_weight(self, pred, inputs):
|
28
|
+
if self.loss.target_type == 'eps':
|
29
|
+
return 1
|
30
|
+
elif self.loss.target_type == "x0":
|
31
|
+
sigma = pred['sigma']
|
32
|
+
return (1./sigma**2).view(-1, 1, 1, 1)
|
33
|
+
else:
|
34
|
+
raise ValueError(f"{self.__class__.__name__} is not support for target_type {self.loss.target_type}")
|
35
|
+
|
36
|
+
class MinSNRWeight(LossWeight):
|
37
|
+
def __init__(self, loss: DiffusionLossContainer, gamma: float = 1.):
|
38
|
+
super().__init__(loss)
|
39
|
+
self.gamma = gamma
|
40
|
+
|
41
|
+
def get_weight(self, pred, inputs):
|
42
|
+
sigma = pred['sigma']
|
43
|
+
if self.loss.target_type == 'eps':
|
44
|
+
w_snr = (self.gamma*sigma**2).clip(max=1).float()
|
45
|
+
elif self.loss.target_type == "x0":
|
46
|
+
w_snr = (1/(sigma**2)).clip(max=self.gamma).float()
|
47
|
+
else:
|
48
|
+
raise ValueError(f"{self.__class__.__name__} is not support for target_type {self.loss.target_type}")
|
49
|
+
|
50
|
+
return w_snr.view(-1, 1, 1, 1)
|
51
|
+
|
52
|
+
class EDMWeight(LossWeight):
|
53
|
+
def __init__(self, loss: DiffusionLossContainer, gamma: float = 1.):
|
54
|
+
super().__init__(loss)
|
55
|
+
self.gamma = gamma
|
56
|
+
|
57
|
+
def get_weight(self, pred, inputs):
|
58
|
+
sigma = pred['sigma']
|
59
|
+
if self.loss.target_type == 'eps':
|
60
|
+
w_snr = ((sigma**2+self.gamma**2)/(self.gamma**2)).float()
|
61
|
+
elif self.loss.target_type == "x0":
|
62
|
+
w_snr = ((sigma**2+self.gamma**2)/((sigma*self.gamma)**2)).float()
|
63
|
+
else:
|
64
|
+
raise ValueError(f"{self.__class__.__name__} is not support for target_type {self.loss.target_type}")
|
65
|
+
|
66
|
+
return w_snr.view(-1, 1, 1, 1)
|
hcpdiff/models/__init__.py
CHANGED
@@ -1,4 +1,3 @@
|
|
1
|
-
from .plugin import PluginBlock, PluginGroup, SinglePluginBlock, MultiPluginBlock, PatchPluginBlock
|
2
1
|
# from .lora_base import LoraBlock, LoraGroup
|
3
2
|
# from .lora_layers import lora_layer_map
|
4
3
|
from .lora_base_patch import LoraBlock, LoraGroup
|
@@ -7,4 +6,5 @@ from .text_emb_ex import EmbeddingPTHook
|
|
7
6
|
from .textencoder_ex import TEEXHook
|
8
7
|
from .tokenizer_ex import TokenizerHook
|
9
8
|
from .cfg_context import CFGContext, DreamArtistPTContext
|
10
|
-
from .wrapper import
|
9
|
+
from .wrapper import SD15Wrapper, SDXLWrapper, PixArtWrapper, TEHookCFG
|
10
|
+
from .controlnet import ControlNetPlugin
|