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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from omegaconf import OmegaConf
|
| 2 |
+
import torch
|
| 3 |
+
from PIL import Image
|
| 4 |
+
from torchvision import transforms
|
| 5 |
+
import os
|
| 6 |
+
from tqdm import tqdm
|
| 7 |
+
import numpy as np
|
| 8 |
+
from pathlib import Path
|
| 9 |
+
import matplotlib.pyplot as plt
|
| 10 |
+
import wandb
|
| 11 |
+
|
| 12 |
+
import sys
|
| 13 |
+
sys.path.append('.')
|
| 14 |
+
from stable_diffusion.ldm.models.diffusion.ddim import DDIMSampler
|
| 15 |
+
from stable_diffusion.ldm.util import instantiate_from_config
|
| 16 |
+
import random
|
| 17 |
+
import argparse
|
| 18 |
+
|
| 19 |
+
def load_model_from_config(config, ckpt, device="cpu", verbose=False):
|
| 20 |
+
"""Loads a model from config and a ckpt
|
| 21 |
+
if config is a path will use omegaconf to load
|
| 22 |
+
"""
|
| 23 |
+
if isinstance(config, (str, Path)):
|
| 24 |
+
config = OmegaConf.load(config)
|
| 25 |
+
|
| 26 |
+
pl_sd = torch.load(ckpt, map_location="cpu")
|
| 27 |
+
global_step = pl_sd["global_step"]
|
| 28 |
+
sd = pl_sd["state_dict"]
|
| 29 |
+
model = instantiate_from_config(config.model)
|
| 30 |
+
m, u = model.load_state_dict(sd, strict=False)
|
| 31 |
+
model.to(device)
|
| 32 |
+
model.eval()
|
| 33 |
+
model.cond_stage_model.device = device
|
| 34 |
+
return model
|
| 35 |
+
|
| 36 |
+
@torch.no_grad()
|
| 37 |
+
def sample_model(model, sampler, c, h, w, ddim_steps, scale, ddim_eta, start_code=None, n_samples=1,t_start=-1,log_every_t=None,till_T=None,verbose=True):
|
| 38 |
+
"""Sample the model"""
|
| 39 |
+
uc = None
|
| 40 |
+
if scale != 1.0:
|
| 41 |
+
uc = model.get_learned_conditioning(n_samples * [""])
|
| 42 |
+
log_t = 100
|
| 43 |
+
if log_every_t is not None:
|
| 44 |
+
log_t = log_every_t
|
| 45 |
+
shape = [4, h // 8, w // 8]
|
| 46 |
+
samples_ddim, inters = sampler.sample(S=ddim_steps,
|
| 47 |
+
conditioning=c,
|
| 48 |
+
batch_size=n_samples,
|
| 49 |
+
shape=shape,
|
| 50 |
+
verbose=False,
|
| 51 |
+
x_T=start_code,
|
| 52 |
+
unconditional_guidance_scale=scale,
|
| 53 |
+
unconditional_conditioning=uc,
|
| 54 |
+
eta=ddim_eta,
|
| 55 |
+
verbose_iter = verbose,
|
| 56 |
+
t_start=t_start,
|
| 57 |
+
log_every_t = log_t,
|
| 58 |
+
till_T = till_T
|
| 59 |
+
)
|
| 60 |
+
if log_every_t is not None:
|
| 61 |
+
return samples_ddim, inters
|
| 62 |
+
return samples_ddim
|
| 63 |
+
|
| 64 |
+
def load_img(path, target_size=512):
|
| 65 |
+
"""Load an image, resize and output -1..1"""
|
| 66 |
+
image = Image.open(path).convert("RGB")
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
tform = transforms.Compose([
|
| 70 |
+
transforms.Resize(target_size),
|
| 71 |
+
transforms.CenterCrop(target_size),
|
| 72 |
+
transforms.ToTensor(),
|
| 73 |
+
])
|
| 74 |
+
image = tform(image)
|
| 75 |
+
return 2.*image - 1.
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def moving_average(a, n=3) :
|
| 79 |
+
ret = np.cumsum(a, dtype=float)
|
| 80 |
+
ret[n:] = ret[n:] - ret[:-n]
|
| 81 |
+
return ret[n - 1:] / n
|
| 82 |
+
|
| 83 |
+
def plot_loss(losses, path,word, n=100):
|
| 84 |
+
v = moving_average(losses, n)
|
| 85 |
+
plt.plot(v, label=f'{word}_loss')
|
| 86 |
+
plt.legend(loc="upper left")
|
| 87 |
+
plt.title('Average loss in trainings', fontsize=20)
|
| 88 |
+
plt.xlabel('Data point', fontsize=16)
|
| 89 |
+
plt.ylabel('Loss value', fontsize=16)
|
| 90 |
+
plt.savefig(path)
|
| 91 |
+
|
| 92 |
+
##################### ESD Functions
|
| 93 |
+
def get_models(config_path, ckpt_path, devices):
|
| 94 |
+
model_orig = load_model_from_config(config_path, ckpt_path, devices[1])
|
| 95 |
+
sampler_orig = DDIMSampler(model_orig)
|
| 96 |
+
|
| 97 |
+
model = load_model_from_config(config_path, ckpt_path, devices[0])
|
| 98 |
+
sampler = DDIMSampler(model)
|
| 99 |
+
|
| 100 |
+
return model_orig, sampler_orig, model, sampler
|
| 101 |
+
|
| 102 |
+
def train_esd(prompt, train_method, start_guidance, negative_guidance, iterations, lr, config_path, ckpt_path, devices, output_name, seperator=None, image_size=512, ddim_steps=50):
|
| 103 |
+
'''
|
| 104 |
+
Function to train diffusion models to erase concepts from model weights
|
| 105 |
+
|
| 106 |
+
Parameters
|
| 107 |
+
----------
|
| 108 |
+
prompt : str
|
| 109 |
+
The concept to erase from diffusion model (Eg: "Van Gogh").
|
| 110 |
+
train_method : str
|
| 111 |
+
The parameters to train for erasure (ESD-x, ESD-u, full, selfattn).
|
| 112 |
+
start_guidance : float
|
| 113 |
+
Guidance to generate images for training.
|
| 114 |
+
negative_guidance : float
|
| 115 |
+
Guidance to erase the concepts from diffusion model.
|
| 116 |
+
iterations : int
|
| 117 |
+
Number of iterations to train.
|
| 118 |
+
lr : float
|
| 119 |
+
learning rate for fine tuning.
|
| 120 |
+
config_path : str
|
| 121 |
+
config path for compvis diffusion format.
|
| 122 |
+
ckpt_path : str
|
| 123 |
+
checkpoint path for pre-trained compvis diffusion weights.
|
| 124 |
+
devices : str
|
| 125 |
+
2 devices used to load the models (Eg: '0,1' will load in cuda:0 and cuda:1).
|
| 126 |
+
seperator : str, optional
|
| 127 |
+
If the prompt has commas can use this to seperate the prompt for individual simulataneous erasures. The default is None.
|
| 128 |
+
image_size : int, optional
|
| 129 |
+
Image size for generated images. The default is 512.
|
| 130 |
+
ddim_steps : int, optional
|
| 131 |
+
Number of diffusion time steps. The default is 50.
|
| 132 |
+
|
| 133 |
+
Returns
|
| 134 |
+
-------
|
| 135 |
+
None
|
| 136 |
+
|
| 137 |
+
'''
|
| 138 |
+
# PROMPT CLEANING
|
| 139 |
+
word_print = prompt.replace(' ','')
|
| 140 |
+
if prompt == 'allartist':
|
| 141 |
+
prompt = "Kelly Mckernan, Thomas Kinkade, Ajin Demi Human, Alena Aenami, Tyler Edlin, Kilian Eng"
|
| 142 |
+
if prompt == 'i2p':
|
| 143 |
+
prompt = "hate, harassment, violence, suffering, humiliation, harm, suicide, sexual, nudity, bodily fluids, blood"
|
| 144 |
+
if prompt == "artifact":
|
| 145 |
+
prompt = "ugly, tiling, poorly drawn hands, poorly drawn feet, poorly drawn face, out of frame, mutation, mutated, extra limbs, extra legs, extra arms, disfigured, deformed, cross-eye, body out of frame, blurry, bad art, bad anatomy, blurred, text, watermark, grainy"
|
| 146 |
+
|
| 147 |
+
if seperator is not None:
|
| 148 |
+
words = prompt.split(seperator)
|
| 149 |
+
words = [word.strip() for word in words]
|
| 150 |
+
else:
|
| 151 |
+
words = [prompt]
|
| 152 |
+
print(words)
|
| 153 |
+
ddim_eta = 0
|
| 154 |
+
# MODEL TRAINING SETUP
|
| 155 |
+
|
| 156 |
+
model_orig, sampler_orig, model, sampler = get_models(config_path, ckpt_path, devices)
|
| 157 |
+
|
| 158 |
+
# choose parameters to train based on train_method
|
| 159 |
+
parameters = []
|
| 160 |
+
for name, param in model.model.diffusion_model.named_parameters():
|
| 161 |
+
# train all layers except x-attns and time_embed layers
|
| 162 |
+
if train_method == 'noxattn':
|
| 163 |
+
if name.startswith('out.') or 'attn2' in name or 'time_embed' in name:
|
| 164 |
+
pass
|
| 165 |
+
else:
|
| 166 |
+
# print(name)
|
| 167 |
+
parameters.append(param)
|
| 168 |
+
# train only self attention layers
|
| 169 |
+
if train_method == 'selfattn':
|
| 170 |
+
if 'attn1' in name:
|
| 171 |
+
# print(name)
|
| 172 |
+
parameters.append(param)
|
| 173 |
+
# train only x attention layers
|
| 174 |
+
if train_method == 'xattn':
|
| 175 |
+
if 'attn2' in name:
|
| 176 |
+
# print(name)
|
| 177 |
+
parameters.append(param)
|
| 178 |
+
# train all layers
|
| 179 |
+
if train_method == 'full':
|
| 180 |
+
# print(name)
|
| 181 |
+
parameters.append(param)
|
| 182 |
+
# train all layers except time embed layers
|
| 183 |
+
if train_method == 'notime':
|
| 184 |
+
if not (name.startswith('out.') or 'time_embed' in name):
|
| 185 |
+
# print(name)
|
| 186 |
+
parameters.append(param)
|
| 187 |
+
if train_method == 'xlayer':
|
| 188 |
+
if 'attn2' in name:
|
| 189 |
+
if 'output_blocks.6.' in name or 'output_blocks.8.' in name:
|
| 190 |
+
# print(name)
|
| 191 |
+
parameters.append(param)
|
| 192 |
+
if train_method == 'selflayer':
|
| 193 |
+
if 'attn1' in name:
|
| 194 |
+
if 'input_blocks.4.' in name or 'input_blocks.7.' in name:
|
| 195 |
+
# print(name)
|
| 196 |
+
parameters.append(param)
|
| 197 |
+
# set model to train
|
| 198 |
+
model.train()
|
| 199 |
+
# create a lambda function for cleaner use of sampling code (only denoising till time step t)
|
| 200 |
+
quick_sample_till_t = lambda x, s, code, t: sample_model(model, sampler,
|
| 201 |
+
x, image_size, image_size, ddim_steps, s, ddim_eta,
|
| 202 |
+
start_code=code, till_T=t, verbose=False)
|
| 203 |
+
|
| 204 |
+
opt = torch.optim.Adam(parameters, lr=lr)
|
| 205 |
+
criteria = torch.nn.MSELoss()
|
| 206 |
+
|
| 207 |
+
# name = f'compvis-word_{word_print}-method_{train_method}-sg_{start_guidance}-ng_{negative_guidance}-iter_{iterations}-lr_{lr}'
|
| 208 |
+
# TRAINING CODE
|
| 209 |
+
pbar = tqdm(range(iterations))
|
| 210 |
+
for _ in pbar:
|
| 211 |
+
word = random.sample(words,1)[0]
|
| 212 |
+
# get text embeddings for unconditional and conditional prompts
|
| 213 |
+
emb_0 = model.get_learned_conditioning([''])
|
| 214 |
+
emb_p = model.get_learned_conditioning([word])
|
| 215 |
+
emb_n = model.get_learned_conditioning([f'{word}'])
|
| 216 |
+
|
| 217 |
+
opt.zero_grad()
|
| 218 |
+
|
| 219 |
+
t_enc = torch.randint(ddim_steps, (1,), device=devices[0])
|
| 220 |
+
# time step from 1000 to 0 (0 being good)
|
| 221 |
+
og_num = round((int(t_enc)/ddim_steps)*1000)
|
| 222 |
+
og_num_lim = round((int(t_enc+1)/ddim_steps)*1000)
|
| 223 |
+
|
| 224 |
+
t_enc_ddpm = torch.randint(og_num, og_num_lim, (1,), device=devices[0])
|
| 225 |
+
|
| 226 |
+
start_code = torch.randn((1, 4, 64, 64)).to(devices[0])
|
| 227 |
+
|
| 228 |
+
with torch.no_grad():
|
| 229 |
+
# generate an image with the concept from ESD model
|
| 230 |
+
z = quick_sample_till_t(emb_p.to(devices[0]), start_guidance, start_code, int(t_enc)) # emb_p seems to work better instead of emb_0
|
| 231 |
+
# get conditional and unconditional scores from frozen model at time step t and image z
|
| 232 |
+
e_0 = model_orig.apply_model(z.to(devices[1]), t_enc_ddpm.to(devices[1]), emb_0.to(devices[1]))
|
| 233 |
+
e_p = model_orig.apply_model(z.to(devices[1]), t_enc_ddpm.to(devices[1]), emb_p.to(devices[1]))
|
| 234 |
+
# breakpoint()
|
| 235 |
+
# get conditional score from ESD model
|
| 236 |
+
e_n = model.apply_model(z.to(devices[0]), t_enc_ddpm.to(devices[0]), emb_n.to(devices[0]))
|
| 237 |
+
e_0.requires_grad = False
|
| 238 |
+
e_p.requires_grad = False
|
| 239 |
+
# reconstruction loss for ESD objective from frozen model and conditional score of ESD model
|
| 240 |
+
loss = criteria(e_n.to(devices[0]), e_0.to(devices[0]) - (negative_guidance*(e_p.to(devices[0]) - e_0.to(devices[0])))) #loss = criteria(e_n, e_0) works the best try 5000 epochs
|
| 241 |
+
# update weights to erase the concept
|
| 242 |
+
loss.backward()
|
| 243 |
+
pbar.set_postfix({"loss": loss.item()})
|
| 244 |
+
opt.step()
|
| 245 |
+
|
| 246 |
+
model.eval()
|
| 247 |
+
torch.save({"state_dict": model.state_dict()}, output_name)
|
| 248 |
+
|
| 249 |
+
def save_history(losses, name, word_print):
|
| 250 |
+
folder_path = f'models/{name}'
|
| 251 |
+
os.makedirs(folder_path, exist_ok=True)
|
| 252 |
+
with open(f'{folder_path}/loss.txt', 'w') as f:
|
| 253 |
+
f.writelines([str(i) for i in losses])
|
| 254 |
+
plot_loss(losses,f'{folder_path}/loss.png' , word_print, n=3)
|
| 255 |
+
|
| 256 |
+
if __name__ == '__main__':
|
| 257 |
+
parser = argparse.ArgumentParser(
|
| 258 |
+
prog = 'TrainESD',
|
| 259 |
+
description = 'Finetuning stable diffusion model to erase concepts using ESD method')
|
| 260 |
+
parser.add_argument('--train_method', help='method of training', type=str, default='noxattn', choices=['xattn','noxattn', 'selfattn', 'full'])
|
| 261 |
+
parser.add_argument('--start_guidance', help='guidance of start image used to train', type=float, required=False, default=3)
|
| 262 |
+
parser.add_argument('--negative_guidance', help='guidance of negative training used to train', type=float, required=False, default=1)
|
| 263 |
+
parser.add_argument('--iterations', help='iterations used to train', type=int, required=False, default=1000)
|
| 264 |
+
parser.add_argument('--lr', help='learning rate used to train', type=int, required=False, default=1e-5)
|
| 265 |
+
parser.add_argument('--config_path', help='config path for stable diffusion v1-4 inference', type=str, required=False, default='configs/train_esd.yaml')
|
| 266 |
+
parser.add_argument('--ckpt_path', help='ckpt path for stable diffusion v1-4', type=str, required=True)
|
| 267 |
+
parser.add_argument('--devices', help='cuda devices to train on', type=str, required=False, default='0,0')
|
| 268 |
+
parser.add_argument('--seperator', help='separator if you want to train bunch of words separately', type=str, required=False, default=None)
|
| 269 |
+
parser.add_argument('--image_size', help='image size used to train', type=int, required=False, default=512)
|
| 270 |
+
parser.add_argument('--ddim_steps', help='ddim steps of inference used to train', type=int, required=False, default=50)
|
| 271 |
+
parser.add_argument('--output_dir', help='output directory to save results', type=str, required=False, default='results/style50')
|
| 272 |
+
parser.add_argument('--object_class', type=str, required=True)
|
| 273 |
+
parser.add_argument('--dry-run', action='store_true', help='dry run')
|
| 274 |
+
args = parser.parse_args()
|
| 275 |
+
|
| 276 |
+
# if not args.dry_run:
|
| 277 |
+
# wandb.init(project='quick-canvas-machine-unlearning', name=args.object_class, config=args)
|
| 278 |
+
# else:
|
| 279 |
+
# wandb = None
|
| 280 |
+
|
| 281 |
+
os.makedirs(args.output_dir, exist_ok=True)
|
| 282 |
+
output_name = f'{args.output_dir}/{args.object_class}.pth'
|
| 283 |
+
print(f"Saving the model to {output_name}")
|
| 284 |
+
|
| 285 |
+
prompt = f'An image of {args.object_class}.'
|
| 286 |
+
print(f"Prompt for unlearning: {prompt}")
|
| 287 |
+
train_method = args.train_method
|
| 288 |
+
start_guidance = args.start_guidance
|
| 289 |
+
negative_guidance = args.negative_guidance
|
| 290 |
+
iterations = args.iterations
|
| 291 |
+
lr = args.lr
|
| 292 |
+
config_path = args.config_path
|
| 293 |
+
ckpt_path = args.ckpt_path
|
| 294 |
+
devices = [f'cuda:{int(d.strip())}' for d in args.devices.split(',')]
|
| 295 |
+
seperator = args.seperator
|
| 296 |
+
image_size = args.image_size
|
| 297 |
+
ddim_steps = args.ddim_steps
|
| 298 |
+
|
| 299 |
+
train_esd(prompt=prompt, train_method=train_method, start_guidance=start_guidance, negative_guidance=negative_guidance, iterations=iterations, lr=lr, config_path=config_path, ckpt_path=ckpt_path, devices=devices, seperator=seperator, image_size=image_size, ddim_steps=ddim_steps, output_name=output_name)
|