Skip to content

UNet1DModel

The UNet model was originally introduced by Ronneberger et al. for biomedical image segmentation, but it is also commonly used in 🤗 Diffusers because it outputs images that are the same size as the input. It is one of the most important components of a diffusion system because it facilitates the actual diffusion process. There are several variants of the UNet model in 🤗 Diffusers, depending on it's number of dimensions and whether it is a conditional model or not. This is a 1D UNet model.

The abstract from the paper is:

There is large consent that successful training of deep networks requires many thousand annotated training samples. In this paper, we present a network and training strategy that relies on the strong use of data augmentation to use the available annotated samples more efficiently. The architecture consists of a contracting path to capture context and a symmetric expanding path that enables precise localization. We show that such a network can be trained end-to-end from very few images and outperforms the prior best method (a sliding-window convolutional network) on the ISBI challenge for segmentation of neuronal structures in electron microscopic stacks. Using the same network trained on transmitted light microscopy images (phase contrast and DIC) we won the ISBI cell tracking challenge 2015 in these categories by a large margin. Moreover, the network is fast. Segmentation of a 512x512 image takes less than a second on a recent GPU. The full implementation (based on Caffe) and the trained networks are available at http://lmb.informatik.uni-freiburg.de/people/ronneber/u-net.

mindone.diffusers.UNet1DModel

Bases: ModelMixin, ConfigMixin

A 1D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.

This model inherits from [ModelMixin]. Check the superclass documentation for it's generic methods implemented for all models (such as downloading or saving).

PARAMETER DESCRIPTION
sample_size

Default length of sample. Should be adaptable at runtime.

TYPE: `int`, *optional* DEFAULT: 65536

in_channels

Number of channels in the input sample.

TYPE: `int`, *optional*, defaults to 2 DEFAULT: 2

out_channels

Number of channels in the output.

TYPE: `int`, *optional*, defaults to 2 DEFAULT: 2

extra_in_channels

Number of additional channels to be added to the input of the first down block. Useful for cases where the input data has more channels than what the model was initially designed for.

TYPE: `int`, *optional*, defaults to 0 DEFAULT: 0

time_embedding_type

Type of time embedding to use.

TYPE: `str`, *optional*, defaults to `"fourier"` DEFAULT: 'fourier'

freq_shift

Frequency shift for Fourier time embedding.

TYPE: `float`, *optional*, defaults to 0.0 DEFAULT: 0.0

flip_sin_to_cos

Whether to flip sin to cos for Fourier time embedding.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: True

down_block_types

Tuple of downsample block types.

TYPE: `Tuple[str]`, *optional*, defaults to `("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")` DEFAULT: ('DownBlock1DNoSkip', 'DownBlock1D', 'AttnDownBlock1D')

up_block_types

Tuple of upsample block types.

TYPE: `Tuple[str]`, *optional*, defaults to `("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")` DEFAULT: ('AttnUpBlock1D', 'UpBlock1D', 'UpBlock1DNoSkip')

block_out_channels

Tuple of block output channels.

TYPE: `Tuple[int]`, *optional*, defaults to `(32, 32, 64)` DEFAULT: (32, 32, 64)

mid_block_type

Block type for middle of UNet.

TYPE: `str`, *optional*, defaults to `"UNetMidBlock1D"` DEFAULT: 'UNetMidBlock1D'

out_block_type

Optional output processing block of UNet.

TYPE: `str`, *optional*, defaults to `None` DEFAULT: None

act_fn

Optional activation function in UNet blocks.

TYPE: `str`, *optional*, defaults to `None` DEFAULT: None

norm_num_groups

The number of groups for normalization.

TYPE: `int`, *optional*, defaults to 8 DEFAULT: 8

layers_per_block

The number of layers per block.

TYPE: `int`, *optional*, defaults to 1 DEFAULT: 1

downsample_each_block

Experimental feature for using a UNet without upsampling.

TYPE: `int`, *optional*, defaults to `False` DEFAULT: False

Source code in mindone/diffusers/models/unets/unet_1d.py
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
class UNet1DModel(ModelMixin, ConfigMixin):
    r"""
    A 1D UNet model that takes a noisy sample and a timestep and returns a sample shaped output.

    This model inherits from [`ModelMixin`]. Check the superclass documentation for it's generic methods implemented
    for all models (such as downloading or saving).

    Parameters:
        sample_size (`int`, *optional*): Default length of sample. Should be adaptable at runtime.
        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.
        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
            input data has more channels than what the model was initially designed for.
        time_embedding_type (`str`, *optional*, defaults to `"fourier"`): Type of time embedding to use.
        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.
        down_block_types (`Tuple[str]`, *optional*, defaults to `("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D")`):
            Tuple of downsample block types.
        up_block_types (`Tuple[str]`, *optional*, defaults to `("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip")`):
            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.
    """

    @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,
        freq_shift: float = 0.0,
        down_block_types: Tuple[str] = ("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D"),
        up_block_types: Tuple[str] = ("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip"),
        mid_block_type: Tuple[str] = "UNetMidBlock1D",
        out_block_type: str = None,
        block_out_channels: Tuple[int] = (32, 32, 64),
        act_fn: str = None,
        norm_num_groups: int = 8,
        layers_per_block: int = 1,
        downsample_each_block: bool = False,
    ):
        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":
            self.time_proj = Timesteps(
                block_out_channels[0], flip_sin_to_cos=flip_sin_to_cos, downscale_freq_shift=freq_shift
            )
            timestep_input_dim = block_out_channels[0]

        if use_timestep_embedding:
            time_embed_dim = block_out_channels[0] * 4
            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],
            )

        # down
        down_blocks = []
        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

            is_final_block = i == len(block_out_channels) - 1

            down_block = get_down_block(
                down_block_type,
                num_layers=layers_per_block,
                in_channels=input_channel,
                out_channels=output_channel,
                temb_channels=block_out_channels[0],
                add_downsample=not is_final_block or downsample_each_block,
            )
            down_blocks.append(down_block)
        self.down_blocks = nn.CellList(down_blocks)

        # mid
        self.mid_block = get_mid_block(
            mid_block_type,
            in_channels=block_out_channels[-1],
            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,
        )

        # up
        up_blocks = []
        reversed_block_out_channels = list(reversed(block_out_channels))
        output_channel = reversed_block_out_channels[0]
        if out_block_type is None:
            final_upsample_channels = out_channels
        else:
            final_upsample_channels = block_out_channels[0]

        for i, up_block_type in enumerate(up_block_types):
            prev_output_channel = output_channel
            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

            up_block = get_up_block(
                up_block_type,
                num_layers=layers_per_block,
                in_channels=prev_output_channel,
                out_channels=output_channel,
                temb_channels=block_out_channels[0],
                add_upsample=not is_final_block,
            )
            up_blocks.append(up_block)
            prev_output_channel = output_channel
        self.up_blocks = nn.CellList(up_blocks)

        # 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,
        )

        self.use_timestep_embedding = self.config.use_timestep_embedding

    def construct(
        self,
        sample: ms.Tensor,
        timestep: Union[ms.Tensor, float, int],
        return_dict: bool = False,
    ) -> Union[UNet1DOutput, Tuple]:
        r"""
        The [`UNet1DModel`] forward method.

        Args:
            sample (`ms.Tensor`):
                The noisy input tensor with the following shape `(batch_size, num_channels, sample_size)`.
            timestep (`ms.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
            return_dict (`bool`, *optional*, defaults to `False`):
                Whether or not to return a [`~models.unets.unet_1d.UNet1DOutput`] instead of a plain tuple.

        Returns:
            [`~models.unets.unet_1d.UNet1DOutput`] or `tuple`:
                If `return_dict` is True, an [`~models.unets.unet_1d.UNet1DOutput`] is returned, otherwise a `tuple` is
                returned where the first element is the sample tensor.
        """

        # 1. time
        timesteps = timestep
        if not ops.is_tensor(timesteps):
            timesteps = ms.tensor([timesteps], dtype=ms.int64)
        elif ops.is_tensor(timesteps) and len(timesteps.shape) == 0:
            timesteps = timesteps[None]

        timestep_embed = self.time_proj(timesteps)

        # timesteps does not contain any weights and will always return f32 tensors
        # but time_embedding might actually be running in fp16. so we need to cast here.
        # there might be better ways to encapsulate this.
        timestep_embed = timestep_embed.to(dtype=self.dtype)
        if self.use_timestep_embedding:
            timestep_embed = self.time_mlp(timestep_embed)
        else:
            timestep_embed = timestep_embed[..., None]
            timestep_embed = timestep_embed.tile((1, 1, sample.shape[2])).to(sample.dtype)
            timestep_embed = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]))

        # 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
        if self.mid_block:
            sample = self.mid_block(sample, timestep_embed)

        # 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]
            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)

        if not return_dict:
            return (sample,)

        return UNet1DOutput(sample=sample)

mindone.diffusers.UNet1DModel.construct(sample, timestep, return_dict=False)

The [UNet1DModel] forward method.

PARAMETER DESCRIPTION
sample

The noisy input tensor with the following shape (batch_size, num_channels, sample_size).

TYPE: `ms.Tensor`

timestep

The number of timesteps to denoise an input.

TYPE: `ms.Tensor` or `float` or `int`

return_dict

Whether or not to return a [~models.unets.unet_1d.UNet1DOutput] instead of a plain tuple.

TYPE: `bool`, *optional*, defaults to `False` DEFAULT: False

RETURNS DESCRIPTION
Union[UNet1DOutput, Tuple]

[~models.unets.unet_1d.UNet1DOutput] or tuple: If return_dict is True, an [~models.unets.unet_1d.UNet1DOutput] is returned, otherwise a tuple is returned where the first element is the sample tensor.

Source code in mindone/diffusers/models/unets/unet_1d.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def construct(
    self,
    sample: ms.Tensor,
    timestep: Union[ms.Tensor, float, int],
    return_dict: bool = False,
) -> Union[UNet1DOutput, Tuple]:
    r"""
    The [`UNet1DModel`] forward method.

    Args:
        sample (`ms.Tensor`):
            The noisy input tensor with the following shape `(batch_size, num_channels, sample_size)`.
        timestep (`ms.Tensor` or `float` or `int`): The number of timesteps to denoise an input.
        return_dict (`bool`, *optional*, defaults to `False`):
            Whether or not to return a [`~models.unets.unet_1d.UNet1DOutput`] instead of a plain tuple.

    Returns:
        [`~models.unets.unet_1d.UNet1DOutput`] or `tuple`:
            If `return_dict` is True, an [`~models.unets.unet_1d.UNet1DOutput`] is returned, otherwise a `tuple` is
            returned where the first element is the sample tensor.
    """

    # 1. time
    timesteps = timestep
    if not ops.is_tensor(timesteps):
        timesteps = ms.tensor([timesteps], dtype=ms.int64)
    elif ops.is_tensor(timesteps) and len(timesteps.shape) == 0:
        timesteps = timesteps[None]

    timestep_embed = self.time_proj(timesteps)

    # timesteps does not contain any weights and will always return f32 tensors
    # but time_embedding might actually be running in fp16. so we need to cast here.
    # there might be better ways to encapsulate this.
    timestep_embed = timestep_embed.to(dtype=self.dtype)
    if self.use_timestep_embedding:
        timestep_embed = self.time_mlp(timestep_embed)
    else:
        timestep_embed = timestep_embed[..., None]
        timestep_embed = timestep_embed.tile((1, 1, sample.shape[2])).to(sample.dtype)
        timestep_embed = timestep_embed.broadcast_to((sample.shape[:1] + timestep_embed.shape[1:]))

    # 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
    if self.mid_block:
        sample = self.mid_block(sample, timestep_embed)

    # 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]
        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)

    if not return_dict:
        return (sample,)

    return UNet1DOutput(sample=sample)

mindone.diffusers.models.unets.unet_1d.UNet1DOutput dataclass

Bases: BaseOutput

The output of [UNet1DModel].

PARAMETER DESCRIPTION
sample

The hidden states output from the last layer of the model.

TYPE: `mindspore.float32` of shape `(batch_size, num_channels, sample_size)`

Source code in mindone/diffusers/models/unets/unet_1d.py
28
29
30
31
32
33
34
35
36
37
38
@dataclass
class UNet1DOutput(BaseOutput):
    """
    The output of [`UNet1DModel`].

    Args:
        sample (`mindspore.float32` of shape `(batch_size, num_channels, sample_size)`):
            The hidden states output from the last layer of the model.
    """

    sample: ms.Tensor