MCPcopy Create free account
hub / github.com/YesianRohn/TextSSR / downsample_2d

Function downsample_2d

diffusers/src/diffusers/models/downsampling.py:356–401  ·  view source on GitHub ↗

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

Source from the content-addressed store, hash-verified

354
355
356def 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

Callers 1

__init__Method · 0.85

Calls 2

upfirdn2d_nativeFunction · 0.85
toMethod · 0.45

Tested by

no test coverage detected