Spaces:
Running
on
Zero
Running
on
Zero
File size: 5,999 Bytes
74a242e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 |
# type: ignore
# Inspired from https://github.com/ixarchakos/try-off-anyone/blob/aa3045453013065573a647e4536922bac696b968/src/model/pipeline.py
# Inspired from https://github.com/ixarchakos/try-off-anyone/blob/aa3045453013065573a647e4536922bac696b968/src/model/attention.py
import torch
from accelerate import load_checkpoint_in_model
from diffusers import AutoencoderKL, DDIMScheduler, UNet2DConditionModel
from diffusers.models.attention_processor import AttnProcessor
from diffusers.utils.torch_utils import randn_tensor
from huggingface_hub import hf_hub_download
from PIL import Image
class Skip(torch.nn.Module):
def __init__(self) -> None:
super().__init__()
def __call__(
self,
attn: torch.Tensor,
hidden_states: torch.Tensor,
encoder_hidden_states: torch.Tensor = None,
attention_mask: torch.Tensor = None,
temb: torch.Tensor = None,
) -> torch.Tensor:
return hidden_states
def fine_tuned_modules(unet: UNet2DConditionModel) -> torch.nn.ModuleList:
trainable_modules = torch.nn.ModuleList()
for blocks in [unet.down_blocks, unet.mid_block, unet.up_blocks]:
if hasattr(blocks, "attentions"):
trainable_modules.append(blocks.attentions)
else:
for block in blocks:
if hasattr(block, "attentions"):
trainable_modules.append(block.attentions)
return trainable_modules
def skip_cross_attentions(unet: UNet2DConditionModel) -> dict[str, AttnProcessor | Skip]:
attn_processors = {
name: unet.attn_processors[name] if name.endswith("attn1.processor") else Skip()
for name in unet.attn_processors.keys()
}
return attn_processors
def encode(image: torch.Tensor, vae: AutoencoderKL) -> torch.Tensor:
image = image.to(memory_format=torch.contiguous_format).float().to(vae.device, dtype=vae.dtype)
with torch.no_grad():
return vae.encode(image).latent_dist.sample() * vae.config.scaling_factor
class TryOffAnyone:
def __init__(
self,
device: torch.device,
dtype: torch.dtype,
concat_dim: int = -2,
) -> None:
self.concat_dim = concat_dim
self.device = device
self.dtype = dtype
self.noise_scheduler = DDIMScheduler.from_pretrained(
pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-inpainting",
subfolder="scheduler",
)
self.vae = AutoencoderKL.from_pretrained(
pretrained_model_name_or_path="stabilityai/sd-vae-ft-mse",
).to(device, dtype=dtype)
self.unet = UNet2DConditionModel.from_pretrained(
pretrained_model_name_or_path="stable-diffusion-v1-5/stable-diffusion-inpainting",
subfolder="unet",
variant="fp16",
).to(device, dtype=dtype)
self.unet.set_attn_processor(skip_cross_attentions(self.unet))
load_checkpoint_in_model(
model=fine_tuned_modules(unet=self.unet),
checkpoint=hf_hub_download(
repo_id="ixarchakos/tryOffAnyone",
filename="model.safetensors",
),
)
@torch.no_grad()
def __call__(
self,
image: torch.Tensor,
mask: torch.Tensor,
inference_steps: int,
scale: float,
generator: torch.Generator,
) -> list[Image.Image]:
image = image.unsqueeze(0).to(self.device, dtype=self.dtype)
mask = (mask.unsqueeze(0) > 0.5).to(self.device, dtype=self.dtype)
masked_image = image * (mask < 0.5)
masked_latent = encode(masked_image, self.vae)
image_latent = encode(image, self.vae)
mask = torch.nn.functional.interpolate(mask, size=masked_latent.shape[-2:], mode="nearest")
masked_latent_concat = torch.cat([masked_latent, image_latent], dim=self.concat_dim)
mask_concat = torch.cat([mask, torch.zeros_like(mask)], dim=self.concat_dim)
latents = randn_tensor(
shape=masked_latent_concat.shape,
generator=generator,
device=self.device,
dtype=self.dtype,
)
self.noise_scheduler.set_timesteps(inference_steps, device=self.device)
timesteps = self.noise_scheduler.timesteps
if do_classifier_free_guidance := (scale > 1.0):
masked_latent_concat = torch.cat(
[
torch.cat([masked_latent, torch.zeros_like(image_latent)], dim=self.concat_dim),
masked_latent_concat,
]
)
mask_concat = torch.cat([mask_concat] * 2)
extra_step = {"generator": generator, "eta": 1.0}
for t in timesteps:
input_latents = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
input_latents = self.noise_scheduler.scale_model_input(input_latents, t)
input_latents = torch.cat([input_latents, mask_concat, masked_latent_concat], dim=1)
noise_pred = self.unet(
input_latents,
t.to(self.device),
encoder_hidden_states=None,
return_dict=False,
)[0]
if do_classifier_free_guidance:
noise_pred_unc, noise_pred_text = noise_pred.chunk(2)
noise_pred = noise_pred_unc + scale * (noise_pred_text - noise_pred_unc)
latents = self.noise_scheduler.step(noise_pred, t, latents, **extra_step).prev_sample
latents = latents.split(latents.shape[self.concat_dim] // 2, dim=self.concat_dim)[0]
latents = 1 / self.vae.config.scaling_factor * latents
image = self.vae.decode(latents.to(self.device, dtype=self.dtype)).sample
image = (image / 2 + 0.5).clamp(0, 1)
image = image.cpu().permute(0, 2, 3, 1).float().numpy()
image = (image * 255).round().astype("uint8")
image = [Image.fromarray(im) for im in image]
return image
|