modelscope/DiffSynth-Painter
14
1import torch2from .sd_unet import ResnetBlock, DownSampler3from .sd_vae_decoder import VAEAttentionBlock4from .tiler import TileWorker5from einops import rearrange6 7 8class SDVAEEncoder(torch.nn.Module):9 def __init__(self):10 super().__init__()11 self.scaling_factor = 0.1821512 self.quant_conv = torch.nn.Conv2d(8, 8, kernel_size=1)13 self.conv_in = torch.nn.Conv2d(3, 128, kernel_size=3, padding=1)14 15 self.blocks = torch.nn.ModuleList([16 # DownEncoderBlock2D17 ResnetBlock(128, 128, eps=1e-6),18 ResnetBlock(128, 128, eps=1e-6),19 DownSampler(128, padding=0, extra_padding=True),20 # DownEncoderBlock2D21 ResnetBlock(128, 256, eps=1e-6),22 ResnetBlock(256, 256, eps=1e-6),23 DownSampler(256, padding=0, extra_padding=True),24 # DownEncoderBlock2D25 ResnetBlock(256, 512, eps=1e-6),26 ResnetBlock(512, 512, eps=1e-6),27 DownSampler(512, padding=0, extra_padding=True),28 # DownEncoderBlock2D29 ResnetBlock(512, 512, eps=1e-6),30 ResnetBlock(512, 512, eps=1e-6),31 # UNetMidBlock2D32 ResnetBlock(512, 512, eps=1e-6),33 VAEAttentionBlock(1, 512, 512, 1, eps=1e-6),34 ResnetBlock(512, 512, eps=1e-6),35 ])36 37 self.conv_norm_out = torch.nn.GroupNorm(num_channels=512, num_groups=32, eps=1e-6)38 self.conv_act = torch.nn.SiLU()39 self.conv_out = torch.nn.Conv2d(512, 8, kernel_size=3, padding=1)40 41 def tiled_forward(self, sample, tile_size=64, tile_stride=32):42 hidden_states = TileWorker().tiled_forward(43 lambda x: self.forward(x),44 sample,45 tile_size,46 tile_stride,47 tile_device=sample.device,48 tile_dtype=sample.dtype49 )50 return hidden_states51 52 def forward(self, sample, tiled=False, tile_size=64, tile_stride=32, **kwargs):53 original_dtype = sample.dtype54 sample = sample.to(dtype=next(iter(self.parameters())).dtype)55 # For VAE Decoder, we do not need to apply the tiler on each layer.56 if tiled:57 return self.tiled_forward(sample, tile_size=tile_size, tile_stride=tile_stride)58 59 # 1. pre-process60 hidden_states = self.conv_in(sample)61 time_emb = None62 text_emb = None63 res_stack = None64 65 # 2. blocks66 for i, block in enumerate(self.blocks):67 hidden_states, time_emb, text_emb, res_stack = block(hidden_states, time_emb, text_emb, res_stack)68 69 # 3. output70 hidden_states = self.conv_norm_out(hidden_states)71 hidden_states = self.conv_act(hidden_states)72 hidden_states = self.conv_out(hidden_states)73 hidden_states = self.quant_conv(hidden_states)74 hidden_states = hidden_states[:, :4]75 hidden_states *= self.scaling_factor76 hidden_states = hidden_states.to(original_dtype)77 78 return hidden_states79 80 def encode_video(self, sample, batch_size=8):81 B = sample.shape[0]82 hidden_states = []83 84 for i in range(0, sample.shape[2], batch_size):85 86 j = min(i + batch_size, sample.shape[2])87 sample_batch = rearrange(sample[:,:,i:j], "B C T H W -> (B T) C H W")88 89 hidden_states_batch = self(sample_batch)90 hidden_states_batch = rearrange(hidden_states_batch, "(B T) C H W -> B C T H W", B=B)91 92 hidden_states.append(hidden_states_batch)93 94 hidden_states = torch.concat(hidden_states, dim=2)95 return hidden_states96 97 @staticmethod98 def state_dict_converter():99 return SDVAEEncoderStateDictConverter()100 101 102class SDVAEEncoderStateDictConverter:103 def __init__(self):104 pass105 106 def from_diffusers(self, state_dict):107 # architecture108 block_types = [109 'ResnetBlock', 'ResnetBlock', 'DownSampler',110 'ResnetBlock', 'ResnetBlock', 'DownSampler',111 'ResnetBlock', 'ResnetBlock', 'DownSampler',112 'ResnetBlock', 'ResnetBlock',113 'ResnetBlock', 'VAEAttentionBlock', 'ResnetBlock'114 ]115 116 # Rename each parameter117 local_rename_dict = {118 "quant_conv": "quant_conv",119 "encoder.conv_in": "conv_in",120 "encoder.mid_block.attentions.0.group_norm": "blocks.12.norm",121 "encoder.mid_block.attentions.0.to_q": "blocks.12.transformer_blocks.0.to_q",122 "encoder.mid_block.attentions.0.to_k": "blocks.12.transformer_blocks.0.to_k",123 "encoder.mid_block.attentions.0.to_v": "blocks.12.transformer_blocks.0.to_v",124 "encoder.mid_block.attentions.0.to_out.0": "blocks.12.transformer_blocks.0.to_out",125 "encoder.mid_block.resnets.0.norm1": "blocks.11.norm1",126 "encoder.mid_block.resnets.0.conv1": "blocks.11.conv1",127 "encoder.mid_block.resnets.0.norm2": "blocks.11.norm2",128 "encoder.mid_block.resnets.0.conv2": "blocks.11.conv2",129 "encoder.mid_block.resnets.1.norm1": "blocks.13.norm1",130 "encoder.mid_block.resnets.1.conv1": "blocks.13.conv1",131 "encoder.mid_block.resnets.1.norm2": "blocks.13.norm2",132 "encoder.mid_block.resnets.1.conv2": "blocks.13.conv2",133 "encoder.conv_norm_out": "conv_norm_out",134 "encoder.conv_out": "conv_out",135 }136 name_list = sorted([name for name in state_dict])137 rename_dict = {}138 block_id = {"ResnetBlock": -1, "DownSampler": -1, "UpSampler": -1}139 last_block_type_with_id = {"ResnetBlock": "", "DownSampler": "", "UpSampler": ""}140 for name in name_list:141 names = name.split(".")142 name_prefix = ".".join(names[:-1])143 if name_prefix in local_rename_dict:144 rename_dict[name] = local_rename_dict[name_prefix] + "." + names[-1]145 elif name.startswith("encoder.down_blocks"):146 block_type = {"resnets": "ResnetBlock", "downsamplers": "DownSampler", "upsamplers": "UpSampler"}[names[3]]147 block_type_with_id = ".".join(names[:5])148 if block_type_with_id != last_block_type_with_id[block_type]:149 block_id[block_type] += 1150 last_block_type_with_id[block_type] = block_type_with_id151 while block_id[block_type] < len(block_types) and block_types[block_id[block_type]] != block_type:152 block_id[block_type] += 1153 block_type_with_id = ".".join(names[:5])154 names = ["blocks", str(block_id[block_type])] + names[5:]155 rename_dict[name] = ".".join(names)156 157 # Convert state_dict158 state_dict_ = {}159 for name, param in state_dict.items():160 if name in rename_dict:161 state_dict_[rename_dict[name]] = param162 return state_dict_163 164 def from_civitai(self, state_dict):165 rename_dict = {166 "first_stage_model.encoder.conv_in.bias": "conv_in.bias",167 "first_stage_model.encoder.conv_in.weight": "conv_in.weight",168 "first_stage_model.encoder.conv_out.bias": "conv_out.bias",169 "first_stage_model.encoder.conv_out.weight": "conv_out.weight",170 "first_stage_model.encoder.down.0.block.0.conv1.bias": "blocks.0.conv1.bias",171 "first_stage_model.encoder.down.0.block.0.conv1.weight": "blocks.0.conv1.weight",172 "first_stage_model.encoder.down.0.block.0.conv2.bias": "blocks.0.conv2.bias",173 "first_stage_model.encoder.down.0.block.0.conv2.weight": "blocks.0.conv2.weight",174 "first_stage_model.encoder.down.0.block.0.norm1.bias": "blocks.0.norm1.bias",175 "first_stage_model.encoder.down.0.block.0.norm1.weight": "blocks.0.norm1.weight",176 "first_stage_model.encoder.down.0.block.0.norm2.bias": "blocks.0.norm2.bias",177 "first_stage_model.encoder.down.0.block.0.norm2.weight": "blocks.0.norm2.weight",178 "first_stage_model.encoder.down.0.block.1.conv1.bias": "blocks.1.conv1.bias",179 "first_stage_model.encoder.down.0.block.1.conv1.weight": "blocks.1.conv1.weight",180 "first_stage_model.encoder.down.0.block.1.conv2.bias": "blocks.1.conv2.bias",181 "first_stage_model.encoder.down.0.block.1.conv2.weight": "blocks.1.conv2.weight",182 "first_stage_model.encoder.down.0.block.1.norm1.bias": "blocks.1.norm1.bias",183 "first_stage_model.encoder.down.0.block.1.norm1.weight": "blocks.1.norm1.weight",184 "first_stage_model.encoder.down.0.block.1.norm2.bias": "blocks.1.norm2.bias",185 "first_stage_model.encoder.down.0.block.1.norm2.weight": "blocks.1.norm2.weight",186 "first_stage_model.encoder.down.0.downsample.conv.bias": "blocks.2.conv.bias",187 "first_stage_model.encoder.down.0.downsample.conv.weight": "blocks.2.conv.weight",188 "first_stage_model.encoder.down.1.block.0.conv1.bias": "blocks.3.conv1.bias",189 "first_stage_model.encoder.down.1.block.0.conv1.weight": "blocks.3.conv1.weight",190 "first_stage_model.encoder.down.1.block.0.conv2.bias": "blocks.3.conv2.bias",191 "first_stage_model.encoder.down.1.block.0.conv2.weight": "blocks.3.conv2.weight",192 "first_stage_model.encoder.down.1.block.0.nin_shortcut.bias": "blocks.3.conv_shortcut.bias",193 "first_stage_model.encoder.down.1.block.0.nin_shortcut.weight": "blocks.3.conv_shortcut.weight",194 "first_stage_model.encoder.down.1.block.0.norm1.bias": "blocks.3.norm1.bias",195 "first_stage_model.encoder.down.1.block.0.norm1.weight": "blocks.3.norm1.weight",196 "first_stage_model.encoder.down.1.block.0.norm2.bias": "blocks.3.norm2.bias",197 "first_stage_model.encoder.down.1.block.0.norm2.weight": "blocks.3.norm2.weight",198 "first_stage_model.encoder.down.1.block.1.conv1.bias": "blocks.4.conv1.bias",199 "first_stage_model.encoder.down.1.block.1.conv1.weight": "blocks.4.conv1.weight",200 "first_stage_model.encoder.down.1.block.1.conv2.bias": "blocks.4.conv2.bias",201 "first_stage_model.encoder.down.1.block.1.conv2.weight": "blocks.4.conv2.weight",202 "first_stage_model.encoder.down.1.block.1.norm1.bias": "blocks.4.norm1.bias",203 "first_stage_model.encoder.down.1.block.1.norm1.weight": "blocks.4.norm1.weight",204 "first_stage_model.encoder.down.1.block.1.norm2.bias": "blocks.4.norm2.bias",205 "first_stage_model.encoder.down.1.block.1.norm2.weight": "blocks.4.norm2.weight",206 "first_stage_model.encoder.down.1.downsample.conv.bias": "blocks.5.conv.bias",207 "first_stage_model.encoder.down.1.downsample.conv.weight": "blocks.5.conv.weight",208 "first_stage_model.encoder.down.2.block.0.conv1.bias": "blocks.6.conv1.bias",209 "first_stage_model.encoder.down.2.block.0.conv1.weight": "blocks.6.conv1.weight",210 "first_stage_model.encoder.down.2.block.0.conv2.bias": "blocks.6.conv2.bias",211 "first_stage_model.encoder.down.2.block.0.conv2.weight": "blocks.6.conv2.weight",212 "first_stage_model.encoder.down.2.block.0.nin_shortcut.bias": "blocks.6.conv_shortcut.bias",213 "first_stage_model.encoder.down.2.block.0.nin_shortcut.weight": "blocks.6.conv_shortcut.weight",214 "first_stage_model.encoder.down.2.block.0.norm1.bias": "blocks.6.norm1.bias",215 "first_stage_model.encoder.down.2.block.0.norm1.weight": "blocks.6.norm1.weight",216 "first_stage_model.encoder.down.2.block.0.norm2.bias": "blocks.6.norm2.bias",217 "first_stage_model.encoder.down.2.block.0.norm2.weight": "blocks.6.norm2.weight",218 "first_stage_model.encoder.down.2.block.1.conv1.bias": "blocks.7.conv1.bias",219 "first_stage_model.encoder.down.2.block.1.conv1.weight": "blocks.7.conv1.weight",220 "first_stage_model.encoder.down.2.block.1.conv2.bias": "blocks.7.conv2.bias",221 "first_stage_model.encoder.down.2.block.1.conv2.weight": "blocks.7.conv2.weight",222 "first_stage_model.encoder.down.2.block.1.norm1.bias": "blocks.7.norm1.bias",223 "first_stage_model.encoder.down.2.block.1.norm1.weight": "blocks.7.norm1.weight",224 "first_stage_model.encoder.down.2.block.1.norm2.bias": "blocks.7.norm2.bias",225 "first_stage_model.encoder.down.2.block.1.norm2.weight": "blocks.7.norm2.weight",226 "first_stage_model.encoder.down.2.downsample.conv.bias": "blocks.8.conv.bias",227 "first_stage_model.encoder.down.2.downsample.conv.weight": "blocks.8.conv.weight",228 "first_stage_model.encoder.down.3.block.0.conv1.bias": "blocks.9.conv1.bias",229 "first_stage_model.encoder.down.3.block.0.conv1.weight": "blocks.9.conv1.weight",230 "first_stage_model.encoder.down.3.block.0.conv2.bias": "blocks.9.conv2.bias",231 "first_stage_model.encoder.down.3.block.0.conv2.weight": "blocks.9.conv2.weight",232 "first_stage_model.encoder.down.3.block.0.norm1.bias": "blocks.9.norm1.bias",233 "first_stage_model.encoder.down.3.block.0.norm1.weight": "blocks.9.norm1.weight",234 "first_stage_model.encoder.down.3.block.0.norm2.bias": "blocks.9.norm2.bias",235 "first_stage_model.encoder.down.3.block.0.norm2.weight": "blocks.9.norm2.weight",236 "first_stage_model.encoder.down.3.block.1.conv1.bias": "blocks.10.conv1.bias",237 "first_stage_model.encoder.down.3.block.1.conv1.weight": "blocks.10.conv1.weight",238 "first_stage_model.encoder.down.3.block.1.conv2.bias": "blocks.10.conv2.bias",239 "first_stage_model.encoder.down.3.block.1.conv2.weight": "blocks.10.conv2.weight",240 "first_stage_model.encoder.down.3.block.1.norm1.bias": "blocks.10.norm1.bias",241 "first_stage_model.encoder.down.3.block.1.norm1.weight": "blocks.10.norm1.weight",242 "first_stage_model.encoder.down.3.block.1.norm2.bias": "blocks.10.norm2.bias",243 "first_stage_model.encoder.down.3.block.1.norm2.weight": "blocks.10.norm2.weight",244 "first_stage_model.encoder.mid.attn_1.k.bias": "blocks.12.transformer_blocks.0.to_k.bias",245 "first_stage_model.encoder.mid.attn_1.k.weight": "blocks.12.transformer_blocks.0.to_k.weight",246 "first_stage_model.encoder.mid.attn_1.norm.bias": "blocks.12.norm.bias",247 "first_stage_model.encoder.mid.attn_1.norm.weight": "blocks.12.norm.weight",248 "first_stage_model.encoder.mid.attn_1.proj_out.bias": "blocks.12.transformer_blocks.0.to_out.bias", 249 "first_stage_model.encoder.mid.attn_1.proj_out.weight": "blocks.12.transformer_blocks.0.to_out.weight", 250 "first_stage_model.encoder.mid.attn_1.q.bias": "blocks.12.transformer_blocks.0.to_q.bias",251 "first_stage_model.encoder.mid.attn_1.q.weight": "blocks.12.transformer_blocks.0.to_q.weight",252 "first_stage_model.encoder.mid.attn_1.v.bias": "blocks.12.transformer_blocks.0.to_v.bias",253 "first_stage_model.encoder.mid.attn_1.v.weight": "blocks.12.transformer_blocks.0.to_v.weight",254 "first_stage_model.encoder.mid.block_1.conv1.bias": "blocks.11.conv1.bias",255 "first_stage_model.encoder.mid.block_1.conv1.weight": "blocks.11.conv1.weight",256 "first_stage_model.encoder.mid.block_1.conv2.bias": "blocks.11.conv2.bias",257 "first_stage_model.encoder.mid.block_1.conv2.weight": "blocks.11.conv2.weight",258 "first_stage_model.encoder.mid.block_1.norm1.bias": "blocks.11.norm1.bias",259 "first_stage_model.encoder.mid.block_1.norm1.weight": "blocks.11.norm1.weight",260 "first_stage_model.encoder.mid.block_1.norm2.bias": "blocks.11.norm2.bias",261 "first_stage_model.encoder.mid.block_1.norm2.weight": "blocks.11.norm2.weight",262 "first_stage_model.encoder.mid.block_2.conv1.bias": "blocks.13.conv1.bias",263 "first_stage_model.encoder.mid.block_2.conv1.weight": "blocks.13.conv1.weight",264 "first_stage_model.encoder.mid.block_2.conv2.bias": "blocks.13.conv2.bias",265 "first_stage_model.encoder.mid.block_2.conv2.weight": "blocks.13.conv2.weight",266 "first_stage_model.encoder.mid.block_2.norm1.bias": "blocks.13.norm1.bias",267 "first_stage_model.encoder.mid.block_2.norm1.weight": "blocks.13.norm1.weight",268 "first_stage_model.encoder.mid.block_2.norm2.bias": "blocks.13.norm2.bias",269 "first_stage_model.encoder.mid.block_2.norm2.weight": "blocks.13.norm2.weight",270 "first_stage_model.encoder.norm_out.bias": "conv_norm_out.bias",271 "first_stage_model.encoder.norm_out.weight": "conv_norm_out.weight",272 "first_stage_model.quant_conv.bias": "quant_conv.bias",273 "first_stage_model.quant_conv.weight": "quant_conv.weight",274 }275 state_dict_ = {}276 for name in state_dict:277 if name in rename_dict:278 param = state_dict[name]279 if "transformer_blocks" in rename_dict[name]:280 param = param.squeeze()281 state_dict_[rename_dict[name]] = param282 return state_dict_283 