MCPcopy Create free account
hub / github.com/huggingface/diffusers / _upsample_2d

Method _upsample_2d

src/diffusers/models/upsampling.py:222–315  ·  view source on GitHub ↗

Fused `upsample_2d()` followed by `Conv2d()`. Padding is performed only once at the beginning, not between the operations. The fused op is considerably more efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of arbitrary order

(
        self,
        hidden_states: torch.Tensor,
        weight: torch.Tensor | None = None,
        kernel: torch.Tensor | None = None,
        factor: int = 2,
        gain: float = 1,
    )

Source from the content-addressed store, hash-verified

220 self.out_channels = out_channels
221
222 def _upsample_2d(
223 self,
224 hidden_states: torch.Tensor,
225 weight: torch.Tensor | None = None,
226 kernel: torch.Tensor | None = None,
227 factor: int = 2,
228 gain: float = 1,
229 ) -> torch.Tensor:
230 """Fused `upsample_2d()` followed by `Conv2d()`.
231
232 Padding is performed only once at the beginning, not between the operations. The fused op is considerably more
233 efficient than performing the same calculation using standard TensorFlow ops. It supports gradients of
234 arbitrary order.
235
236 Args:
237 hidden_states (`torch.Tensor`):
238 Input tensor of the shape `[N, C, H, W]` or `[N, H, W, C]`.
239 weight (`torch.Tensor`, *optional*):
240 Weight tensor of the shape `[filterH, filterW, inChannels, outChannels]`. Grouped convolution can be
241 performed by `inChannels = x.shape[0] // numGroups`.
242 kernel (`torch.Tensor`, *optional*):
243 FIR filter of the shape `[firH, firW]` or `[firN]` (separable). The default is `[1] * factor`, which
244 corresponds to nearest-neighbor upsampling.
245 factor (`int`, *optional*): Integer upsampling factor (default: 2).
246 gain (`float`, *optional*): Scaling factor for signal magnitude (default: 1.0).
247
248 Returns:
249 output (`torch.Tensor`):
250 Tensor of the shape `[N, C, H * factor, W * factor]` or `[N, H * factor, W * factor, C]`, and same
251 datatype as `hidden_states`.
252 """
253
254 assert isinstance(factor, int) and factor >= 1
255
256 # Setup filter kernel.
257 if kernel is None:
258 kernel = [1] * factor
259
260 # setup kernel
261 kernel = torch.tensor(kernel, dtype=torch.float32)
262 if kernel.ndim == 1:
263 kernel = torch.outer(kernel, kernel)
264 kernel /= torch.sum(kernel)
265
266 kernel = kernel * (gain * (factor**2))
267
268 if self.use_conv:
269 convH = weight.shape[2]
270 convW = weight.shape[3]
271 inC = weight.shape[1]
272
273 pad_value = (kernel.shape[0] - factor) - (convW - 1)
274
275 stride = (factor, factor)
276 # Determine data dimensions.
277 output_shape = (
278 (hidden_states.shape[2] - 1) * factor + convH,
279 (hidden_states.shape[3] - 1) * factor + convW,

Callers 1

forwardMethod · 0.95

Calls 1

upfirdn2d_nativeFunction · 0.85

Tested by

no test coverage detected