r"""Downsample2D a batch of 2D images with the given filter. Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the specifie
(
hidden_states: torch.Tensor,
kernel: Optional[torch.Tensor] = None,
factor: int = 2,
gain: float = 1,
)
| 354 | |
| 355 | |
| 356 | def downsample_2d( |
| 357 | hidden_states: torch.Tensor, |
| 358 | kernel: Optional[torch.Tensor] = None, |
| 359 | factor: int = 2, |
| 360 | gain: float = 1, |
| 361 | ) -> torch.Tensor: |
| 362 | r"""Downsample2D a batch of 2D images with the given filter. |
| 363 | Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the |
| 364 | given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the |
| 365 | specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its |
| 366 | shape is a multiple of the downsampling factor. |
| 367 | |
| 368 | Args: |
| 369 | hidden_states (`torch.Tensor`) |
| 370 | Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`. |
| 371 | kernel (`torch.Tensor`, *optional*): |
| 372 | FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which |
| 373 | corresponds to average pooling. |
| 374 | factor (`int`, *optional*, default to `2`): |
| 375 | Integer downsampling factor. |
| 376 | gain (`float`, *optional*, default to `1.0`): |
| 377 | Scaling factor for signal magnitude. |
| 378 | |
| 379 | Returns: |
| 380 | output (`torch.Tensor`): |
| 381 | Tensor of the shape `[N, C, H // factor, W // factor]` |
| 382 | """ |
| 383 | |
| 384 | assert isinstance(factor, int) and factor >= 1 |
| 385 | if kernel is None: |
| 386 | kernel = [1] * factor |
| 387 | |
| 388 | kernel = torch.tensor(kernel, dtype=torch.float32) |
| 389 | if kernel.ndim == 1: |
| 390 | kernel = torch.outer(kernel, kernel) |
| 391 | kernel /= torch.sum(kernel) |
| 392 | |
| 393 | kernel = kernel * gain |
| 394 | pad_value = kernel.shape[0] - factor |
| 395 | output = upfirdn2d_native( |
| 396 | hidden_states, |
| 397 | kernel.to(device=hidden_states.device), |
| 398 | down=factor, |
| 399 | pad=((pad_value + 1) // 2, pad_value // 2), |
| 400 | ) |
| 401 | return output |
no test coverage detected