|
| 1 | +from typing import Dict, Union |
| 2 | + |
| 3 | +import torch |
| 4 | +import torch.nn as nn |
| 5 | + |
| 6 | +from ..configuration_utils import ConfigMixin, register_to_config |
| 7 | +from ..modeling_utils import ModelMixin |
| 8 | +from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps |
| 9 | +from .unet_blocks import UNetMidBlock2D, get_down_block, get_up_block |
| 10 | + |
| 11 | + |
| 12 | +class UNet2DModel(ModelMixin, ConfigMixin): |
| 13 | + @register_to_config |
| 14 | + def __init__( |
| 15 | + self, |
| 16 | + sample_size=None, |
| 17 | + in_channels=3, |
| 18 | + out_channels=3, |
| 19 | + center_input_sample=False, |
| 20 | + time_embedding_type="positional", |
| 21 | + freq_shift=0, |
| 22 | + flip_sin_to_cos=True, |
| 23 | + down_block_types=("DownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D", "AttnDownBlock2D"), |
| 24 | + up_block_types=("AttnUpBlock2D", "AttnUpBlock2D", "AttnUpBlock2D", "UpBlock2D"), |
| 25 | + block_out_channels=(224, 448, 672, 896), |
| 26 | + layers_per_block=2, |
| 27 | + mid_block_scale_factor=1, |
| 28 | + downsample_padding=1, |
| 29 | + act_fn="silu", |
| 30 | + attention_head_dim=8, |
| 31 | + norm_num_groups=32, |
| 32 | + norm_eps=1e-5, |
| 33 | + ): |
| 34 | + super().__init__() |
| 35 | + |
| 36 | + self.sample_size = sample_size |
| 37 | + time_embed_dim = block_out_channels[0] * 4 |
| 38 | + |
| 39 | + # input |
| 40 | + self.conv_in = nn.Conv2d(in_channels, block_out_channels[0], kernel_size=3, padding=(1, 1)) |
| 41 | + |
| 42 | + # time |
| 43 | + if time_embedding_type == "fourier": |
| 44 | + self.time_proj = GaussianFourierProjection(embedding_size=block_out_channels[0], scale=16) |
| 45 | + timestep_input_dim = 2 * block_out_channels[0] |
| 46 | + elif time_embedding_type == "positional": |
| 47 | + self.time_proj = Timesteps(block_out_channels[0], flip_sin_to_cos, freq_shift) |
| 48 | + timestep_input_dim = block_out_channels[0] |
| 49 | + |
| 50 | + self.time_embedding = TimestepEmbedding(timestep_input_dim, time_embed_dim) |
| 51 | + |
| 52 | + self.down_blocks = nn.ModuleList([]) |
| 53 | + self.mid_block = None |
| 54 | + self.up_blocks = nn.ModuleList([]) |
| 55 | + |
| 56 | + # down |
| 57 | + output_channel = block_out_channels[0] |
| 58 | + for i, down_block_type in enumerate(down_block_types): |
| 59 | + input_channel = output_channel |
| 60 | + output_channel = block_out_channels[i] |
| 61 | + is_final_block = i == len(block_out_channels) - 1 |
| 62 | + |
| 63 | + down_block = get_down_block( |
| 64 | + down_block_type, |
| 65 | + num_layers=layers_per_block, |
| 66 | + in_channels=input_channel, |
| 67 | + out_channels=output_channel, |
| 68 | + temb_channels=time_embed_dim, |
| 69 | + add_downsample=not is_final_block, |
| 70 | + resnet_eps=norm_eps, |
| 71 | + resnet_act_fn=act_fn, |
| 72 | + attn_num_head_channels=attention_head_dim, |
| 73 | + downsample_padding=downsample_padding, |
| 74 | + ) |
| 75 | + self.down_blocks.append(down_block) |
| 76 | + |
| 77 | + # mid |
| 78 | + self.mid_block = UNetMidBlock2D( |
| 79 | + in_channels=block_out_channels[-1], |
| 80 | + temb_channels=time_embed_dim, |
| 81 | + resnet_eps=norm_eps, |
| 82 | + resnet_act_fn=act_fn, |
| 83 | + output_scale_factor=mid_block_scale_factor, |
| 84 | + resnet_time_scale_shift="default", |
| 85 | + attn_num_head_channels=attention_head_dim, |
| 86 | + resnet_groups=norm_num_groups, |
| 87 | + ) |
| 88 | + |
| 89 | + # up |
| 90 | + reversed_block_out_channels = list(reversed(block_out_channels)) |
| 91 | + output_channel = reversed_block_out_channels[0] |
| 92 | + for i, up_block_type in enumerate(up_block_types): |
| 93 | + prev_output_channel = output_channel |
| 94 | + output_channel = reversed_block_out_channels[i] |
| 95 | + input_channel = reversed_block_out_channels[min(i + 1, len(block_out_channels) - 1)] |
| 96 | + |
| 97 | + is_final_block = i == len(block_out_channels) - 1 |
| 98 | + |
| 99 | + up_block = get_up_block( |
| 100 | + up_block_type, |
| 101 | + num_layers=layers_per_block + 1, |
| 102 | + in_channels=input_channel, |
| 103 | + out_channels=output_channel, |
| 104 | + prev_output_channel=prev_output_channel, |
| 105 | + temb_channels=time_embed_dim, |
| 106 | + add_upsample=not is_final_block, |
| 107 | + resnet_eps=norm_eps, |
| 108 | + resnet_act_fn=act_fn, |
| 109 | + attn_num_head_channels=attention_head_dim, |
| 110 | + ) |
| 111 | + self.up_blocks.append(up_block) |
| 112 | + prev_output_channel = output_channel |
| 113 | + |
| 114 | + # out |
| 115 | + num_groups_out = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4, 32) |
| 116 | + self.conv_norm_out = nn.GroupNorm(num_channels=block_out_channels[0], num_groups=num_groups_out, eps=norm_eps) |
| 117 | + self.conv_act = nn.SiLU() |
| 118 | + self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, 3, padding=1) |
| 119 | + |
| 120 | + def forward( |
| 121 | + self, sample: torch.FloatTensor, timestep: Union[torch.Tensor, float, int] |
| 122 | + ) -> Dict[str, torch.FloatTensor]: |
| 123 | + |
| 124 | + # 0. center input if necessary |
| 125 | + if self.config.center_input_sample: |
| 126 | + sample = 2 * sample - 1.0 |
| 127 | + |
| 128 | + # 1. time |
| 129 | + timesteps = timestep |
| 130 | + if not torch.is_tensor(timesteps): |
| 131 | + timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device) |
| 132 | + elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0: |
| 133 | + timesteps = timesteps[None].to(sample.device) |
| 134 | + |
| 135 | + t_emb = self.time_proj(timesteps) |
| 136 | + emb = self.time_embedding(t_emb) |
| 137 | + |
| 138 | + # 2. pre-process |
| 139 | + skip_sample = sample |
| 140 | + sample = self.conv_in(sample) |
| 141 | + |
| 142 | + # 3. down |
| 143 | + down_block_res_samples = (sample,) |
| 144 | + for downsample_block in self.down_blocks: |
| 145 | + if hasattr(downsample_block, "skip_conv"): |
| 146 | + sample, res_samples, skip_sample = downsample_block( |
| 147 | + hidden_states=sample, temb=emb, skip_sample=skip_sample |
| 148 | + ) |
| 149 | + else: |
| 150 | + sample, res_samples = downsample_block(hidden_states=sample, temb=emb) |
| 151 | + |
| 152 | + down_block_res_samples += res_samples |
| 153 | + |
| 154 | + # 4. mid |
| 155 | + sample = self.mid_block(sample, emb) |
| 156 | + |
| 157 | + # 5. up |
| 158 | + skip_sample = None |
| 159 | + for upsample_block in self.up_blocks: |
| 160 | + res_samples = down_block_res_samples[-len(upsample_block.resnets) :] |
| 161 | + down_block_res_samples = down_block_res_samples[: -len(upsample_block.resnets)] |
| 162 | + |
| 163 | + if hasattr(upsample_block, "skip_conv"): |
| 164 | + sample, skip_sample = upsample_block(sample, res_samples, emb, skip_sample) |
| 165 | + else: |
| 166 | + sample = upsample_block(sample, res_samples, emb) |
| 167 | + |
| 168 | + # 6. post-process |
| 169 | + sample = self.conv_norm_out(sample) |
| 170 | + sample = self.conv_act(sample) |
| 171 | + sample = self.conv_out(sample) |
| 172 | + |
| 173 | + if skip_sample is not None: |
| 174 | + sample += skip_sample |
| 175 | + |
| 176 | + if self.config.time_embedding_type == "fourier": |
| 177 | + timesteps = timesteps.reshape((sample.shape[0], *([1] * len(sample.shape[1:])))) |
| 178 | + sample = sample / timesteps |
| 179 | + |
| 180 | + output = {"sample": sample} |
| 181 | + |
| 182 | + return output |
0 commit comments