modelscope/DiffSynth-Painter
14
1import torch2from .attention import Attention3from .sd_unet import ResnetBlock, UpSampler4from .tiler import TileWorker5 6 7class VAEAttentionBlock(torch.nn.Module):8 9 def __init__(self, num_attention_heads, attention_head_dim, in_channels, num_layers=1, norm_num_groups=32, eps=1e-5):10 super().__init__()11 inner_dim = num_attention_heads * attention_head_dim12 13 self.norm = torch.nn.GroupNorm(num_groups=norm_num_groups, num_channels=in_channels, eps=eps, affine=True)14 15 self.transformer_blocks = torch.nn.ModuleList([16 Attention(17 inner_dim,18 num_attention_heads,19 attention_head_dim,20 bias_q=True,21 bias_kv=True,22 bias_out=True23 )24 for d in range(num_layers)25 ])26 27 def forward(self, hidden_states, time_emb, text_emb, res_stack):28 batch, _, height, width = hidden_states.shape29 residual = hidden_states30 31 hidden_states = self.norm(hidden_states)32 inner_dim = hidden_states.shape[1]33 hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * width, inner_dim)34 35 for block in self.transformer_blocks:36 hidden_states = block(hidden_states)37 38 hidden_states = hidden_states.reshape(batch, height, width, inner_dim).permute(0, 3, 1, 2).contiguous()39 hidden_states = hidden_states + residual40 41 return hidden_states, time_emb, text_emb, res_stack42 43 44class SDVAEDecoder(torch.nn.Module):45 def __init__(self):46 super().__init__()47 self.scaling_factor = 0.1821548 self.post_quant_conv = torch.nn.Conv2d(4, 4, kernel_size=1)49 self.conv_in = torch.nn.Conv2d(4, 512, kernel_size=3, padding=1)50 51 self.blocks = torch.nn.ModuleList([52 # UNetMidBlock2D53 ResnetBlock(512, 512, eps=1e-6),54 VAEAttentionBlock(1, 512, 512, 1, eps=1e-6),55 ResnetBlock(512, 512, eps=1e-6),56 # UpDecoderBlock2D57 ResnetBlock(512, 512, eps=1e-6),58 ResnetBlock(512, 512, eps=1e-6),59 ResnetBlock(512, 512, eps=1e-6),60 UpSampler(512),61 # UpDecoderBlock2D62 ResnetBlock(512, 512, eps=1e-6),63 ResnetBlock(512, 512, eps=1e-6),64 ResnetBlock(512, 512, eps=1e-6),65 UpSampler(512),66 # UpDecoderBlock2D67 ResnetBlock(512, 256, eps=1e-6),68 ResnetBlock(256, 256, eps=1e-6),69 ResnetBlock(256, 256, eps=1e-6),70 UpSampler(256),71 # UpDecoderBlock2D72 ResnetBlock(256, 128, eps=1e-6),73 ResnetBlock(128, 128, eps=1e-6),74 ResnetBlock(128, 128, eps=1e-6),75 ])76 77 self.conv_norm_out = torch.nn.GroupNorm(num_channels=128, num_groups=32, eps=1e-5)78 self.conv_act = torch.nn.SiLU()79 self.conv_out = torch.nn.Conv2d(128, 3, kernel_size=3, padding=1)80 81 def tiled_forward(self, sample, tile_size=64, tile_stride=32):82 hidden_states = TileWorker().tiled_forward(83 lambda x: self.forward(x),84 sample,85 tile_size,86 tile_stride,87 tile_device=sample.device,88 tile_dtype=sample.dtype89 )90 return hidden_states91 92 def forward(self, sample, tiled=False, tile_size=64, tile_stride=32, **kwargs):93 original_dtype = sample.dtype94 sample = sample.to(dtype=next(iter(self.parameters())).dtype)95 # For VAE Decoder, we do not need to apply the tiler on each layer.96 if tiled:97 return self.tiled_forward(sample, tile_size=tile_size, tile_stride=tile_stride)98 99 # 1. pre-process100 sample = sample / self.scaling_factor101 hidden_states = self.post_quant_conv(sample)102 hidden_states = self.conv_in(hidden_states)103 time_emb = None104 text_emb = None105 res_stack = None106 107 # 2. blocks108 for i, block in enumerate(self.blocks):109 hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)110 111 # 3. output112 hidden_states = self.conv_norm_out(hidden_states)113 hidden_states = self.conv_act(hidden_states)114 hidden_states = self.conv_out(hidden_states)115 hidden_states = hidden_states.to(original_dtype)116 117 return hidden_states118 119 @staticmethod120 def state_dict_converter():121 return SDVAEDecoderStateDictConverter()122 123 124class SDVAEDecoderStateDictConverter:125 def __init__(self):126 pass127 128 def from_diffusers(self, state_dict):129 # architecture130 block_types = [131 'ResnetBlock', 'VAEAttentionBlock', 'ResnetBlock',132 'ResnetBlock', 'ResnetBlock', 'ResnetBlock', 'UpSampler',133 'ResnetBlock', 'ResnetBlock', 'ResnetBlock', 'UpSampler',134 'ResnetBlock', 'ResnetBlock', 'ResnetBlock', 'UpSampler',135 'ResnetBlock', 'ResnetBlock', 'ResnetBlock'136 ]137 138 # Rename each parameter139 local_rename_dict = {140 "post_quant_conv": "post_quant_conv",141 "decoder.conv_in": "conv_in",142 "decoder.mid_block.attentions.0.group_norm": "blocks.1.norm",143 "decoder.mid_block.attentions.0.to_q": "blocks.1.transformer_blocks.0.to_q",144 "decoder.mid_block.attentions.0.to_k": "blocks.1.transformer_blocks.0.to_k",145 "decoder.mid_block.attentions.0.to_v": "blocks.1.transformer_blocks.0.to_v",146 "decoder.mid_block.attentions.0.to_out.0": "blocks.1.transformer_blocks.0.to_out",147 "decoder.mid_block.resnets.0.norm1": "blocks.0.norm1",148 "decoder.mid_block.resnets.0.conv1": "blocks.0.conv1",149 "decoder.mid_block.resnets.0.norm2": "blocks.0.norm2",150 "decoder.mid_block.resnets.0.conv2": "blocks.0.conv2",151 "decoder.mid_block.resnets.1.norm1": "blocks.2.norm1",152 "decoder.mid_block.resnets.1.conv1": "blocks.2.conv1",153 "decoder.mid_block.resnets.1.norm2": "blocks.2.norm2",154 "decoder.mid_block.resnets.1.conv2": "blocks.2.conv2",155 "decoder.conv_norm_out": "conv_norm_out",156 "decoder.conv_out": "conv_out",157 }158 name_list = sorted([name for name in state_dict])159 rename_dict = {}160 block_id = {"ResnetBlock": 2, "DownSampler": 2, "UpSampler": 2}161 last_block_type_with_id = {"ResnetBlock": "", "DownSampler": "", "UpSampler": ""}162 for name in name_list:163 names = name.split(".")164 name_prefix = ".".join(names[:-1])165 if name_prefix in local_rename_dict:166 rename_dict[name] = local_rename_dict[name_prefix] + "." + names[-1]167 elif name.startswith("decoder.up_blocks"):168 block_type = {"resnets": "ResnetBlock", "downsamplers": "DownSampler", "upsamplers": "UpSampler"}[names[3]]169 block_type_with_id = ".".join(names[:5])170 if block_type_with_id != last_block_type_with_id[block_type]:171 block_id[block_type] += 1172 last_block_type_with_id[block_type] = block_type_with_id173 while block_id[block_type] < len(block_types) and block_types[block_id[block_type]] != block_type:174 block_id[block_type] += 1175 block_type_with_id = ".".join(names[:5])176 names = ["blocks", str(block_id[block_type])] + names[5:]177 rename_dict[name] = ".".join(names)178 179 # Convert state_dict180 state_dict_ = {}181 for name, param in state_dict.items():182 if name in rename_dict:183 state_dict_[rename_dict[name]] = param184 return state_dict_185 186 def from_civitai(self, state_dict):187 rename_dict = {188 "first_stage_model.decoder.conv_in.bias": "conv_in.bias",189 "first_stage_model.decoder.conv_in.weight": "conv_in.weight",190 "first_stage_model.decoder.conv_out.bias": "conv_out.bias",191 "first_stage_model.decoder.conv_out.weight": "conv_out.weight",192 "first_stage_model.decoder.mid.attn_1.k.bias": "blocks.1.transformer_blocks.0.to_k.bias",193 "first_stage_model.decoder.mid.attn_1.k.weight": "blocks.1.transformer_blocks.0.to_k.weight",194 "first_stage_model.decoder.mid.attn_1.norm.bias": "blocks.1.norm.bias",195 "first_stage_model.decoder.mid.attn_1.norm.weight": "blocks.1.norm.weight",196 "first_stage_model.decoder.mid.attn_1.proj_out.bias": "blocks.1.transformer_blocks.0.to_out.bias", 197 "first_stage_model.decoder.mid.attn_1.proj_out.weight": "blocks.1.transformer_blocks.0.to_out.weight",198 "first_stage_model.decoder.mid.attn_1.q.bias": "blocks.1.transformer_blocks.0.to_q.bias",199 "first_stage_model.decoder.mid.attn_1.q.weight": "blocks.1.transformer_blocks.0.to_q.weight",200 "first_stage_model.decoder.mid.attn_1.v.bias": "blocks.1.transformer_blocks.0.to_v.bias",201 "first_stage_model.decoder.mid.attn_1.v.weight": "blocks.1.transformer_blocks.0.to_v.weight",202 "first_stage_model.decoder.mid.block_1.conv1.bias": "blocks.0.conv1.bias",203 "first_stage_model.decoder.mid.block_1.conv1.weight": "blocks.0.conv1.weight",204 "first_stage_model.decoder.mid.block_1.conv2.bias": "blocks.0.conv2.bias",205 "first_stage_model.decoder.mid.block_1.conv2.weight": "blocks.0.conv2.weight",206 "first_stage_model.decoder.mid.block_1.norm1.bias": "blocks.0.norm1.bias",207 "first_stage_model.decoder.mid.block_1.norm1.weight": "blocks.0.norm1.weight",208 "first_stage_model.decoder.mid.block_1.norm2.bias": "blocks.0.norm2.bias",209 "first_stage_model.decoder.mid.block_1.norm2.weight": "blocks.0.norm2.weight",210 "first_stage_model.decoder.mid.block_2.conv1.bias": "blocks.2.conv1.bias",211 "first_stage_model.decoder.mid.block_2.conv1.weight": "blocks.2.conv1.weight",212 "first_stage_model.decoder.mid.block_2.conv2.bias": "blocks.2.conv2.bias",213 "first_stage_model.decoder.mid.block_2.conv2.weight": "blocks.2.conv2.weight",214 "first_stage_model.decoder.mid.block_2.norm1.bias": "blocks.2.norm1.bias",215 "first_stage_model.decoder.mid.block_2.norm1.weight": "blocks.2.norm1.weight",216 "first_stage_model.decoder.mid.block_2.norm2.bias": "blocks.2.norm2.bias",217 "first_stage_model.decoder.mid.block_2.norm2.weight": "blocks.2.norm2.weight",218 "first_stage_model.decoder.norm_out.bias": "conv_norm_out.bias",219 "first_stage_model.decoder.norm_out.weight": "conv_norm_out.weight",220 "first_stage_model.decoder.up.0.block.0.conv1.bias": "blocks.15.conv1.bias",221 "first_stage_model.decoder.up.0.block.0.conv1.weight": "blocks.15.conv1.weight",222 "first_stage_model.decoder.up.0.block.0.conv2.bias": "blocks.15.conv2.bias",223 "first_stage_model.decoder.up.0.block.0.conv2.weight": "blocks.15.conv2.weight",224 "first_stage_model.decoder.up.0.block.0.nin_shortcut.bias": "blocks.15.conv_shortcut.bias",225 "first_stage_model.decoder.up.0.block.0.nin_shortcut.weight": "blocks.15.conv_shortcut.weight", 226 "first_stage_model.decoder.up.0.block.0.norm1.bias": "blocks.15.norm1.bias",227 "first_stage_model.decoder.up.0.block.0.norm1.weight": "blocks.15.norm1.weight",228 "first_stage_model.decoder.up.0.block.0.norm2.bias": "blocks.15.norm2.bias",229 "first_stage_model.decoder.up.0.block.0.norm2.weight": "blocks.15.norm2.weight",230 "first_stage_model.decoder.up.0.block.1.conv1.bias": "blocks.16.conv1.bias",231 "first_stage_model.decoder.up.0.block.1.conv1.weight": "blocks.16.conv1.weight",232 "first_stage_model.decoder.up.0.block.1.conv2.bias": "blocks.16.conv2.bias",233 "first_stage_model.decoder.up.0.block.1.conv2.weight": "blocks.16.conv2.weight",234 "first_stage_model.decoder.up.0.block.1.norm1.bias": "blocks.16.norm1.bias",235 "first_stage_model.decoder.up.0.block.1.norm1.weight": "blocks.16.norm1.weight",236 "first_stage_model.decoder.up.0.block.1.norm2.bias": "blocks.16.norm2.bias",237 "first_stage_model.decoder.up.0.block.1.norm2.weight": "blocks.16.norm2.weight",238 "first_stage_model.decoder.up.0.block.2.conv1.bias": "blocks.17.conv1.bias",239 "first_stage_model.decoder.up.0.block.2.conv1.weight": "blocks.17.conv1.weight",240 "first_stage_model.decoder.up.0.block.2.conv2.bias": "blocks.17.conv2.bias",241 "first_stage_model.decoder.up.0.block.2.conv2.weight": "blocks.17.conv2.weight",242 "first_stage_model.decoder.up.0.block.2.norm1.bias": "blocks.17.norm1.bias",243 "first_stage_model.decoder.up.0.block.2.norm1.weight": "blocks.17.norm1.weight",244 "first_stage_model.decoder.up.0.block.2.norm2.bias": "blocks.17.norm2.bias",245 "first_stage_model.decoder.up.0.block.2.norm2.weight": "blocks.17.norm2.weight",246 "first_stage_model.decoder.up.1.block.0.conv1.bias": "blocks.11.conv1.bias",247 "first_stage_model.decoder.up.1.block.0.conv1.weight": "blocks.11.conv1.weight",248 "first_stage_model.decoder.up.1.block.0.conv2.bias": "blocks.11.conv2.bias",249 "first_stage_model.decoder.up.1.block.0.conv2.weight": "blocks.11.conv2.weight",250 "first_stage_model.decoder.up.1.block.0.nin_shortcut.bias": "blocks.11.conv_shortcut.bias",251 "first_stage_model.decoder.up.1.block.0.nin_shortcut.weight": "blocks.11.conv_shortcut.weight", 252 "first_stage_model.decoder.up.1.block.0.norm1.bias": "blocks.11.norm1.bias",253 "first_stage_model.decoder.up.1.block.0.norm1.weight": "blocks.11.norm1.weight",254 "first_stage_model.decoder.up.1.block.0.norm2.bias": "blocks.11.norm2.bias",255 "first_stage_model.decoder.up.1.block.0.norm2.weight": "blocks.11.norm2.weight",256 "first_stage_model.decoder.up.1.block.1.conv1.bias": "blocks.12.conv1.bias",257 "first_stage_model.decoder.up.1.block.1.conv1.weight": "blocks.12.conv1.weight",258 "first_stage_model.decoder.up.1.block.1.conv2.bias": "blocks.12.conv2.bias",259 "first_stage_model.decoder.up.1.block.1.conv2.weight": "blocks.12.conv2.weight",260 "first_stage_model.decoder.up.1.block.1.norm1.bias": "blocks.12.norm1.bias",261 "first_stage_model.decoder.up.1.block.1.norm1.weight": "blocks.12.norm1.weight",262 "first_stage_model.decoder.up.1.block.1.norm2.bias": "blocks.12.norm2.bias",263 "first_stage_model.decoder.up.1.block.1.norm2.weight": "blocks.12.norm2.weight",264 "first_stage_model.decoder.up.1.block.2.conv1.bias": "blocks.13.conv1.bias",265 "first_stage_model.decoder.up.1.block.2.conv1.weight": "blocks.13.conv1.weight",266 "first_stage_model.decoder.up.1.block.2.conv2.bias": "blocks.13.conv2.bias",267 "first_stage_model.decoder.up.1.block.2.conv2.weight": "blocks.13.conv2.weight",268 "first_stage_model.decoder.up.1.block.2.norm1.bias": "blocks.13.norm1.bias",269 "first_stage_model.decoder.up.1.block.2.norm1.weight": "blocks.13.norm1.weight",270 "first_stage_model.decoder.up.1.block.2.norm2.bias": "blocks.13.norm2.bias",271 "first_stage_model.decoder.up.1.block.2.norm2.weight": "blocks.13.norm2.weight",272 "first_stage_model.decoder.up.1.upsample.conv.bias": "blocks.14.conv.bias",273 "first_stage_model.decoder.up.1.upsample.conv.weight": "blocks.14.conv.weight",274 "first_stage_model.decoder.up.2.block.0.conv1.bias": "blocks.7.conv1.bias",275 "first_stage_model.decoder.up.2.block.0.conv1.weight": "blocks.7.conv1.weight",276 "first_stage_model.decoder.up.2.block.0.conv2.bias": "blocks.7.conv2.bias",277 "first_stage_model.decoder.up.2.block.0.conv2.weight": "blocks.7.conv2.weight",278 "first_stage_model.decoder.up.2.block.0.norm1.bias": "blocks.7.norm1.bias",279 "first_stage_model.decoder.up.2.block.0.norm1.weight": "blocks.7.norm1.weight",280 "first_stage_model.decoder.up.2.block.0.norm2.bias": "blocks.7.norm2.bias",281 "first_stage_model.decoder.up.2.block.0.norm2.weight": "blocks.7.norm2.weight",282 "first_stage_model.decoder.up.2.block.1.conv1.bias": "blocks.8.conv1.bias",283 "first_stage_model.decoder.up.2.block.1.conv1.weight": "blocks.8.conv1.weight",284 "first_stage_model.decoder.up.2.block.1.conv2.bias": "blocks.8.conv2.bias",285 "first_stage_model.decoder.up.2.block.1.conv2.weight": "blocks.8.conv2.weight",286 "first_stage_model.decoder.up.2.block.1.norm1.bias": "blocks.8.norm1.bias",287 "first_stage_model.decoder.up.2.block.1.norm1.weight": "blocks.8.norm1.weight",288 "first_stage_model.decoder.up.2.block.1.norm2.bias": "blocks.8.norm2.bias",289 "first_stage_model.decoder.up.2.block.1.norm2.weight": "blocks.8.norm2.weight",290 "first_stage_model.decoder.up.2.block.2.conv1.bias": "blocks.9.conv1.bias",291 "first_stage_model.decoder.up.2.block.2.conv1.weight": "blocks.9.conv1.weight",292 "first_stage_model.decoder.up.2.block.2.conv2.bias": "blocks.9.conv2.bias",293 "first_stage_model.decoder.up.2.block.2.conv2.weight": "blocks.9.conv2.weight",294 "first_stage_model.decoder.up.2.block.2.norm1.bias": "blocks.9.norm1.bias",295 "first_stage_model.decoder.up.2.block.2.norm1.weight": "blocks.9.norm1.weight",296 "first_stage_model.decoder.up.2.block.2.norm2.bias": "blocks.9.norm2.bias",297 "first_stage_model.decoder.up.2.block.2.norm2.weight": "blocks.9.norm2.weight",298 "first_stage_model.decoder.up.2.upsample.conv.bias": "blocks.10.conv.bias",299 "first_stage_model.decoder.up.2.upsample.conv.weight": "blocks.10.conv.weight",300 "first_stage_model.decoder.up.3.block.0.conv1.bias": "blocks.3.conv1.bias",301 "first_stage_model.decoder.up.3.block.0.conv1.weight": "blocks.3.conv1.weight",302 "first_stage_model.decoder.up.3.block.0.conv2.bias": "blocks.3.conv2.bias",303 "first_stage_model.decoder.up.3.block.0.conv2.weight": "blocks.3.conv2.weight",304 "first_stage_model.decoder.up.3.block.0.norm1.bias": "blocks.3.norm1.bias",305 "first_stage_model.decoder.up.3.block.0.norm1.weight": "blocks.3.norm1.weight",306 "first_stage_model.decoder.up.3.block.0.norm2.bias": "blocks.3.norm2.bias",307 "first_stage_model.decoder.up.3.block.0.norm2.weight": "blocks.3.norm2.weight",308 "first_stage_model.decoder.up.3.block.1.conv1.bias": "blocks.4.conv1.bias",309 "first_stage_model.decoder.up.3.block.1.conv1.weight": "blocks.4.conv1.weight",310 "first_stage_model.decoder.up.3.block.1.conv2.bias": "blocks.4.conv2.bias",311 "first_stage_model.decoder.up.3.block.1.conv2.weight": "blocks.4.conv2.weight",312 "first_stage_model.decoder.up.3.block.1.norm1.bias": "blocks.4.norm1.bias",313 "first_stage_model.decoder.up.3.block.1.norm1.weight": "blocks.4.norm1.weight",314 "first_stage_model.decoder.up.3.block.1.norm2.bias": "blocks.4.norm2.bias",315 "first_stage_model.decoder.up.3.block.1.norm2.weight": "blocks.4.norm2.weight",316 "first_stage_model.decoder.up.3.block.2.conv1.bias": "blocks.5.conv1.bias",317 "first_stage_model.decoder.up.3.block.2.conv1.weight": "blocks.5.conv1.weight",318 "first_stage_model.decoder.up.3.block.2.conv2.bias": "blocks.5.conv2.bias",319 "first_stage_model.decoder.up.3.block.2.conv2.weight": "blocks.5.conv2.weight",320 "first_stage_model.decoder.up.3.block.2.norm1.bias": "blocks.5.norm1.bias",321 "first_stage_model.decoder.up.3.block.2.norm1.weight": "blocks.5.norm1.weight",322 "first_stage_model.decoder.up.3.block.2.norm2.bias": "blocks.5.norm2.bias",323 "first_stage_model.decoder.up.3.block.2.norm2.weight": "blocks.5.norm2.weight",324 "first_stage_model.decoder.up.3.upsample.conv.bias": "blocks.6.conv.bias",325 "first_stage_model.decoder.up.3.upsample.conv.weight": "blocks.6.conv.weight",326 "first_stage_model.post_quant_conv.bias": "post_quant_conv.bias",327 "first_stage_model.post_quant_conv.weight": "post_quant_conv.weight",328 }329 state_dict_ = {}330 for name in state_dict:331 if name in rename_dict:332 param = state_dict[name]333 if "transformer_blocks" in rename_dict[name]:334 param = param.squeeze()335 state_dict_[rename_dict[name]] = param336 return state_dict_337 