MCPcopy Create free account
hub / github.com/adobe-research/custom-diffusion / compose

Function compose

src/diffusers_composenW.py:44–164  ·  view source on GitHub ↗
(paths, category, outpath, pretrained_model_path, regularization_prompt, prompts, save_path, device='cuda')

Source from the content-addressed store, hash-verified

42
43
44def compose(paths, category, outpath, pretrained_model_path, regularization_prompt, prompts, save_path, device='cuda'):
45 model_id = pretrained_model_path
46 pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")
47
48 layers_modified = []
49 for name, param in pipe.unet.named_parameters():
50 if 'attn2.to_k' in name or 'attn2.to_v' in name:
51 layers_modified.append(name)
52
53 tokenizer = pipe.tokenizer
54
55 def get_text_embedding(prompts):
56 with torch.no_grad():
57 uc = []
58 for text in prompts:
59 tokens = tokenizer(text,
60 truncation=True,
61 max_length=tokenizer.model_max_length,
62 return_length=True,
63 return_overflowing_tokens=False,
64 padding="do_not_pad",
65 ).input_ids
66 if 'photo of a' in text[:15]:
67 print(text)
68 uc.append(pipe.text_encoder(torch.cuda.LongTensor(tokens).reshape(1,-1))[0][:, 4:].reshape(-1, 768))
69 else:
70 uc.append(pipe.text_encoder(torch.cuda.LongTensor(tokens).reshape(1,-1))[0][:, 1:].reshape(-1, 768))
71 return torch.cat(uc, 0).float()
72
73 embeds = {}
74 count = 1
75 model2_sts = []
76 modifier_tokens = []
77 modifier_token_ids = []
78 categories = []
79 for path1, cat1 in zip(paths.split('+'), category.split('+')):
80 model2_st = torch.load(path1)
81 if 'modifier_token' in model2_st:
82 # composition of models with individual concept only
83 key = list(model2_st['modifier_token'].keys())[0]
84 _ = tokenizer.add_tokens(f'<new{count}>')
85 modifier_token_ids.append(tokenizer.convert_tokens_to_ids(f'<new{count}>'))
86 modifier_tokens.append(True)
87 embeds[f'<new{count}>'] = model2_st['modifier_token'][key]
88 else:
89 modifier_tokens.append(False)
90
91 model2_sts.append(model2_st['unet'])
92 categories.append(cat1)
93 count += 1
94
95 pipe.text_encoder.resize_token_embeddings(len(tokenizer))
96 token_embeds = pipe.text_encoder.get_input_embeddings().weight.data
97 for (x, y) in zip(modifier_token_ids, list(embeds.keys())):
98 token_embeds[x] = embeds[y]
99 print(x, y, "added embeddings")
100
101 f = open(regularization_prompt, 'r')

Callers 1

Calls 2

get_text_embeddingFunction · 0.70
gdupdateWexactFunction · 0.70

Tested by

no test coverage detected