Register
Login
Resources
Docs Blog Datasets Glossary Case Studies Tutorials & Webinars
Product
Data Engine LLMs Platform Enterprise
Pricing Explore
Connect to our Discord channel

ip_adapter.py 11 KB

You have to be logged in to leave a comment. Sign In
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
  1. import torch
  2. import ldm_patched.modules.clip_vision
  3. import safetensors.torch as sf
  4. import ldm_patched.modules.model_management as model_management
  5. import ldm_patched.ldm.modules.attention as attention
  6. from extras.resampler import Resampler
  7. from ldm_patched.modules.model_patcher import ModelPatcher
  8. from modules.core import numpy_to_pytorch
  9. from modules.ops import use_patched_ops
  10. from ldm_patched.modules.ops import manual_cast
  11. SD_V12_CHANNELS = [320] * 4 + [640] * 4 + [1280] * 4 + [1280] * 6 + [640] * 6 + [320] * 6 + [1280] * 2
  12. SD_XL_CHANNELS = [640] * 8 + [1280] * 40 + [1280] * 60 + [640] * 12 + [1280] * 20
  13. def sdp(q, k, v, extra_options):
  14. return attention.optimized_attention(q, k, v, heads=extra_options["n_heads"], mask=None)
  15. class ImageProjModel(torch.nn.Module):
  16. def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
  17. super().__init__()
  18. self.cross_attention_dim = cross_attention_dim
  19. self.clip_extra_context_tokens = clip_extra_context_tokens
  20. self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
  21. self.norm = torch.nn.LayerNorm(cross_attention_dim)
  22. def forward(self, image_embeds):
  23. embeds = image_embeds
  24. clip_extra_context_tokens = self.proj(embeds).reshape(-1, self.clip_extra_context_tokens,
  25. self.cross_attention_dim)
  26. clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
  27. return clip_extra_context_tokens
  28. class To_KV(torch.nn.Module):
  29. def __init__(self, cross_attention_dim):
  30. super().__init__()
  31. channels = SD_XL_CHANNELS if cross_attention_dim == 2048 else SD_V12_CHANNELS
  32. self.to_kvs = torch.nn.ModuleList(
  33. [torch.nn.Linear(cross_attention_dim, channel, bias=False) for channel in channels])
  34. def load_state_dict_ordered(self, sd):
  35. state_dict = []
  36. for i in range(4096):
  37. for k in ['k', 'v']:
  38. key = f'{i}.to_{k}_ip.weight'
  39. if key in sd:
  40. state_dict.append(sd[key])
  41. for i, v in enumerate(state_dict):
  42. self.to_kvs[i].weight = torch.nn.Parameter(v, requires_grad=False)
  43. class IPAdapterModel(torch.nn.Module):
  44. def __init__(self, state_dict, plus, cross_attention_dim=768, clip_embeddings_dim=1024, clip_extra_context_tokens=4,
  45. sdxl_plus=False):
  46. super().__init__()
  47. self.plus = plus
  48. if self.plus:
  49. self.image_proj_model = Resampler(
  50. dim=1280 if sdxl_plus else cross_attention_dim,
  51. depth=4,
  52. dim_head=64,
  53. heads=20 if sdxl_plus else 12,
  54. num_queries=clip_extra_context_tokens,
  55. embedding_dim=clip_embeddings_dim,
  56. output_dim=cross_attention_dim,
  57. ff_mult=4
  58. )
  59. else:
  60. self.image_proj_model = ImageProjModel(
  61. cross_attention_dim=cross_attention_dim,
  62. clip_embeddings_dim=clip_embeddings_dim,
  63. clip_extra_context_tokens=clip_extra_context_tokens
  64. )
  65. self.image_proj_model.load_state_dict(state_dict["image_proj"])
  66. self.ip_layers = To_KV(cross_attention_dim)
  67. self.ip_layers.load_state_dict_ordered(state_dict["ip_adapter"])
  68. clip_vision: ldm_patched.modules.clip_vision.ClipVisionModel = None
  69. ip_negative: torch.Tensor = None
  70. ip_adapters: dict = {}
  71. def load_ip_adapter(clip_vision_path, ip_negative_path, ip_adapter_path):
  72. global clip_vision, ip_negative, ip_adapters
  73. if clip_vision is None and isinstance(clip_vision_path, str):
  74. clip_vision = ldm_patched.modules.clip_vision.load(clip_vision_path)
  75. if ip_negative is None and isinstance(ip_negative_path, str):
  76. ip_negative = sf.load_file(ip_negative_path)['data']
  77. if not isinstance(ip_adapter_path, str) or ip_adapter_path in ip_adapters:
  78. return
  79. load_device = model_management.get_torch_device()
  80. offload_device = torch.device('cpu')
  81. use_fp16 = model_management.should_use_fp16(device=load_device)
  82. ip_state_dict = torch.load(ip_adapter_path, map_location="cpu", weights_only=True)
  83. plus = "latents" in ip_state_dict["image_proj"]
  84. cross_attention_dim = ip_state_dict["ip_adapter"]["1.to_k_ip.weight"].shape[1]
  85. sdxl = cross_attention_dim == 2048
  86. sdxl_plus = sdxl and plus
  87. if plus:
  88. clip_extra_context_tokens = ip_state_dict["image_proj"]["latents"].shape[1]
  89. clip_embeddings_dim = ip_state_dict["image_proj"]["latents"].shape[2]
  90. else:
  91. clip_extra_context_tokens = ip_state_dict["image_proj"]["proj.weight"].shape[0] // cross_attention_dim
  92. clip_embeddings_dim = None
  93. with use_patched_ops(manual_cast):
  94. ip_adapter = IPAdapterModel(
  95. ip_state_dict,
  96. plus=plus,
  97. cross_attention_dim=cross_attention_dim,
  98. clip_embeddings_dim=clip_embeddings_dim,
  99. clip_extra_context_tokens=clip_extra_context_tokens,
  100. sdxl_plus=sdxl_plus
  101. )
  102. ip_adapter.sdxl = sdxl
  103. ip_adapter.load_device = load_device
  104. ip_adapter.offload_device = offload_device
  105. ip_adapter.dtype = torch.float16 if use_fp16 else torch.float32
  106. ip_adapter.to(offload_device, dtype=ip_adapter.dtype)
  107. image_proj_model = ModelPatcher(model=ip_adapter.image_proj_model, load_device=load_device,
  108. offload_device=offload_device)
  109. ip_layers = ModelPatcher(model=ip_adapter.ip_layers, load_device=load_device,
  110. offload_device=offload_device)
  111. ip_adapters[ip_adapter_path] = dict(
  112. ip_adapter=ip_adapter,
  113. image_proj_model=image_proj_model,
  114. ip_layers=ip_layers,
  115. ip_unconds=None
  116. )
  117. return
  118. @torch.no_grad()
  119. @torch.inference_mode()
  120. def clip_preprocess(image):
  121. mean = torch.tensor([0.48145466, 0.4578275, 0.40821073], device=image.device, dtype=image.dtype).view([1, 3, 1, 1])
  122. std = torch.tensor([0.26862954, 0.26130258, 0.27577711], device=image.device, dtype=image.dtype).view([1, 3, 1, 1])
  123. image = image.movedim(-1, 1)
  124. # https://github.com/tencent-ailab/IP-Adapter/blob/d580c50a291566bbf9fc7ac0f760506607297e6d/README.md?plain=1#L75
  125. B, C, H, W = image.shape
  126. assert H == 224 and W == 224
  127. return (image - mean) / std
  128. @torch.no_grad()
  129. @torch.inference_mode()
  130. def preprocess(img, ip_adapter_path):
  131. global ip_adapters
  132. entry = ip_adapters[ip_adapter_path]
  133. ldm_patched.modules.model_management.load_model_gpu(clip_vision.patcher)
  134. pixel_values = clip_preprocess(numpy_to_pytorch(img).to(clip_vision.load_device))
  135. outputs = clip_vision.model(pixel_values=pixel_values, output_hidden_states=True)
  136. ip_adapter = entry['ip_adapter']
  137. ip_layers = entry['ip_layers']
  138. image_proj_model = entry['image_proj_model']
  139. ip_unconds = entry['ip_unconds']
  140. if ip_adapter.plus:
  141. cond = outputs.hidden_states[-2]
  142. else:
  143. cond = outputs.image_embeds
  144. cond = cond.to(device=ip_adapter.load_device, dtype=ip_adapter.dtype)
  145. ldm_patched.modules.model_management.load_model_gpu(image_proj_model)
  146. cond = image_proj_model.model(cond).to(device=ip_adapter.load_device, dtype=ip_adapter.dtype)
  147. ldm_patched.modules.model_management.load_model_gpu(ip_layers)
  148. if ip_unconds is None:
  149. uncond = ip_negative.to(device=ip_adapter.load_device, dtype=ip_adapter.dtype)
  150. ip_unconds = [m(uncond).cpu() for m in ip_layers.model.to_kvs]
  151. entry['ip_unconds'] = ip_unconds
  152. ip_conds = [m(cond).cpu() for m in ip_layers.model.to_kvs]
  153. return ip_conds, ip_unconds
  154. @torch.no_grad()
  155. @torch.inference_mode()
  156. def patch_model(model, tasks):
  157. new_model = model.clone()
  158. def make_attn_patcher(ip_index):
  159. def patcher(n, context_attn2, value_attn2, extra_options):
  160. org_dtype = n.dtype
  161. current_step = float(model.model.diffusion_model.current_step.detach().cpu().numpy()[0])
  162. cond_or_uncond = extra_options['cond_or_uncond']
  163. q = n
  164. k = [context_attn2]
  165. v = [value_attn2]
  166. b, _, _ = q.shape
  167. for (cs, ucs), cn_stop, cn_weight in tasks:
  168. if current_step < cn_stop:
  169. ip_k_c = cs[ip_index * 2].to(q)
  170. ip_v_c = cs[ip_index * 2 + 1].to(q)
  171. ip_k_uc = ucs[ip_index * 2].to(q)
  172. ip_v_uc = ucs[ip_index * 2 + 1].to(q)
  173. ip_k = torch.cat([(ip_k_c, ip_k_uc)[i] for i in cond_or_uncond], dim=0)
  174. ip_v = torch.cat([(ip_v_c, ip_v_uc)[i] for i in cond_or_uncond], dim=0)
  175. # Midjourney's attention formulation of image prompt (non-official reimplementation)
  176. # Written by Lvmin Zhang at Stanford University, 2023 Dec
  177. # For non-commercial use only - if you use this in commercial project then
  178. # probably it has some intellectual property issues.
  179. # Contact lvminzhang@acm.org if you are not sure.
  180. # Below is the sensitive part with potential intellectual property issues.
  181. ip_v_mean = torch.mean(ip_v, dim=1, keepdim=True)
  182. ip_v_offset = ip_v - ip_v_mean
  183. B, F, C = ip_k.shape
  184. channel_penalty = float(C) / 1280.0
  185. weight = cn_weight * channel_penalty
  186. ip_k = ip_k * weight
  187. ip_v = ip_v_offset + ip_v_mean * weight
  188. k.append(ip_k)
  189. v.append(ip_v)
  190. k = torch.cat(k, dim=1)
  191. v = torch.cat(v, dim=1)
  192. out = sdp(q, k, v, extra_options)
  193. return out.to(dtype=org_dtype)
  194. return patcher
  195. def set_model_patch_replace(model, number, key):
  196. to = model.model_options["transformer_options"]
  197. if "patches_replace" not in to:
  198. to["patches_replace"] = {}
  199. if "attn2" not in to["patches_replace"]:
  200. to["patches_replace"]["attn2"] = {}
  201. if key not in to["patches_replace"]["attn2"]:
  202. to["patches_replace"]["attn2"][key] = make_attn_patcher(number)
  203. number = 0
  204. for id in [4, 5, 7, 8]:
  205. block_indices = range(2) if id in [4, 5] else range(10)
  206. for index in block_indices:
  207. set_model_patch_replace(new_model, number, ("input", id, index))
  208. number += 1
  209. for id in range(6):
  210. block_indices = range(2) if id in [3, 4, 5] else range(10)
  211. for index in block_indices:
  212. set_model_patch_replace(new_model, number, ("output", id, index))
  213. number += 1
  214. for index in range(10):
  215. set_model_patch_replace(new_model, number, ("middle", 0, index))
  216. number += 1
  217. return new_model
Tip!

Press p or to see the previous file or, n or to see the next file

Comments

Loading...