2024-08-04 19:45:43 +00:00
|
|
|
import torch
|
2024-08-28 20:18:39 +00:00
|
|
|
import comfy.ops
|
2024-08-04 19:45:43 +00:00
|
|
|
|
|
|
|
def pad_to_patch_size(img, patch_size=(2, 2), padding_mode="circular"):
|
2024-11-27 18:45:32 +00:00
|
|
|
if padding_mode == "circular" and (torch.jit.is_tracing() or torch.jit.is_scripting()):
|
2024-08-04 19:45:43 +00:00
|
|
|
padding_mode = "reflect"
|
|
|
|
pad_h = (patch_size[0] - img.shape[-2] % patch_size[0]) % patch_size[0]
|
|
|
|
pad_w = (patch_size[1] - img.shape[-1] % patch_size[1]) % patch_size[1]
|
|
|
|
return torch.nn.functional.pad(img, (0, pad_w, 0, pad_h), mode=padding_mode)
|
2024-08-28 20:18:39 +00:00
|
|
|
|
|
|
|
try:
|
|
|
|
rms_norm_torch = torch.nn.functional.rms_norm
|
|
|
|
except:
|
|
|
|
rms_norm_torch = None
|
|
|
|
|
2024-10-26 10:54:00 +00:00
|
|
|
def rms_norm(x, weight=None, eps=1e-6):
|
2024-09-06 07:21:52 +00:00
|
|
|
if rms_norm_torch is not None and not (torch.jit.is_tracing() or torch.jit.is_scripting()):
|
2024-10-26 10:54:00 +00:00
|
|
|
if weight is None:
|
|
|
|
return rms_norm_torch(x, (x.shape[-1],), eps=eps)
|
|
|
|
else:
|
|
|
|
return rms_norm_torch(x, weight.shape, weight=comfy.ops.cast_to(weight, dtype=x.dtype, device=x.device), eps=eps)
|
2024-08-28 20:18:39 +00:00
|
|
|
else:
|
2024-10-26 10:54:00 +00:00
|
|
|
r = x * torch.rsqrt(torch.mean(x**2, dim=-1, keepdim=True) + eps)
|
|
|
|
if weight is None:
|
|
|
|
return r
|
|
|
|
else:
|
|
|
|
return r * comfy.ops.cast_to(weight, dtype=x.dtype, device=x.device)
|