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

Function downsample_2d

src/diffusers/models/downsampling.py:293–338  ·  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.FloatTensor,
    kernel: Optional[torch.FloatTensor] = None,
    factor: int = 2,
    gain: float = 1,
)

Source from the content-addressed store, hash-verified

291
292
293def downsample_2d(
294 hidden_states: torch.FloatTensor,
295 kernel: Optional[torch.FloatTensor] = None,
296 factor: int = 2,
297 gain: float = 1,
298) -> torch.FloatTensor:
299 r"""Downsample2D a batch of 2D images with the given filter.
300 Accepts a batch of 2D images of the shape `[N, C, H, W]` or `[N, H, W, C]` and downsamples each image with the
301 given filter. The filter is normalized so that if the input pixels are constant, they will be scaled by the
302 specified `gain`. Pixels outside the image are assumed to be zero, and the filter is padded with zeros so that its
303 shape is a multiple of the downsampling factor.
304
305 Args:
306 hidden_states (`torch.FloatTensor`)
307 Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
308 kernel (`torch.FloatTensor`, *optional*):
309 FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
310 corresponds to average pooling.
311 factor (`int`, *optional*, default to `2`):
312 Integer downsampling factor.
313 gain (`float`, *optional*, default to `1.0`):
314 Scaling factor for signal magnitude.
315
316 Returns:
317 output (`torch.FloatTensor`):
318 Tensor of the shape `[N, C, H // factor, W // factor]`
319 """
320
321 assert isinstance(factor, int) and factor >= 1
322 if kernel is None:
323 kernel = [1] * factor
324
325 kernel = torch.tensor(kernel, dtype=torch.float32)
326 if kernel.ndim == 1:
327 kernel = torch.outer(kernel, kernel)
328 kernel /= torch.sum(kernel)
329
330 kernel = kernel * gain
331 pad_value = kernel.shape[0] - factor
332 output = upfirdn2d_native(
333 hidden_states,
334 kernel.to(device=hidden_states.device),
335 down=factor,
336 pad=((pad_value + 1) // 2, pad_value // 2),
337 )
338 return output

Callers 1

__init__Method · 0.85

Calls 2

upfirdn2d_nativeFunction · 0.85
toMethod · 0.45

Tested by

no test coverage detected