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