unet_1d.py 10.5 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
# Copyright 2023 The HuggingFace Team. All rights reserved.
2
3
4
5
6
7
8
9
10
11
12
13
14
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

15
16
17
18
19
20
21
from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
22
from ..utils import BaseOutput
23
from .embeddings import GaussianFourierProjection, TimestepEmbedding, Timesteps
24
from .modeling_utils import ModelMixin
25
from .unet_1d_blocks import get_down_block, get_mid_block, get_out_block, get_up_block
26
27
28
29
30


@dataclass
class UNet1DOutput(BaseOutput):
    """
Steven Liu's avatar
Steven Liu committed
31
32
    The output of [`UNet1DModel`].

33
34
    Args:
        sample (`torch.FloatTensor` of shape `(batch_size, num_channels, sample_size)`):
Steven Liu's avatar
Steven Liu committed
35
            The hidden states output from the last layer of the model.
36
37
38
39
40
41
42
    """

    sample: torch.FloatTensor


class UNet1DModel(ModelMixin, ConfigMixin):
    r"""
Steven Liu's avatar
Steven Liu committed
43
    A 1D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.
44

Steven Liu's avatar
Steven Liu committed
45
46
    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
    for all models (such as downloading or saving).
47
48

    Parameters:
49
        sample_size (`int`, *optional*): Default length of sample. Should be adaptable at runtime.
50
51
        in_channels (`int`, *optional*, defaults to 2): Number of channels in the input sample.
        out_channels (`int`, *optional*, defaults to 2): Number of channels in the output.
52
53
        extra_in_channels (`int`, *optional*, defaults to 0):
            Number of additional channels to be added to the input of the first down block. Useful for cases where the
Steven Liu's avatar
Steven Liu committed
54
            input data has more channels than what the model was initially designed for.
55
        time_embedding_type (`str`, *optional*, defaults to `"fourier"`): Type of time embedding to use.
Steven Liu's avatar
Steven Liu committed
56
57
58
        freq_shift (`float`, *optional*, defaults to 0.0): Frequency shift for Fourier time embedding.
        flip_sin_to_cos (`bool`, *optional*, defaults to `False`):
            Whether to flip sin to cos for Fourier time embedding.
59
        down_block_types (`Tuple[str]`, *optional*, defaults to `("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")`):
Steven Liu's avatar
Steven Liu committed
60
            Tuple of downsample block types.
61
        up_block_types (`Tuple[str]`, *optional*, defaults to `("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")`):
Steven Liu's avatar
Steven Liu committed
62
63
64
65
66
67
68
69
70
71
            Tuple of upsample block types.
        block_out_channels (`Tuple[int]`, *optional*, defaults to `(32, 32, 64)`):
            Tuple of block output channels.
        mid_block_type (`str`, *optional*, defaults to `"UNetMidBlock1D"`): Block type for middle of UNet.
        out_block_type (`str`, *optional*, defaults to `None`): Optional output processing block of UNet.
        act_fn (`str`, *optional*, defaults to `None`): Optional activation function in UNet blocks.
        norm_num_groups (`int`, *optional*, defaults to 8): The number of groups for normalization.
        layers_per_block (`int`, *optional*, defaults to 1): The number of layers per block.
        downsample_each_block (`int`, *optional*, defaults to `False`):
            Experimental feature for using a UNet without upsampling.
72
73
74
75
76
77
78
79
80
81
82
83
84
    """

    @register_to_config
    def __init__(
        self,
        sample_size: int = 65536,
        sample_rate: Optional[int] = None,
        in_channels: int = 2,
        out_channels: int = 2,
        extra_in_channels: int = 0,
        time_embedding_type: str = "fourier",
        flip_sin_to_cos: bool = True,
        use_timestep_embedding: bool = False,
85
        freq_shift: float = 0.0,
86
87
        down_block_types: Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D"),
        up_block_types: Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip"),
88
89
        mid_block_type: Tuple[str] = "UNetMidBlock1D",
        out_block_type: str = None,
90
        block_out_channels: Tuple[int] = (32, 32, 64),
91
92
93
94
        act_fn: str = None,
        norm_num_groups: int = 8,
        layers_per_block: int = 1,
        downsample_each_block: bool = False,
95
96
97
98
99
100
101
102
103
104
105
    ):
        super().__init__()
        self.sample_size = sample_size

        # time
        if time_embedding_type == "fourier":
            self.time_proj = GaussianFourierProjection(
                embedding_size=8, set_W_to_weight=False, log=False, flip_sin_to_cos=flip_sin_to_cos
            )
            timestep_input_dim = 2 * block_out_channels[0]
        elif time_embedding_type == "positional":
106
107
108
            self.time_proj = Timesteps(
                block_out_channels[0], flip_sin_to_cos=flip_sin_to_cos, downscale_freq_shift=freq_shift
            )
109
110
111
112
            timestep_input_dim = block_out_channels[0]

        if use_timestep_embedding:
            time_embed_dim = block_out_channels[0] * 4
113
114
115
116
117
118
            self.time_mlp = TimestepEmbedding(
                in_channels=timestep_input_dim,
                time_embed_dim=time_embed_dim,
                act_fn=act_fn,
                out_dim=block_out_channels[0],
            )
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133

        self.down_blocks = nn.ModuleList([])
        self.mid_block = None
        self.up_blocks = nn.ModuleList([])
        self.out_block = None

        # down
        output_channel = in_channels
        for i, down_block_type in enumerate(down_block_types):
            input_channel = output_channel
            output_channel = block_out_channels[i]

            if i == 0:
                input_channel += extra_in_channels

134
135
            is_final_block = i == len(block_out_channels) - 1

136
137
            down_block = get_down_block(
                down_block_type,
138
                num_layers=layers_per_block,
139
140
                in_channels=input_channel,
                out_channels=output_channel,
141
142
                temb_channels=block_out_channels[0],
                add_downsample=not is_final_block or downsample_each_block,
143
144
145
146
147
            )
            self.down_blocks.append(down_block)

        # mid
        self.mid_block = get_mid_block(
148
            mid_block_type,
149
            in_channels=block_out_channels[-1],
150
151
152
153
154
            mid_channels=block_out_channels[-1],
            out_channels=block_out_channels[-1],
            embed_dim=block_out_channels[0],
            num_layers=layers_per_block,
            add_downsample=downsample_each_block,
155
156
157
158
159
        )

        # up
        reversed_block_out_channels = list(reversed(block_out_channels))
        output_channel = reversed_block_out_channels[0]
160
161
162
163
164
        if out_block_type is None:
            final_upsample_channels = out_channels
        else:
            final_upsample_channels = block_out_channels[0]

165
166
        for i, up_block_type in enumerate(up_block_types):
            prev_output_channel = output_channel
167
168
169
170
171
            output_channel = (
                reversed_block_out_channels[i + 1] if i < len(up_block_types) - 1 else final_upsample_channels
            )

            is_final_block = i == len(block_out_channels) - 1
172
173
174

            up_block = get_up_block(
                up_block_type,
175
                num_layers=layers_per_block,
176
177
                in_channels=prev_output_channel,
                out_channels=output_channel,
178
179
                temb_channels=block_out_channels[0],
                add_upsample=not is_final_block,
180
181
182
183
            )
            self.up_blocks.append(up_block)
            prev_output_channel = output_channel

184
185
186
187
188
189
190
191
192
193
        # out
        num_groups_out = norm_num_groups if norm_num_groups is not None else min(block_out_channels[0] // 4, 32)
        self.out_block = get_out_block(
            out_block_type=out_block_type,
            num_groups_out=num_groups_out,
            embed_dim=block_out_channels[0],
            out_channels=out_channels,
            act_fn=act_fn,
            fc_dim=block_out_channels[-1] // 4,
        )
194
195
196
197
198
199
200
201

    def forward(
        self,
        sample: torch.FloatTensor,
        timestep: Union[torch.Tensor, float, int],
        return_dict: bool = True,
    ) -> Union[UNet1DOutput, Tuple]:
        r"""
Steven Liu's avatar
Steven Liu committed
202
203
        The [`UNet1DModel`] forward method.

204
        Args:
Steven Liu's avatar
Steven Liu committed
205
206
207
            sample (`torch.FloatTensor`):
                The noisy input tensor with the following shape `(batch_size, num_channels, sample_size)`.
            timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
208
209
210
211
            return_dict (`bool`, *optional*, defaults to `True`):
                Whether or not to return a [`~models.unet_1d.UNet1DOutput`] instead of a plain tuple.

        Returns:
Steven Liu's avatar
Steven Liu committed
212
213
214
            [`~models.unet_1d.UNet1DOutput`] or `tuple`:
                If `return_dict` is True, an [`~models.unet_1d.UNet1DOutput`] is returned, otherwise a `tuple` is
                returned where the first element is the sample tensor.
215
216
        """

217
218
219
220
221
222
223
224
225
226
227
228
229
        # 1. time
        timesteps = timestep
        if not torch.is_tensor(timesteps):
            timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
        elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
            timesteps = timesteps[None].to(sample.device)

        timestep_embed = self.time_proj(timesteps)
        if self.config.use_timestep_embedding:
            timestep_embed = self.time_mlp(timestep_embed)
        else:
            timestep_embed = timestep_embed[..., None]
            timestep_embed = timestep_embed.repeat([1, 1, sample.shape[2]]).to(sample.dtype)
230
            timestep_embed = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]))
231
232
233
234
235
236
237
238

        # 2. down
        down_block_res_samples = ()
        for downsample_block in self.down_blocks:
            sample, res_samples = downsample_block(hidden_states=sample, temb=timestep_embed)
            down_block_res_samples += res_samples

        # 3. mid
239
240
        if self.mid_block:
            sample = self.mid_block(sample, timestep_embed)
241
242
243
244
245

        # 4. up
        for i, upsample_block in enumerate(self.up_blocks):
            res_samples = down_block_res_samples[-1:]
            down_block_res_samples = down_block_res_samples[:-1]
246
247
248
249
250
            sample = upsample_block(sample, res_hidden_states_tuple=res_samples, temb=timestep_embed)

        # 5. post-process
        if self.out_block:
            sample = self.out_block(sample, timestep_embed)
251
252
253
254
255

        if not return_dict:
            return (sample,)

        return UNet1DOutput(sample=sample)