MCPcopy Create free account
hub / github.com/TencentARC/BrushNet / forward

Method forward

src/diffusers/models/unets/unet_2d.py:243–346  ·  view source on GitHub ↗

r""" The [`UNet2DModel`] forward method. Args: sample (`torch.FloatTensor`): The noisy input tensor with the following shape `(batch, channel, height, width)`. timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to deno

(
        self,
        sample: torch.FloatTensor,
        timestep: Union[torch.Tensor, float, int],
        class_labels: Optional[torch.Tensor] = None,
        return_dict: bool = True,
    )

Source from the content-addressed store, hash-verified

241 self.conv_out = nn.Conv2d(block_out_channels[0], out_channels, kernel_size=3, padding=1)
242
243 def forward(
244 self,
245 sample: torch.FloatTensor,
246 timestep: Union[torch.Tensor, float, int],
247 class_labels: Optional[torch.Tensor] = None,
248 return_dict: bool = True,
249 ) -> Union[UNet2DOutput, Tuple]:
250 r"""
251 The [`UNet2DModel`] forward method.
252
253 Args:
254 sample (`torch.FloatTensor`):
255 The noisy input tensor with the following shape `(batch, channel, height, width)`.
256 timestep (`torch.FloatTensor` or `float` or `int`): The number of timesteps to denoise an input.
257 class_labels (`torch.FloatTensor`, *optional*, defaults to `None`):
258 Optional class labels for conditioning. Their embeddings will be summed with the timestep embeddings.
259 return_dict (`bool`, *optional*, defaults to `True`):
260 Whether or not to return a [`~models.unet_2d.UNet2DOutput`] instead of a plain tuple.
261
262 Returns:
263 [`~models.unet_2d.UNet2DOutput`] or `tuple`:
264 If `return_dict` is True, an [`~models.unet_2d.UNet2DOutput`] is returned, otherwise a `tuple` is
265 returned where the first element is the sample tensor.
266 """
267 # 0. center input if necessary
268 if self.config.center_input_sample:
269 sample = 2 * sample - 1.0
270
271 # 1. time
272 timesteps = timestep
273 if not torch.is_tensor(timesteps):
274 timesteps = torch.tensor([timesteps], dtype=torch.long, device=sample.device)
275 elif torch.is_tensor(timesteps) and len(timesteps.shape) == 0:
276 timesteps = timesteps[None].to(sample.device)
277
278 # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
279 timesteps = timesteps * torch.ones(sample.shape[0], dtype=timesteps.dtype, device=timesteps.device)
280
281 t_emb = self.time_proj(timesteps)
282
283 # timesteps does not contain any weights and will always return f32 tensors
284 # but time_embedding might actually be running in fp16. so we need to cast here.
285 # there might be better ways to encapsulate this.
286 t_emb = t_emb.to(dtype=self.dtype)
287 emb = self.time_embedding(t_emb)
288
289 if self.class_embedding is not None:
290 if class_labels is None:
291 raise ValueError("class_labels should be provided when doing class conditioning")
292
293 if self.config.class_embed_type == "timestep":
294 class_labels = self.time_proj(class_labels)
295
296 class_emb = self.class_embedding(class_labels).to(dtype=self.dtype)
297 emb = emb + class_emb
298 elif self.class_embedding is None and class_labels is not None:
299 raise ValueError("class_embedding needs to be initialized in order to use class conditioning")
300

Callers

nothing calls this directly

Calls 2

UNet2DOutputClass · 0.70
toMethod · 0.45

Tested by

no test coverage detected