Spaces:
Sleeping
Sleeping
Upload 10 files
Browse files- ip_adapter/__init__.py +9 -0
- ip_adapter/attention_processor.py +558 -0
- ip_adapter/attention_processor_faceid.py +427 -0
- ip_adapter/custom_pipelines.py +394 -0
- ip_adapter/ip_adapter.py +417 -0
- ip_adapter/ip_adapter_faceid.py +542 -0
- ip_adapter/ip_adapter_faceid_separate.py +547 -0
- ip_adapter/resampler.py +158 -0
- ip_adapter/test_resampler.py +44 -0
- ip_adapter/utils.py +93 -0
ip_adapter/__init__.py
ADDED
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from .ip_adapter import IPAdapter, IPAdapterPlus, IPAdapterPlusXL, IPAdapterXL, IPAdapterFull
|
2 |
+
|
3 |
+
__all__ = [
|
4 |
+
"IPAdapter",
|
5 |
+
"IPAdapterPlus",
|
6 |
+
"IPAdapterPlusXL",
|
7 |
+
"IPAdapterXL",
|
8 |
+
"IPAdapterFull",
|
9 |
+
]
|
ip_adapter/attention_processor.py
ADDED
@@ -0,0 +1,558 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
|
7 |
+
class AttnProcessor(nn.Module):
|
8 |
+
r"""
|
9 |
+
Default processor for performing attention-related computations.
|
10 |
+
"""
|
11 |
+
|
12 |
+
def __init__(
|
13 |
+
self,
|
14 |
+
hidden_size=None,
|
15 |
+
cross_attention_dim=None,
|
16 |
+
):
|
17 |
+
super().__init__()
|
18 |
+
|
19 |
+
def __call__(
|
20 |
+
self,
|
21 |
+
attn,
|
22 |
+
hidden_states,
|
23 |
+
encoder_hidden_states=None,
|
24 |
+
attention_mask=None,
|
25 |
+
temb=None,
|
26 |
+
):
|
27 |
+
residual = hidden_states
|
28 |
+
|
29 |
+
if attn.spatial_norm is not None:
|
30 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
31 |
+
|
32 |
+
input_ndim = hidden_states.ndim
|
33 |
+
|
34 |
+
if input_ndim == 4:
|
35 |
+
batch_size, channel, height, width = hidden_states.shape
|
36 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
37 |
+
|
38 |
+
batch_size, sequence_length, _ = (
|
39 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
40 |
+
)
|
41 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
42 |
+
|
43 |
+
if attn.group_norm is not None:
|
44 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
45 |
+
|
46 |
+
query = attn.to_q(hidden_states)
|
47 |
+
|
48 |
+
if encoder_hidden_states is None:
|
49 |
+
encoder_hidden_states = hidden_states
|
50 |
+
elif attn.norm_cross:
|
51 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
52 |
+
|
53 |
+
key = attn.to_k(encoder_hidden_states)
|
54 |
+
value = attn.to_v(encoder_hidden_states)
|
55 |
+
|
56 |
+
query = attn.head_to_batch_dim(query)
|
57 |
+
key = attn.head_to_batch_dim(key)
|
58 |
+
value = attn.head_to_batch_dim(value)
|
59 |
+
|
60 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
61 |
+
hidden_states = torch.bmm(attention_probs, value)
|
62 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
63 |
+
|
64 |
+
# linear proj
|
65 |
+
hidden_states = attn.to_out[0](hidden_states)
|
66 |
+
# dropout
|
67 |
+
hidden_states = attn.to_out[1](hidden_states)
|
68 |
+
|
69 |
+
if input_ndim == 4:
|
70 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
71 |
+
|
72 |
+
if attn.residual_connection:
|
73 |
+
hidden_states = hidden_states + residual
|
74 |
+
|
75 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
76 |
+
|
77 |
+
return hidden_states
|
78 |
+
|
79 |
+
|
80 |
+
class IPAttnProcessor(nn.Module):
|
81 |
+
r"""
|
82 |
+
Attention processor for IP-Adapater.
|
83 |
+
Args:
|
84 |
+
hidden_size (`int`):
|
85 |
+
The hidden size of the attention layer.
|
86 |
+
cross_attention_dim (`int`):
|
87 |
+
The number of channels in the `encoder_hidden_states`.
|
88 |
+
scale (`float`, defaults to 1.0):
|
89 |
+
the weight scale of image prompt.
|
90 |
+
num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
|
91 |
+
The context length of the image features.
|
92 |
+
"""
|
93 |
+
|
94 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
|
95 |
+
super().__init__()
|
96 |
+
|
97 |
+
self.hidden_size = hidden_size
|
98 |
+
self.cross_attention_dim = cross_attention_dim
|
99 |
+
self.scale = scale
|
100 |
+
self.num_tokens = num_tokens
|
101 |
+
|
102 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
103 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
104 |
+
|
105 |
+
def __call__(
|
106 |
+
self,
|
107 |
+
attn,
|
108 |
+
hidden_states,
|
109 |
+
encoder_hidden_states=None,
|
110 |
+
attention_mask=None,
|
111 |
+
temb=None,
|
112 |
+
):
|
113 |
+
residual = hidden_states
|
114 |
+
|
115 |
+
if attn.spatial_norm is not None:
|
116 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
117 |
+
|
118 |
+
input_ndim = hidden_states.ndim
|
119 |
+
|
120 |
+
if input_ndim == 4:
|
121 |
+
batch_size, channel, height, width = hidden_states.shape
|
122 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
123 |
+
|
124 |
+
batch_size, sequence_length, _ = (
|
125 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
126 |
+
)
|
127 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
128 |
+
|
129 |
+
if attn.group_norm is not None:
|
130 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
131 |
+
|
132 |
+
query = attn.to_q(hidden_states)
|
133 |
+
|
134 |
+
if encoder_hidden_states is None:
|
135 |
+
encoder_hidden_states = hidden_states
|
136 |
+
else:
|
137 |
+
# get encoder_hidden_states, ip_hidden_states
|
138 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
139 |
+
encoder_hidden_states, ip_hidden_states = (
|
140 |
+
encoder_hidden_states[:, :end_pos, :],
|
141 |
+
encoder_hidden_states[:, end_pos:, :],
|
142 |
+
)
|
143 |
+
if attn.norm_cross:
|
144 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
145 |
+
|
146 |
+
key = attn.to_k(encoder_hidden_states)
|
147 |
+
value = attn.to_v(encoder_hidden_states)
|
148 |
+
|
149 |
+
query = attn.head_to_batch_dim(query)
|
150 |
+
key = attn.head_to_batch_dim(key)
|
151 |
+
value = attn.head_to_batch_dim(value)
|
152 |
+
|
153 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
154 |
+
hidden_states = torch.bmm(attention_probs, value)
|
155 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
156 |
+
|
157 |
+
# for ip-adapter
|
158 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
159 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
160 |
+
|
161 |
+
ip_key = attn.head_to_batch_dim(ip_key)
|
162 |
+
ip_value = attn.head_to_batch_dim(ip_value)
|
163 |
+
|
164 |
+
ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
|
165 |
+
self.attn_map = ip_attention_probs
|
166 |
+
ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
|
167 |
+
ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
|
168 |
+
|
169 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
170 |
+
|
171 |
+
# linear proj
|
172 |
+
hidden_states = attn.to_out[0](hidden_states)
|
173 |
+
# dropout
|
174 |
+
hidden_states = attn.to_out[1](hidden_states)
|
175 |
+
|
176 |
+
if input_ndim == 4:
|
177 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
178 |
+
|
179 |
+
if attn.residual_connection:
|
180 |
+
hidden_states = hidden_states + residual
|
181 |
+
|
182 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
183 |
+
|
184 |
+
return hidden_states
|
185 |
+
|
186 |
+
|
187 |
+
class AttnProcessor2_0(torch.nn.Module):
|
188 |
+
r"""
|
189 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
190 |
+
"""
|
191 |
+
|
192 |
+
def __init__(
|
193 |
+
self,
|
194 |
+
hidden_size=None,
|
195 |
+
cross_attention_dim=None,
|
196 |
+
):
|
197 |
+
super().__init__()
|
198 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
199 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
200 |
+
|
201 |
+
def __call__(
|
202 |
+
self,
|
203 |
+
attn,
|
204 |
+
hidden_states,
|
205 |
+
encoder_hidden_states=None,
|
206 |
+
attention_mask=None,
|
207 |
+
temb=None,
|
208 |
+
):
|
209 |
+
residual = hidden_states
|
210 |
+
|
211 |
+
if attn.spatial_norm is not None:
|
212 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
213 |
+
|
214 |
+
input_ndim = hidden_states.ndim
|
215 |
+
|
216 |
+
if input_ndim == 4:
|
217 |
+
batch_size, channel, height, width = hidden_states.shape
|
218 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
219 |
+
|
220 |
+
batch_size, sequence_length, _ = (
|
221 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
222 |
+
)
|
223 |
+
|
224 |
+
if attention_mask is not None:
|
225 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
226 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
227 |
+
# (batch, heads, source_length, target_length)
|
228 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
229 |
+
|
230 |
+
if attn.group_norm is not None:
|
231 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
232 |
+
|
233 |
+
query = attn.to_q(hidden_states)
|
234 |
+
|
235 |
+
if encoder_hidden_states is None:
|
236 |
+
encoder_hidden_states = hidden_states
|
237 |
+
elif attn.norm_cross:
|
238 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
239 |
+
|
240 |
+
key = attn.to_k(encoder_hidden_states)
|
241 |
+
value = attn.to_v(encoder_hidden_states)
|
242 |
+
|
243 |
+
inner_dim = key.shape[-1]
|
244 |
+
head_dim = inner_dim // attn.heads
|
245 |
+
|
246 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
247 |
+
|
248 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
249 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
250 |
+
|
251 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
252 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
253 |
+
hidden_states = F.scaled_dot_product_attention(
|
254 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
255 |
+
)
|
256 |
+
|
257 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
258 |
+
hidden_states = hidden_states.to(query.dtype)
|
259 |
+
|
260 |
+
# linear proj
|
261 |
+
hidden_states = attn.to_out[0](hidden_states)
|
262 |
+
# dropout
|
263 |
+
hidden_states = attn.to_out[1](hidden_states)
|
264 |
+
|
265 |
+
if input_ndim == 4:
|
266 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
267 |
+
|
268 |
+
if attn.residual_connection:
|
269 |
+
hidden_states = hidden_states + residual
|
270 |
+
|
271 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
272 |
+
|
273 |
+
return hidden_states
|
274 |
+
|
275 |
+
|
276 |
+
class IPAttnProcessor2_0(torch.nn.Module):
|
277 |
+
r"""
|
278 |
+
Attention processor for IP-Adapater for PyTorch 2.0.
|
279 |
+
Args:
|
280 |
+
hidden_size (`int`):
|
281 |
+
The hidden size of the attention layer.
|
282 |
+
cross_attention_dim (`int`):
|
283 |
+
The number of channels in the `encoder_hidden_states`.
|
284 |
+
scale (`float`, defaults to 1.0):
|
285 |
+
the weight scale of image prompt.
|
286 |
+
num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
|
287 |
+
The context length of the image features.
|
288 |
+
"""
|
289 |
+
|
290 |
+
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4):
|
291 |
+
super().__init__()
|
292 |
+
|
293 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
294 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
295 |
+
|
296 |
+
self.hidden_size = hidden_size
|
297 |
+
self.cross_attention_dim = cross_attention_dim
|
298 |
+
self.scale = scale
|
299 |
+
self.num_tokens = num_tokens
|
300 |
+
|
301 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
302 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
303 |
+
|
304 |
+
def __call__(
|
305 |
+
self,
|
306 |
+
attn,
|
307 |
+
hidden_states,
|
308 |
+
encoder_hidden_states=None,
|
309 |
+
attention_mask=None,
|
310 |
+
temb=None,
|
311 |
+
):
|
312 |
+
residual = hidden_states
|
313 |
+
|
314 |
+
if attn.spatial_norm is not None:
|
315 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
316 |
+
|
317 |
+
input_ndim = hidden_states.ndim
|
318 |
+
|
319 |
+
if input_ndim == 4:
|
320 |
+
batch_size, channel, height, width = hidden_states.shape
|
321 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
322 |
+
|
323 |
+
batch_size, sequence_length, _ = (
|
324 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
325 |
+
)
|
326 |
+
|
327 |
+
if attention_mask is not None:
|
328 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
329 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
330 |
+
# (batch, heads, source_length, target_length)
|
331 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
332 |
+
|
333 |
+
if attn.group_norm is not None:
|
334 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
335 |
+
|
336 |
+
query = attn.to_q(hidden_states)
|
337 |
+
|
338 |
+
if encoder_hidden_states is None:
|
339 |
+
encoder_hidden_states = hidden_states
|
340 |
+
else:
|
341 |
+
# get encoder_hidden_states, ip_hidden_states
|
342 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
343 |
+
encoder_hidden_states, ip_hidden_states = (
|
344 |
+
encoder_hidden_states[:, :end_pos, :],
|
345 |
+
encoder_hidden_states[:, end_pos:, :],
|
346 |
+
)
|
347 |
+
if attn.norm_cross:
|
348 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
349 |
+
|
350 |
+
key = attn.to_k(encoder_hidden_states)
|
351 |
+
value = attn.to_v(encoder_hidden_states)
|
352 |
+
|
353 |
+
inner_dim = key.shape[-1]
|
354 |
+
head_dim = inner_dim // attn.heads
|
355 |
+
|
356 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
357 |
+
|
358 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
359 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
360 |
+
|
361 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
362 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
363 |
+
hidden_states = F.scaled_dot_product_attention(
|
364 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
365 |
+
)
|
366 |
+
|
367 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
368 |
+
hidden_states = hidden_states.to(query.dtype)
|
369 |
+
|
370 |
+
# for ip-adapter
|
371 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
372 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
373 |
+
|
374 |
+
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
375 |
+
ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
376 |
+
|
377 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
378 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
379 |
+
ip_hidden_states = F.scaled_dot_product_attention(
|
380 |
+
query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
|
381 |
+
)
|
382 |
+
with torch.no_grad():
|
383 |
+
self.attn_map = query @ ip_key.transpose(-2, -1).softmax(dim=-1)
|
384 |
+
#print(self.attn_map.shape)
|
385 |
+
|
386 |
+
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
387 |
+
ip_hidden_states = ip_hidden_states.to(query.dtype)
|
388 |
+
|
389 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
390 |
+
|
391 |
+
# linear proj
|
392 |
+
hidden_states = attn.to_out[0](hidden_states)
|
393 |
+
# dropout
|
394 |
+
hidden_states = attn.to_out[1](hidden_states)
|
395 |
+
|
396 |
+
if input_ndim == 4:
|
397 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
398 |
+
|
399 |
+
if attn.residual_connection:
|
400 |
+
hidden_states = hidden_states + residual
|
401 |
+
|
402 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
403 |
+
|
404 |
+
return hidden_states
|
405 |
+
|
406 |
+
|
407 |
+
## for controlnet
|
408 |
+
class CNAttnProcessor:
|
409 |
+
r"""
|
410 |
+
Default processor for performing attention-related computations.
|
411 |
+
"""
|
412 |
+
|
413 |
+
def __init__(self, num_tokens=4):
|
414 |
+
self.num_tokens = num_tokens
|
415 |
+
|
416 |
+
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None):
|
417 |
+
residual = hidden_states
|
418 |
+
|
419 |
+
if attn.spatial_norm is not None:
|
420 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
421 |
+
|
422 |
+
input_ndim = hidden_states.ndim
|
423 |
+
|
424 |
+
if input_ndim == 4:
|
425 |
+
batch_size, channel, height, width = hidden_states.shape
|
426 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
427 |
+
|
428 |
+
batch_size, sequence_length, _ = (
|
429 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
430 |
+
)
|
431 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
432 |
+
|
433 |
+
if attn.group_norm is not None:
|
434 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
435 |
+
|
436 |
+
query = attn.to_q(hidden_states)
|
437 |
+
|
438 |
+
if encoder_hidden_states is None:
|
439 |
+
encoder_hidden_states = hidden_states
|
440 |
+
else:
|
441 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
442 |
+
encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text
|
443 |
+
if attn.norm_cross:
|
444 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
445 |
+
|
446 |
+
key = attn.to_k(encoder_hidden_states)
|
447 |
+
value = attn.to_v(encoder_hidden_states)
|
448 |
+
|
449 |
+
query = attn.head_to_batch_dim(query)
|
450 |
+
key = attn.head_to_batch_dim(key)
|
451 |
+
value = attn.head_to_batch_dim(value)
|
452 |
+
|
453 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
454 |
+
hidden_states = torch.bmm(attention_probs, value)
|
455 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
456 |
+
|
457 |
+
# linear proj
|
458 |
+
hidden_states = attn.to_out[0](hidden_states)
|
459 |
+
# dropout
|
460 |
+
hidden_states = attn.to_out[1](hidden_states)
|
461 |
+
|
462 |
+
if input_ndim == 4:
|
463 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
464 |
+
|
465 |
+
if attn.residual_connection:
|
466 |
+
hidden_states = hidden_states + residual
|
467 |
+
|
468 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
469 |
+
|
470 |
+
return hidden_states
|
471 |
+
|
472 |
+
|
473 |
+
class CNAttnProcessor2_0:
|
474 |
+
r"""
|
475 |
+
Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0).
|
476 |
+
"""
|
477 |
+
|
478 |
+
def __init__(self, num_tokens=4):
|
479 |
+
if not hasattr(F, "scaled_dot_product_attention"):
|
480 |
+
raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
|
481 |
+
self.num_tokens = num_tokens
|
482 |
+
|
483 |
+
def __call__(
|
484 |
+
self,
|
485 |
+
attn,
|
486 |
+
hidden_states,
|
487 |
+
encoder_hidden_states=None,
|
488 |
+
attention_mask=None,
|
489 |
+
temb=None,
|
490 |
+
):
|
491 |
+
residual = hidden_states
|
492 |
+
|
493 |
+
if attn.spatial_norm is not None:
|
494 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
495 |
+
|
496 |
+
input_ndim = hidden_states.ndim
|
497 |
+
|
498 |
+
if input_ndim == 4:
|
499 |
+
batch_size, channel, height, width = hidden_states.shape
|
500 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
501 |
+
|
502 |
+
batch_size, sequence_length, _ = (
|
503 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
504 |
+
)
|
505 |
+
|
506 |
+
if attention_mask is not None:
|
507 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
508 |
+
# scaled_dot_product_attention expects attention_mask shape to be
|
509 |
+
# (batch, heads, source_length, target_length)
|
510 |
+
attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
|
511 |
+
|
512 |
+
if attn.group_norm is not None:
|
513 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
514 |
+
|
515 |
+
query = attn.to_q(hidden_states)
|
516 |
+
|
517 |
+
if encoder_hidden_states is None:
|
518 |
+
encoder_hidden_states = hidden_states
|
519 |
+
else:
|
520 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
521 |
+
encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text
|
522 |
+
if attn.norm_cross:
|
523 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
524 |
+
|
525 |
+
key = attn.to_k(encoder_hidden_states)
|
526 |
+
value = attn.to_v(encoder_hidden_states)
|
527 |
+
|
528 |
+
inner_dim = key.shape[-1]
|
529 |
+
head_dim = inner_dim // attn.heads
|
530 |
+
|
531 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
532 |
+
|
533 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
534 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
535 |
+
|
536 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
537 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
538 |
+
hidden_states = F.scaled_dot_product_attention(
|
539 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
540 |
+
)
|
541 |
+
|
542 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
543 |
+
hidden_states = hidden_states.to(query.dtype)
|
544 |
+
|
545 |
+
# linear proj
|
546 |
+
hidden_states = attn.to_out[0](hidden_states)
|
547 |
+
# dropout
|
548 |
+
hidden_states = attn.to_out[1](hidden_states)
|
549 |
+
|
550 |
+
if input_ndim == 4:
|
551 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
552 |
+
|
553 |
+
if attn.residual_connection:
|
554 |
+
hidden_states = hidden_states + residual
|
555 |
+
|
556 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
557 |
+
|
558 |
+
return hidden_states
|
ip_adapter/attention_processor_faceid.py
ADDED
@@ -0,0 +1,427 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py
|
2 |
+
import torch
|
3 |
+
import torch.nn as nn
|
4 |
+
import torch.nn.functional as F
|
5 |
+
|
6 |
+
from diffusers.models.lora import LoRALinearLayer
|
7 |
+
|
8 |
+
|
9 |
+
class LoRAAttnProcessor(nn.Module):
|
10 |
+
r"""
|
11 |
+
Default processor for performing attention-related computations.
|
12 |
+
"""
|
13 |
+
|
14 |
+
def __init__(
|
15 |
+
self,
|
16 |
+
hidden_size=None,
|
17 |
+
cross_attention_dim=None,
|
18 |
+
rank=4,
|
19 |
+
network_alpha=None,
|
20 |
+
lora_scale=1.0,
|
21 |
+
):
|
22 |
+
super().__init__()
|
23 |
+
|
24 |
+
self.rank = rank
|
25 |
+
self.lora_scale = lora_scale
|
26 |
+
|
27 |
+
self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
28 |
+
self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
29 |
+
self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
30 |
+
self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
31 |
+
|
32 |
+
def __call__(
|
33 |
+
self,
|
34 |
+
attn,
|
35 |
+
hidden_states,
|
36 |
+
encoder_hidden_states=None,
|
37 |
+
attention_mask=None,
|
38 |
+
temb=None,
|
39 |
+
):
|
40 |
+
residual = hidden_states
|
41 |
+
|
42 |
+
if attn.spatial_norm is not None:
|
43 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
44 |
+
|
45 |
+
input_ndim = hidden_states.ndim
|
46 |
+
|
47 |
+
if input_ndim == 4:
|
48 |
+
batch_size, channel, height, width = hidden_states.shape
|
49 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
50 |
+
|
51 |
+
batch_size, sequence_length, _ = (
|
52 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
53 |
+
)
|
54 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
55 |
+
|
56 |
+
if attn.group_norm is not None:
|
57 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
58 |
+
|
59 |
+
query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
|
60 |
+
|
61 |
+
if encoder_hidden_states is None:
|
62 |
+
encoder_hidden_states = hidden_states
|
63 |
+
elif attn.norm_cross:
|
64 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
65 |
+
|
66 |
+
key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
|
67 |
+
value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
|
68 |
+
|
69 |
+
query = attn.head_to_batch_dim(query)
|
70 |
+
key = attn.head_to_batch_dim(key)
|
71 |
+
value = attn.head_to_batch_dim(value)
|
72 |
+
|
73 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
74 |
+
hidden_states = torch.bmm(attention_probs, value)
|
75 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
76 |
+
|
77 |
+
# linear proj
|
78 |
+
hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
|
79 |
+
# dropout
|
80 |
+
hidden_states = attn.to_out[1](hidden_states)
|
81 |
+
|
82 |
+
if input_ndim == 4:
|
83 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
84 |
+
|
85 |
+
if attn.residual_connection:
|
86 |
+
hidden_states = hidden_states + residual
|
87 |
+
|
88 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
89 |
+
|
90 |
+
return hidden_states
|
91 |
+
|
92 |
+
|
93 |
+
class LoRAIPAttnProcessor(nn.Module):
|
94 |
+
r"""
|
95 |
+
Attention processor for IP-Adapater.
|
96 |
+
Args:
|
97 |
+
hidden_size (`int`):
|
98 |
+
The hidden size of the attention layer.
|
99 |
+
cross_attention_dim (`int`):
|
100 |
+
The number of channels in the `encoder_hidden_states`.
|
101 |
+
scale (`float`, defaults to 1.0):
|
102 |
+
the weight scale of image prompt.
|
103 |
+
num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16):
|
104 |
+
The context length of the image features.
|
105 |
+
"""
|
106 |
+
|
107 |
+
def __init__(self, hidden_size, cross_attention_dim=None, rank=4, network_alpha=None, lora_scale=1.0, scale=1.0, num_tokens=4):
|
108 |
+
super().__init__()
|
109 |
+
|
110 |
+
self.rank = rank
|
111 |
+
self.lora_scale = lora_scale
|
112 |
+
|
113 |
+
self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
114 |
+
self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
115 |
+
self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
116 |
+
self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
117 |
+
|
118 |
+
self.hidden_size = hidden_size
|
119 |
+
self.cross_attention_dim = cross_attention_dim
|
120 |
+
self.scale = scale
|
121 |
+
self.num_tokens = num_tokens
|
122 |
+
|
123 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
124 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
125 |
+
|
126 |
+
def __call__(
|
127 |
+
self,
|
128 |
+
attn,
|
129 |
+
hidden_states,
|
130 |
+
encoder_hidden_states=None,
|
131 |
+
attention_mask=None,
|
132 |
+
temb=None,
|
133 |
+
):
|
134 |
+
residual = hidden_states
|
135 |
+
|
136 |
+
if attn.spatial_norm is not None:
|
137 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
138 |
+
|
139 |
+
input_ndim = hidden_states.ndim
|
140 |
+
|
141 |
+
if input_ndim == 4:
|
142 |
+
batch_size, channel, height, width = hidden_states.shape
|
143 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
144 |
+
|
145 |
+
batch_size, sequence_length, _ = (
|
146 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
147 |
+
)
|
148 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
149 |
+
|
150 |
+
if attn.group_norm is not None:
|
151 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
152 |
+
|
153 |
+
query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
|
154 |
+
|
155 |
+
if encoder_hidden_states is None:
|
156 |
+
encoder_hidden_states = hidden_states
|
157 |
+
else:
|
158 |
+
# get encoder_hidden_states, ip_hidden_states
|
159 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
160 |
+
encoder_hidden_states, ip_hidden_states = (
|
161 |
+
encoder_hidden_states[:, :end_pos, :],
|
162 |
+
encoder_hidden_states[:, end_pos:, :],
|
163 |
+
)
|
164 |
+
if attn.norm_cross:
|
165 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
166 |
+
|
167 |
+
key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
|
168 |
+
value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
|
169 |
+
|
170 |
+
query = attn.head_to_batch_dim(query)
|
171 |
+
key = attn.head_to_batch_dim(key)
|
172 |
+
value = attn.head_to_batch_dim(value)
|
173 |
+
|
174 |
+
attention_probs = attn.get_attention_scores(query, key, attention_mask)
|
175 |
+
hidden_states = torch.bmm(attention_probs, value)
|
176 |
+
hidden_states = attn.batch_to_head_dim(hidden_states)
|
177 |
+
|
178 |
+
# for ip-adapter
|
179 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
180 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
181 |
+
|
182 |
+
ip_key = attn.head_to_batch_dim(ip_key)
|
183 |
+
ip_value = attn.head_to_batch_dim(ip_value)
|
184 |
+
|
185 |
+
ip_attention_probs = attn.get_attention_scores(query, ip_key, None)
|
186 |
+
self.attn_map = ip_attention_probs
|
187 |
+
ip_hidden_states = torch.bmm(ip_attention_probs, ip_value)
|
188 |
+
ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
|
189 |
+
|
190 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
191 |
+
|
192 |
+
# linear proj
|
193 |
+
hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
|
194 |
+
# dropout
|
195 |
+
hidden_states = attn.to_out[1](hidden_states)
|
196 |
+
|
197 |
+
if input_ndim == 4:
|
198 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
199 |
+
|
200 |
+
if attn.residual_connection:
|
201 |
+
hidden_states = hidden_states + residual
|
202 |
+
|
203 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
204 |
+
|
205 |
+
return hidden_states
|
206 |
+
|
207 |
+
|
208 |
+
class LoRAAttnProcessor2_0(nn.Module):
|
209 |
+
|
210 |
+
r"""
|
211 |
+
Default processor for performing attention-related computations.
|
212 |
+
"""
|
213 |
+
|
214 |
+
def __init__(
|
215 |
+
self,
|
216 |
+
hidden_size=None,
|
217 |
+
cross_attention_dim=None,
|
218 |
+
rank=4,
|
219 |
+
network_alpha=None,
|
220 |
+
lora_scale=1.0,
|
221 |
+
):
|
222 |
+
super().__init__()
|
223 |
+
|
224 |
+
self.rank = rank
|
225 |
+
self.lora_scale = lora_scale
|
226 |
+
|
227 |
+
self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
228 |
+
self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
229 |
+
self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
230 |
+
self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
231 |
+
|
232 |
+
def __call__(
|
233 |
+
self,
|
234 |
+
attn,
|
235 |
+
hidden_states,
|
236 |
+
encoder_hidden_states=None,
|
237 |
+
attention_mask=None,
|
238 |
+
temb=None,
|
239 |
+
):
|
240 |
+
residual = hidden_states
|
241 |
+
|
242 |
+
if attn.spatial_norm is not None:
|
243 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
244 |
+
|
245 |
+
input_ndim = hidden_states.ndim
|
246 |
+
|
247 |
+
if input_ndim == 4:
|
248 |
+
batch_size, channel, height, width = hidden_states.shape
|
249 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
250 |
+
|
251 |
+
batch_size, sequence_length, _ = (
|
252 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
253 |
+
)
|
254 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
255 |
+
|
256 |
+
if attn.group_norm is not None:
|
257 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
258 |
+
|
259 |
+
query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
|
260 |
+
|
261 |
+
if encoder_hidden_states is None:
|
262 |
+
encoder_hidden_states = hidden_states
|
263 |
+
elif attn.norm_cross:
|
264 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
265 |
+
|
266 |
+
key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
|
267 |
+
value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
|
268 |
+
|
269 |
+
inner_dim = key.shape[-1]
|
270 |
+
head_dim = inner_dim // attn.heads
|
271 |
+
|
272 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
273 |
+
|
274 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
275 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
276 |
+
|
277 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
278 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
279 |
+
hidden_states = F.scaled_dot_product_attention(
|
280 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
281 |
+
)
|
282 |
+
|
283 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
284 |
+
hidden_states = hidden_states.to(query.dtype)
|
285 |
+
|
286 |
+
# linear proj
|
287 |
+
hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
|
288 |
+
# dropout
|
289 |
+
hidden_states = attn.to_out[1](hidden_states)
|
290 |
+
|
291 |
+
if input_ndim == 4:
|
292 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
293 |
+
|
294 |
+
if attn.residual_connection:
|
295 |
+
hidden_states = hidden_states + residual
|
296 |
+
|
297 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
298 |
+
|
299 |
+
return hidden_states
|
300 |
+
|
301 |
+
|
302 |
+
class LoRAIPAttnProcessor2_0(nn.Module):
|
303 |
+
r"""
|
304 |
+
Processor for implementing the LoRA attention mechanism.
|
305 |
+
|
306 |
+
Args:
|
307 |
+
hidden_size (`int`, *optional*):
|
308 |
+
The hidden size of the attention layer.
|
309 |
+
cross_attention_dim (`int`, *optional*):
|
310 |
+
The number of channels in the `encoder_hidden_states`.
|
311 |
+
rank (`int`, defaults to 4):
|
312 |
+
The dimension of the LoRA update matrices.
|
313 |
+
network_alpha (`int`, *optional*):
|
314 |
+
Equivalent to `alpha` but it's usage is specific to Kohya (A1111) style LoRAs.
|
315 |
+
"""
|
316 |
+
|
317 |
+
def __init__(self, hidden_size, cross_attention_dim=None, rank=4, network_alpha=None, lora_scale=1.0, scale=1.0, num_tokens=4):
|
318 |
+
super().__init__()
|
319 |
+
|
320 |
+
self.rank = rank
|
321 |
+
self.lora_scale = lora_scale
|
322 |
+
self.num_tokens = num_tokens
|
323 |
+
|
324 |
+
self.to_q_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
325 |
+
self.to_k_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
326 |
+
self.to_v_lora = LoRALinearLayer(cross_attention_dim or hidden_size, hidden_size, rank, network_alpha)
|
327 |
+
self.to_out_lora = LoRALinearLayer(hidden_size, hidden_size, rank, network_alpha)
|
328 |
+
|
329 |
+
|
330 |
+
self.hidden_size = hidden_size
|
331 |
+
self.cross_attention_dim = cross_attention_dim
|
332 |
+
self.scale = scale
|
333 |
+
|
334 |
+
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
335 |
+
self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
|
336 |
+
|
337 |
+
def __call__(
|
338 |
+
self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, scale=1.0, temb=None
|
339 |
+
):
|
340 |
+
residual = hidden_states
|
341 |
+
|
342 |
+
if attn.spatial_norm is not None:
|
343 |
+
hidden_states = attn.spatial_norm(hidden_states, temb)
|
344 |
+
|
345 |
+
input_ndim = hidden_states.ndim
|
346 |
+
|
347 |
+
if input_ndim == 4:
|
348 |
+
batch_size, channel, height, width = hidden_states.shape
|
349 |
+
hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
|
350 |
+
|
351 |
+
batch_size, sequence_length, _ = (
|
352 |
+
hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape
|
353 |
+
)
|
354 |
+
attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
|
355 |
+
|
356 |
+
if attn.group_norm is not None:
|
357 |
+
hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
|
358 |
+
|
359 |
+
query = attn.to_q(hidden_states) + self.lora_scale * self.to_q_lora(hidden_states)
|
360 |
+
#query = attn.head_to_batch_dim(query)
|
361 |
+
|
362 |
+
if encoder_hidden_states is None:
|
363 |
+
encoder_hidden_states = hidden_states
|
364 |
+
else:
|
365 |
+
# get encoder_hidden_states, ip_hidden_states
|
366 |
+
end_pos = encoder_hidden_states.shape[1] - self.num_tokens
|
367 |
+
encoder_hidden_states, ip_hidden_states = (
|
368 |
+
encoder_hidden_states[:, :end_pos, :],
|
369 |
+
encoder_hidden_states[:, end_pos:, :],
|
370 |
+
)
|
371 |
+
if attn.norm_cross:
|
372 |
+
encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
|
373 |
+
|
374 |
+
# for text
|
375 |
+
key = attn.to_k(encoder_hidden_states) + self.lora_scale * self.to_k_lora(encoder_hidden_states)
|
376 |
+
value = attn.to_v(encoder_hidden_states) + self.lora_scale * self.to_v_lora(encoder_hidden_states)
|
377 |
+
|
378 |
+
inner_dim = key.shape[-1]
|
379 |
+
head_dim = inner_dim // attn.heads
|
380 |
+
|
381 |
+
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
382 |
+
|
383 |
+
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
384 |
+
value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
385 |
+
|
386 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
387 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
388 |
+
hidden_states = F.scaled_dot_product_attention(
|
389 |
+
query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False
|
390 |
+
)
|
391 |
+
|
392 |
+
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
393 |
+
hidden_states = hidden_states.to(query.dtype)
|
394 |
+
|
395 |
+
# for ip
|
396 |
+
ip_key = self.to_k_ip(ip_hidden_states)
|
397 |
+
ip_value = self.to_v_ip(ip_hidden_states)
|
398 |
+
|
399 |
+
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
400 |
+
ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
|
401 |
+
|
402 |
+
# the output of sdp = (batch, num_heads, seq_len, head_dim)
|
403 |
+
# TODO: add support for attn.scale when we move to Torch 2.1
|
404 |
+
ip_hidden_states = F.scaled_dot_product_attention(
|
405 |
+
query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False
|
406 |
+
)
|
407 |
+
|
408 |
+
|
409 |
+
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim)
|
410 |
+
ip_hidden_states = ip_hidden_states.to(query.dtype)
|
411 |
+
|
412 |
+
hidden_states = hidden_states + self.scale * ip_hidden_states
|
413 |
+
|
414 |
+
# linear proj
|
415 |
+
hidden_states = attn.to_out[0](hidden_states) + self.lora_scale * self.to_out_lora(hidden_states)
|
416 |
+
# dropout
|
417 |
+
hidden_states = attn.to_out[1](hidden_states)
|
418 |
+
|
419 |
+
if input_ndim == 4:
|
420 |
+
hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
|
421 |
+
|
422 |
+
if attn.residual_connection:
|
423 |
+
hidden_states = hidden_states + residual
|
424 |
+
|
425 |
+
hidden_states = hidden_states / attn.rescale_output_factor
|
426 |
+
|
427 |
+
return hidden_states
|
ip_adapter/custom_pipelines.py
ADDED
@@ -0,0 +1,394 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from typing import Any, Callable, Dict, List, Optional, Tuple, Union
|
2 |
+
|
3 |
+
import torch
|
4 |
+
from diffusers import StableDiffusionXLPipeline
|
5 |
+
from diffusers.pipelines.stable_diffusion_xl import StableDiffusionXLPipelineOutput
|
6 |
+
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import rescale_noise_cfg
|
7 |
+
|
8 |
+
from .utils import is_torch2_available
|
9 |
+
|
10 |
+
if is_torch2_available():
|
11 |
+
from .attention_processor import IPAttnProcessor2_0 as IPAttnProcessor
|
12 |
+
else:
|
13 |
+
from .attention_processor import IPAttnProcessor
|
14 |
+
|
15 |
+
|
16 |
+
class StableDiffusionXLCustomPipeline(StableDiffusionXLPipeline):
|
17 |
+
def set_scale(self, scale):
|
18 |
+
for attn_processor in self.unet.attn_processors.values():
|
19 |
+
if isinstance(attn_processor, IPAttnProcessor):
|
20 |
+
attn_processor.scale = scale
|
21 |
+
|
22 |
+
@torch.no_grad()
|
23 |
+
def __call__( # noqa: C901
|
24 |
+
self,
|
25 |
+
prompt: Optional[Union[str, List[str]]] = None,
|
26 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
27 |
+
height: Optional[int] = None,
|
28 |
+
width: Optional[int] = None,
|
29 |
+
num_inference_steps: int = 50,
|
30 |
+
denoising_end: Optional[float] = None,
|
31 |
+
guidance_scale: float = 5.0,
|
32 |
+
negative_prompt: Optional[Union[str, List[str]]] = None,
|
33 |
+
negative_prompt_2: Optional[Union[str, List[str]]] = None,
|
34 |
+
num_images_per_prompt: Optional[int] = 1,
|
35 |
+
eta: float = 0.0,
|
36 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
37 |
+
latents: Optional[torch.FloatTensor] = None,
|
38 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
39 |
+
negative_prompt_embeds: Optional[torch.FloatTensor] = None,
|
40 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
41 |
+
negative_pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
42 |
+
output_type: Optional[str] = "pil",
|
43 |
+
return_dict: bool = True,
|
44 |
+
callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
|
45 |
+
callback_steps: int = 1,
|
46 |
+
cross_attention_kwargs: Optional[Dict[str, Any]] = None,
|
47 |
+
guidance_rescale: float = 0.0,
|
48 |
+
original_size: Optional[Tuple[int, int]] = None,
|
49 |
+
crops_coords_top_left: Tuple[int, int] = (0, 0),
|
50 |
+
target_size: Optional[Tuple[int, int]] = None,
|
51 |
+
negative_original_size: Optional[Tuple[int, int]] = None,
|
52 |
+
negative_crops_coords_top_left: Tuple[int, int] = (0, 0),
|
53 |
+
negative_target_size: Optional[Tuple[int, int]] = None,
|
54 |
+
control_guidance_start: float = 0.0,
|
55 |
+
control_guidance_end: float = 1.0,
|
56 |
+
):
|
57 |
+
r"""
|
58 |
+
Function invoked when calling the pipeline for generation.
|
59 |
+
|
60 |
+
Args:
|
61 |
+
prompt (`str` or `List[str]`, *optional*):
|
62 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
63 |
+
instead.
|
64 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
65 |
+
The prompt or prompts to be sent to the `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
66 |
+
used in both text-encoders
|
67 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
68 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
69 |
+
Anything below 512 pixels won't work well for
|
70 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
71 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
72 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
73 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
74 |
+
Anything below 512 pixels won't work well for
|
75 |
+
[stabilityai/stable-diffusion-xl-base-1.0](https://huggingface.co/stabilityai/stable-diffusion-xl-base-1.0)
|
76 |
+
and checkpoints that are not specifically fine-tuned on low resolutions.
|
77 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
78 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
79 |
+
expense of slower inference.
|
80 |
+
denoising_end (`float`, *optional*):
|
81 |
+
When specified, determines the fraction (between 0.0 and 1.0) of the total denoising process to be
|
82 |
+
completed before it is intentionally prematurely terminated. As a result, the returned sample will
|
83 |
+
still retain a substantial amount of noise as determined by the discrete timesteps selected by the
|
84 |
+
scheduler. The denoising_end parameter should ideally be utilized when this pipeline forms a part of a
|
85 |
+
"Mixture of Denoisers" multi-pipeline setup, as elaborated in [**Refining the Image
|
86 |
+
Output**](https://huggingface.co/docs/diffusers/api/pipelines/stable_diffusion/stable_diffusion_xl#refining-the-image-output)
|
87 |
+
guidance_scale (`float`, *optional*, defaults to 5.0):
|
88 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
89 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
90 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
91 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
92 |
+
usually at the expense of lower image quality.
|
93 |
+
negative_prompt (`str` or `List[str]`, *optional*):
|
94 |
+
The prompt or prompts not to guide the image generation. If not defined, one has to pass
|
95 |
+
`negative_prompt_embeds` instead. Ignored when not using guidance (i.e., ignored if `guidance_scale` is
|
96 |
+
less than `1`).
|
97 |
+
negative_prompt_2 (`str` or `List[str]`, *optional*):
|
98 |
+
The prompt or prompts not to guide the image generation to be sent to `tokenizer_2` and
|
99 |
+
`text_encoder_2`. If not defined, `negative_prompt` is used in both text-encoders
|
100 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
101 |
+
The number of images to generate per prompt.
|
102 |
+
eta (`float`, *optional*, defaults to 0.0):
|
103 |
+
Corresponds to parameter eta (Ξ·) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
|
104 |
+
[`schedulers.DDIMScheduler`], will be ignored for others.
|
105 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
106 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
107 |
+
to make generation deterministic.
|
108 |
+
latents (`torch.FloatTensor`, *optional*):
|
109 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
110 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
111 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
112 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
113 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
114 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
115 |
+
negative_prompt_embeds (`torch.FloatTensor`, *optional*):
|
116 |
+
Pre-generated negative text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
117 |
+
weighting. If not provided, negative_prompt_embeds will be generated from `negative_prompt` input
|
118 |
+
argument.
|
119 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
120 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
121 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
122 |
+
negative_pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
123 |
+
Pre-generated negative pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt
|
124 |
+
weighting. If not provided, pooled negative_prompt_embeds will be generated from `negative_prompt`
|
125 |
+
input argument.
|
126 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
127 |
+
The output format of the generate image. Choose between
|
128 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
129 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
130 |
+
Whether or not to return a [`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] instead
|
131 |
+
of a plain tuple.
|
132 |
+
callback (`Callable`, *optional*):
|
133 |
+
A function that will be called every `callback_steps` steps during inference. The function will be
|
134 |
+
called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
|
135 |
+
callback_steps (`int`, *optional*, defaults to 1):
|
136 |
+
The frequency at which the `callback` function will be called. If not specified, the callback will be
|
137 |
+
called at every step.
|
138 |
+
cross_attention_kwargs (`dict`, *optional*):
|
139 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
140 |
+
`self.processor` in
|
141 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
142 |
+
guidance_rescale (`float`, *optional*, defaults to 0.7):
|
143 |
+
Guidance rescale factor proposed by [Common Diffusion Noise Schedules and Sample Steps are
|
144 |
+
Flawed](https://arxiv.org/pdf/2305.08891.pdf) `guidance_scale` is defined as `Ο` in equation 16. of
|
145 |
+
[Common Diffusion Noise Schedules and Sample Steps are Flawed](https://arxiv.org/pdf/2305.08891.pdf).
|
146 |
+
Guidance rescale factor should fix overexposure when using zero terminal SNR.
|
147 |
+
original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
148 |
+
If `original_size` is not the same as `target_size` the image will appear to be down- or upsampled.
|
149 |
+
`original_size` defaults to `(width, height)` if not specified. Part of SDXL's micro-conditioning as
|
150 |
+
explained in section 2.2 of
|
151 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
152 |
+
crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
153 |
+
`crops_coords_top_left` can be used to generate an image that appears to be "cropped" from the position
|
154 |
+
`crops_coords_top_left` downwards. Favorable, well-centered images are usually achieved by setting
|
155 |
+
`crops_coords_top_left` to (0, 0). Part of SDXL's micro-conditioning as explained in section 2.2 of
|
156 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
157 |
+
target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
158 |
+
For most cases, `target_size` should be set to the desired height and width of the generated image. If
|
159 |
+
not specified it will default to `(width, height)`. Part of SDXL's micro-conditioning as explained in
|
160 |
+
section 2.2 of [https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952).
|
161 |
+
negative_original_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
162 |
+
To negatively condition the generation process based on a specific image resolution. Part of SDXL's
|
163 |
+
micro-conditioning as explained in section 2.2 of
|
164 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
165 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
166 |
+
negative_crops_coords_top_left (`Tuple[int]`, *optional*, defaults to (0, 0)):
|
167 |
+
To negatively condition the generation process based on a specific crop coordinates. Part of SDXL's
|
168 |
+
micro-conditioning as explained in section 2.2 of
|
169 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
170 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
171 |
+
negative_target_size (`Tuple[int]`, *optional*, defaults to (1024, 1024)):
|
172 |
+
To negatively condition the generation process based on a target image resolution. It should be as same
|
173 |
+
as the `target_size` for most cases. Part of SDXL's micro-conditioning as explained in section 2.2 of
|
174 |
+
[https://huggingface.co/papers/2307.01952](https://huggingface.co/papers/2307.01952). For more
|
175 |
+
information, refer to this issue thread: https://github.com/huggingface/diffusers/issues/4208.
|
176 |
+
control_guidance_start (`float`, *optional*, defaults to 0.0):
|
177 |
+
The percentage of total steps at which the ControlNet starts applying.
|
178 |
+
control_guidance_end (`float`, *optional*, defaults to 1.0):
|
179 |
+
The percentage of total steps at which the ControlNet stops applying.
|
180 |
+
|
181 |
+
Examples:
|
182 |
+
|
183 |
+
Returns:
|
184 |
+
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] or `tuple`:
|
185 |
+
[`~pipelines.stable_diffusion_xl.StableDiffusionXLPipelineOutput`] if `return_dict` is True, otherwise a
|
186 |
+
`tuple`. When returning a tuple, the first element is a list with the generated images.
|
187 |
+
"""
|
188 |
+
# 0. Default height and width to unet
|
189 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
190 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
191 |
+
|
192 |
+
original_size = original_size or (height, width)
|
193 |
+
target_size = target_size or (height, width)
|
194 |
+
|
195 |
+
# 1. Check inputs. Raise error if not correct
|
196 |
+
self.check_inputs(
|
197 |
+
prompt,
|
198 |
+
prompt_2,
|
199 |
+
height,
|
200 |
+
width,
|
201 |
+
callback_steps,
|
202 |
+
negative_prompt,
|
203 |
+
negative_prompt_2,
|
204 |
+
prompt_embeds,
|
205 |
+
negative_prompt_embeds,
|
206 |
+
pooled_prompt_embeds,
|
207 |
+
negative_pooled_prompt_embeds,
|
208 |
+
)
|
209 |
+
|
210 |
+
# 2. Define call parameters
|
211 |
+
if prompt is not None and isinstance(prompt, str):
|
212 |
+
batch_size = 1
|
213 |
+
elif prompt is not None and isinstance(prompt, list):
|
214 |
+
batch_size = len(prompt)
|
215 |
+
else:
|
216 |
+
batch_size = prompt_embeds.shape[0]
|
217 |
+
|
218 |
+
device = self._execution_device
|
219 |
+
|
220 |
+
# here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
|
221 |
+
# of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
|
222 |
+
# corresponds to doing no classifier free guidance.
|
223 |
+
do_classifier_free_guidance = guidance_scale > 1.0
|
224 |
+
|
225 |
+
# 3. Encode input prompt
|
226 |
+
text_encoder_lora_scale = (
|
227 |
+
cross_attention_kwargs.get("scale", None) if cross_attention_kwargs is not None else None
|
228 |
+
)
|
229 |
+
(
|
230 |
+
prompt_embeds,
|
231 |
+
negative_prompt_embeds,
|
232 |
+
pooled_prompt_embeds,
|
233 |
+
negative_pooled_prompt_embeds,
|
234 |
+
) = self.encode_prompt(
|
235 |
+
prompt=prompt,
|
236 |
+
prompt_2=prompt_2,
|
237 |
+
device=device,
|
238 |
+
num_images_per_prompt=num_images_per_prompt,
|
239 |
+
do_classifier_free_guidance=do_classifier_free_guidance,
|
240 |
+
negative_prompt=negative_prompt,
|
241 |
+
negative_prompt_2=negative_prompt_2,
|
242 |
+
prompt_embeds=prompt_embeds,
|
243 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
244 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
245 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
246 |
+
lora_scale=text_encoder_lora_scale,
|
247 |
+
)
|
248 |
+
|
249 |
+
# 4. Prepare timesteps
|
250 |
+
self.scheduler.set_timesteps(num_inference_steps, device=device)
|
251 |
+
|
252 |
+
timesteps = self.scheduler.timesteps
|
253 |
+
|
254 |
+
# 5. Prepare latent variables
|
255 |
+
num_channels_latents = self.unet.config.in_channels
|
256 |
+
latents = self.prepare_latents(
|
257 |
+
batch_size * num_images_per_prompt,
|
258 |
+
num_channels_latents,
|
259 |
+
height,
|
260 |
+
width,
|
261 |
+
prompt_embeds.dtype,
|
262 |
+
device,
|
263 |
+
generator,
|
264 |
+
latents,
|
265 |
+
)
|
266 |
+
|
267 |
+
# 6. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
|
268 |
+
extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
|
269 |
+
|
270 |
+
# 7. Prepare added time ids & embeddings
|
271 |
+
add_text_embeds = pooled_prompt_embeds
|
272 |
+
if self.text_encoder_2 is None:
|
273 |
+
text_encoder_projection_dim = int(pooled_prompt_embeds.shape[-1])
|
274 |
+
else:
|
275 |
+
text_encoder_projection_dim = self.text_encoder_2.config.projection_dim
|
276 |
+
|
277 |
+
add_time_ids = self._get_add_time_ids(
|
278 |
+
original_size,
|
279 |
+
crops_coords_top_left,
|
280 |
+
target_size,
|
281 |
+
dtype=prompt_embeds.dtype,
|
282 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
283 |
+
)
|
284 |
+
if negative_original_size is not None and negative_target_size is not None:
|
285 |
+
negative_add_time_ids = self._get_add_time_ids(
|
286 |
+
negative_original_size,
|
287 |
+
negative_crops_coords_top_left,
|
288 |
+
negative_target_size,
|
289 |
+
dtype=prompt_embeds.dtype,
|
290 |
+
text_encoder_projection_dim=text_encoder_projection_dim,
|
291 |
+
)
|
292 |
+
else:
|
293 |
+
negative_add_time_ids = add_time_ids
|
294 |
+
|
295 |
+
if do_classifier_free_guidance:
|
296 |
+
prompt_embeds = torch.cat([negative_prompt_embeds, prompt_embeds], dim=0)
|
297 |
+
add_text_embeds = torch.cat([negative_pooled_prompt_embeds, add_text_embeds], dim=0)
|
298 |
+
add_time_ids = torch.cat([negative_add_time_ids, add_time_ids], dim=0)
|
299 |
+
|
300 |
+
prompt_embeds = prompt_embeds.to(device)
|
301 |
+
add_text_embeds = add_text_embeds.to(device)
|
302 |
+
add_time_ids = add_time_ids.to(device).repeat(batch_size * num_images_per_prompt, 1)
|
303 |
+
|
304 |
+
# 8. Denoising loop
|
305 |
+
num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
|
306 |
+
|
307 |
+
# 7.1 Apply denoising_end
|
308 |
+
if denoising_end is not None and isinstance(denoising_end, float) and denoising_end > 0 and denoising_end < 1:
|
309 |
+
discrete_timestep_cutoff = int(
|
310 |
+
round(
|
311 |
+
self.scheduler.config.num_train_timesteps
|
312 |
+
- (denoising_end * self.scheduler.config.num_train_timesteps)
|
313 |
+
)
|
314 |
+
)
|
315 |
+
num_inference_steps = len(list(filter(lambda ts: ts >= discrete_timestep_cutoff, timesteps)))
|
316 |
+
timesteps = timesteps[:num_inference_steps]
|
317 |
+
|
318 |
+
# get init conditioning scale
|
319 |
+
for attn_processor in self.unet.attn_processors.values():
|
320 |
+
if isinstance(attn_processor, IPAttnProcessor):
|
321 |
+
conditioning_scale = attn_processor.scale
|
322 |
+
break
|
323 |
+
|
324 |
+
with self.progress_bar(total=num_inference_steps) as progress_bar:
|
325 |
+
for i, t in enumerate(timesteps):
|
326 |
+
if (i / len(timesteps) < control_guidance_start) or ((i + 1) / len(timesteps) > control_guidance_end):
|
327 |
+
self.set_scale(0.0)
|
328 |
+
else:
|
329 |
+
self.set_scale(conditioning_scale)
|
330 |
+
|
331 |
+
# expand the latents if we are doing classifier free guidance
|
332 |
+
latent_model_input = torch.cat([latents] * 2) if do_classifier_free_guidance else latents
|
333 |
+
|
334 |
+
latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
|
335 |
+
|
336 |
+
# predict the noise residual
|
337 |
+
added_cond_kwargs = {"text_embeds": add_text_embeds, "time_ids": add_time_ids}
|
338 |
+
noise_pred = self.unet(
|
339 |
+
latent_model_input,
|
340 |
+
t,
|
341 |
+
encoder_hidden_states=prompt_embeds,
|
342 |
+
cross_attention_kwargs=cross_attention_kwargs,
|
343 |
+
added_cond_kwargs=added_cond_kwargs,
|
344 |
+
return_dict=False,
|
345 |
+
)[0]
|
346 |
+
|
347 |
+
# perform guidance
|
348 |
+
if do_classifier_free_guidance:
|
349 |
+
noise_pred_uncond, noise_pred_text = noise_pred.chunk(2)
|
350 |
+
noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
|
351 |
+
|
352 |
+
if do_classifier_free_guidance and guidance_rescale > 0.0:
|
353 |
+
# Based on 3.4. in https://arxiv.org/pdf/2305.08891.pdf
|
354 |
+
noise_pred = rescale_noise_cfg(noise_pred, noise_pred_text, guidance_rescale=guidance_rescale)
|
355 |
+
|
356 |
+
# compute the previous noisy sample x_t -> x_t-1
|
357 |
+
latents = self.scheduler.step(noise_pred, t, latents, **extra_step_kwargs, return_dict=False)[0]
|
358 |
+
|
359 |
+
# call the callback, if provided
|
360 |
+
if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
|
361 |
+
progress_bar.update()
|
362 |
+
if callback is not None and i % callback_steps == 0:
|
363 |
+
callback(i, t, latents)
|
364 |
+
|
365 |
+
if not output_type == "latent":
|
366 |
+
# make sure the VAE is in float32 mode, as it overflows in float16
|
367 |
+
needs_upcasting = self.vae.dtype == torch.float16 and self.vae.config.force_upcast
|
368 |
+
|
369 |
+
if needs_upcasting:
|
370 |
+
self.upcast_vae()
|
371 |
+
latents = latents.to(next(iter(self.vae.post_quant_conv.parameters())).dtype)
|
372 |
+
|
373 |
+
image = self.vae.decode(latents / self.vae.config.scaling_factor, return_dict=False)[0]
|
374 |
+
|
375 |
+
# cast back to fp16 if needed
|
376 |
+
if needs_upcasting:
|
377 |
+
self.vae.to(dtype=torch.float16)
|
378 |
+
else:
|
379 |
+
image = latents
|
380 |
+
|
381 |
+
if output_type != "latent":
|
382 |
+
# apply watermark if available
|
383 |
+
if self.watermark is not None:
|
384 |
+
image = self.watermark.apply_watermark(image)
|
385 |
+
|
386 |
+
image = self.image_processor.postprocess(image, output_type=output_type)
|
387 |
+
|
388 |
+
# Offload all models
|
389 |
+
self.maybe_free_model_hooks()
|
390 |
+
|
391 |
+
if not return_dict:
|
392 |
+
return (image,)
|
393 |
+
|
394 |
+
return StableDiffusionXLPipelineOutput(images=image)
|
ip_adapter/ip_adapter.py
ADDED
@@ -0,0 +1,417 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from diffusers import StableDiffusionPipeline
|
6 |
+
from diffusers.pipelines.controlnet import MultiControlNetModel
|
7 |
+
from PIL import Image
|
8 |
+
from safetensors import safe_open
|
9 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
10 |
+
|
11 |
+
from .utils import is_torch2_available, get_generator
|
12 |
+
|
13 |
+
if is_torch2_available():
|
14 |
+
from .attention_processor import (
|
15 |
+
AttnProcessor2_0 as AttnProcessor,
|
16 |
+
)
|
17 |
+
from .attention_processor import (
|
18 |
+
CNAttnProcessor2_0 as CNAttnProcessor,
|
19 |
+
)
|
20 |
+
from .attention_processor import (
|
21 |
+
IPAttnProcessor2_0 as IPAttnProcessor,
|
22 |
+
)
|
23 |
+
else:
|
24 |
+
from .attention_processor import AttnProcessor, CNAttnProcessor, IPAttnProcessor
|
25 |
+
from .resampler import Resampler
|
26 |
+
|
27 |
+
|
28 |
+
class ImageProjModel(torch.nn.Module):
|
29 |
+
"""Projection Model"""
|
30 |
+
|
31 |
+
def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4):
|
32 |
+
super().__init__()
|
33 |
+
|
34 |
+
self.generator = None
|
35 |
+
self.cross_attention_dim = cross_attention_dim
|
36 |
+
self.clip_extra_context_tokens = clip_extra_context_tokens
|
37 |
+
self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim)
|
38 |
+
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
39 |
+
|
40 |
+
def forward(self, image_embeds):
|
41 |
+
embeds = image_embeds
|
42 |
+
clip_extra_context_tokens = self.proj(embeds).reshape(
|
43 |
+
-1, self.clip_extra_context_tokens, self.cross_attention_dim
|
44 |
+
)
|
45 |
+
clip_extra_context_tokens = self.norm(clip_extra_context_tokens)
|
46 |
+
return clip_extra_context_tokens
|
47 |
+
|
48 |
+
|
49 |
+
class MLPProjModel(torch.nn.Module):
|
50 |
+
"""SD model with image prompt"""
|
51 |
+
def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024):
|
52 |
+
super().__init__()
|
53 |
+
|
54 |
+
self.proj = torch.nn.Sequential(
|
55 |
+
torch.nn.Linear(clip_embeddings_dim, clip_embeddings_dim),
|
56 |
+
torch.nn.GELU(),
|
57 |
+
torch.nn.Linear(clip_embeddings_dim, cross_attention_dim),
|
58 |
+
torch.nn.LayerNorm(cross_attention_dim)
|
59 |
+
)
|
60 |
+
|
61 |
+
def forward(self, image_embeds):
|
62 |
+
clip_extra_context_tokens = self.proj(image_embeds)
|
63 |
+
return clip_extra_context_tokens
|
64 |
+
|
65 |
+
|
66 |
+
class IPAdapter:
|
67 |
+
def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_tokens=4):
|
68 |
+
self.device = device
|
69 |
+
self.image_encoder_path = image_encoder_path
|
70 |
+
self.ip_ckpt = ip_ckpt
|
71 |
+
self.num_tokens = num_tokens
|
72 |
+
|
73 |
+
self.pipe = sd_pipe.to(self.device)
|
74 |
+
self.set_ip_adapter()
|
75 |
+
|
76 |
+
# load image encoder
|
77 |
+
self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to(
|
78 |
+
self.device, dtype=torch.float16
|
79 |
+
)
|
80 |
+
self.clip_image_processor = CLIPImageProcessor()
|
81 |
+
# image proj model
|
82 |
+
self.image_proj_model = self.init_proj()
|
83 |
+
|
84 |
+
self.load_ip_adapter()
|
85 |
+
|
86 |
+
def init_proj(self):
|
87 |
+
image_proj_model = ImageProjModel(
|
88 |
+
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
89 |
+
clip_embeddings_dim=self.image_encoder.config.projection_dim,
|
90 |
+
clip_extra_context_tokens=self.num_tokens,
|
91 |
+
).to(self.device, dtype=torch.float16)
|
92 |
+
return image_proj_model
|
93 |
+
|
94 |
+
def set_ip_adapter(self):
|
95 |
+
unet = self.pipe.unet
|
96 |
+
attn_procs = {}
|
97 |
+
for name in unet.attn_processors.keys():
|
98 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
99 |
+
if name.startswith("mid_block"):
|
100 |
+
hidden_size = unet.config.block_out_channels[-1]
|
101 |
+
elif name.startswith("up_blocks"):
|
102 |
+
block_id = int(name[len("up_blocks.")])
|
103 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
104 |
+
elif name.startswith("down_blocks"):
|
105 |
+
block_id = int(name[len("down_blocks.")])
|
106 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
107 |
+
if cross_attention_dim is None:
|
108 |
+
attn_procs[name] = AttnProcessor()
|
109 |
+
else:
|
110 |
+
attn_procs[name] = IPAttnProcessor(
|
111 |
+
hidden_size=hidden_size,
|
112 |
+
cross_attention_dim=cross_attention_dim,
|
113 |
+
scale=1.0,
|
114 |
+
num_tokens=self.num_tokens,
|
115 |
+
).to(self.device, dtype=torch.float16)
|
116 |
+
unet.set_attn_processor(attn_procs)
|
117 |
+
if hasattr(self.pipe, "controlnet"):
|
118 |
+
if isinstance(self.pipe.controlnet, MultiControlNetModel):
|
119 |
+
for controlnet in self.pipe.controlnet.nets:
|
120 |
+
controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
|
121 |
+
else:
|
122 |
+
self.pipe.controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
|
123 |
+
|
124 |
+
def load_ip_adapter(self):
|
125 |
+
if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors":
|
126 |
+
state_dict = {"image_proj": {}, "ip_adapter": {}}
|
127 |
+
with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f:
|
128 |
+
for key in f.keys():
|
129 |
+
if key.startswith("image_proj."):
|
130 |
+
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
|
131 |
+
elif key.startswith("ip_adapter."):
|
132 |
+
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
|
133 |
+
else:
|
134 |
+
state_dict = torch.load(self.ip_ckpt, map_location="cpu")
|
135 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"])
|
136 |
+
ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
|
137 |
+
ip_layers.load_state_dict(state_dict["ip_adapter"])
|
138 |
+
|
139 |
+
@torch.inference_mode()
|
140 |
+
def get_image_embeds(self, pil_image=None, clip_image_embeds=None):
|
141 |
+
if pil_image is not None:
|
142 |
+
if isinstance(pil_image, Image.Image):
|
143 |
+
pil_image = [pil_image]
|
144 |
+
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
|
145 |
+
clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds
|
146 |
+
else:
|
147 |
+
clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16)
|
148 |
+
image_prompt_embeds = self.image_proj_model(clip_image_embeds)
|
149 |
+
uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(clip_image_embeds))
|
150 |
+
return image_prompt_embeds, uncond_image_prompt_embeds
|
151 |
+
|
152 |
+
def set_scale(self, scale):
|
153 |
+
for attn_processor in self.pipe.unet.attn_processors.values():
|
154 |
+
if isinstance(attn_processor, IPAttnProcessor):
|
155 |
+
attn_processor.scale = scale
|
156 |
+
|
157 |
+
def generate(
|
158 |
+
self,
|
159 |
+
pil_image=None,
|
160 |
+
clip_image_embeds=None,
|
161 |
+
prompt=None,
|
162 |
+
negative_prompt=None,
|
163 |
+
scale=1.0,
|
164 |
+
num_samples=4,
|
165 |
+
seed=None,
|
166 |
+
guidance_scale=7.5,
|
167 |
+
num_inference_steps=30,
|
168 |
+
**kwargs,
|
169 |
+
):
|
170 |
+
self.set_scale(scale)
|
171 |
+
|
172 |
+
if pil_image is not None:
|
173 |
+
num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
|
174 |
+
else:
|
175 |
+
num_prompts = clip_image_embeds.size(0)
|
176 |
+
|
177 |
+
if prompt is None:
|
178 |
+
prompt = "best quality, high quality"
|
179 |
+
if negative_prompt is None:
|
180 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
181 |
+
|
182 |
+
if not isinstance(prompt, List):
|
183 |
+
prompt = [prompt] * num_prompts
|
184 |
+
if not isinstance(negative_prompt, List):
|
185 |
+
negative_prompt = [negative_prompt] * num_prompts
|
186 |
+
|
187 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(
|
188 |
+
pil_image=pil_image, clip_image_embeds=clip_image_embeds
|
189 |
+
)
|
190 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
191 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
192 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
193 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
194 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
195 |
+
|
196 |
+
with torch.inference_mode():
|
197 |
+
prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt(
|
198 |
+
prompt,
|
199 |
+
device=self.device,
|
200 |
+
num_images_per_prompt=num_samples,
|
201 |
+
do_classifier_free_guidance=True,
|
202 |
+
negative_prompt=negative_prompt,
|
203 |
+
)
|
204 |
+
prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
|
205 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
|
206 |
+
|
207 |
+
generator = get_generator(seed, self.device)
|
208 |
+
|
209 |
+
images = self.pipe(
|
210 |
+
prompt_embeds=prompt_embeds,
|
211 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
212 |
+
guidance_scale=guidance_scale,
|
213 |
+
num_inference_steps=num_inference_steps,
|
214 |
+
generator=generator,
|
215 |
+
**kwargs,
|
216 |
+
).images
|
217 |
+
|
218 |
+
return images
|
219 |
+
|
220 |
+
|
221 |
+
class IPAdapterXL(IPAdapter):
|
222 |
+
"""SDXL"""
|
223 |
+
|
224 |
+
def generate(
|
225 |
+
self,
|
226 |
+
pil_image,
|
227 |
+
prompt=None,
|
228 |
+
negative_prompt=None,
|
229 |
+
scale=1.0,
|
230 |
+
num_samples=4,
|
231 |
+
seed=None,
|
232 |
+
num_inference_steps=30,
|
233 |
+
**kwargs,
|
234 |
+
):
|
235 |
+
self.set_scale(scale)
|
236 |
+
|
237 |
+
num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
|
238 |
+
|
239 |
+
if prompt is None:
|
240 |
+
prompt = "best quality, high quality"
|
241 |
+
if negative_prompt is None:
|
242 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
243 |
+
|
244 |
+
if not isinstance(prompt, List):
|
245 |
+
prompt = [prompt] * num_prompts
|
246 |
+
if not isinstance(negative_prompt, List):
|
247 |
+
negative_prompt = [negative_prompt] * num_prompts
|
248 |
+
|
249 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
|
250 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
251 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
252 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
253 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
254 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
255 |
+
|
256 |
+
with torch.inference_mode():
|
257 |
+
(
|
258 |
+
prompt_embeds,
|
259 |
+
negative_prompt_embeds,
|
260 |
+
pooled_prompt_embeds,
|
261 |
+
negative_pooled_prompt_embeds,
|
262 |
+
) = self.pipe.encode_prompt(
|
263 |
+
prompt,
|
264 |
+
num_images_per_prompt=num_samples,
|
265 |
+
do_classifier_free_guidance=True,
|
266 |
+
negative_prompt=negative_prompt,
|
267 |
+
)
|
268 |
+
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
269 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
270 |
+
|
271 |
+
self.generator = get_generator(seed, self.device)
|
272 |
+
|
273 |
+
images = self.pipe(
|
274 |
+
prompt_embeds=prompt_embeds,
|
275 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
276 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
277 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
278 |
+
num_inference_steps=num_inference_steps,
|
279 |
+
generator=self.generator,
|
280 |
+
**kwargs,
|
281 |
+
).images
|
282 |
+
|
283 |
+
return images
|
284 |
+
|
285 |
+
|
286 |
+
class IPAdapterPlus(IPAdapter):
|
287 |
+
"""IP-Adapter with fine-grained features"""
|
288 |
+
|
289 |
+
def init_proj(self):
|
290 |
+
image_proj_model = Resampler(
|
291 |
+
dim=self.pipe.unet.config.cross_attention_dim,
|
292 |
+
depth=4,
|
293 |
+
dim_head=64,
|
294 |
+
heads=12,
|
295 |
+
num_queries=self.num_tokens,
|
296 |
+
embedding_dim=self.image_encoder.config.hidden_size,
|
297 |
+
output_dim=self.pipe.unet.config.cross_attention_dim,
|
298 |
+
ff_mult=4,
|
299 |
+
).to(self.device, dtype=torch.float16)
|
300 |
+
return image_proj_model
|
301 |
+
|
302 |
+
@torch.inference_mode()
|
303 |
+
def get_image_embeds(self, pil_image=None, clip_image_embeds=None):
|
304 |
+
if isinstance(pil_image, Image.Image):
|
305 |
+
pil_image = [pil_image]
|
306 |
+
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
|
307 |
+
clip_image = clip_image.to(self.device, dtype=torch.float16)
|
308 |
+
clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
|
309 |
+
image_prompt_embeds = self.image_proj_model(clip_image_embeds)
|
310 |
+
uncond_clip_image_embeds = self.image_encoder(
|
311 |
+
torch.zeros_like(clip_image), output_hidden_states=True
|
312 |
+
).hidden_states[-2]
|
313 |
+
uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds)
|
314 |
+
return image_prompt_embeds, uncond_image_prompt_embeds
|
315 |
+
|
316 |
+
|
317 |
+
class IPAdapterFull(IPAdapterPlus):
|
318 |
+
"""IP-Adapter with full features"""
|
319 |
+
|
320 |
+
def init_proj(self):
|
321 |
+
image_proj_model = MLPProjModel(
|
322 |
+
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
323 |
+
clip_embeddings_dim=self.image_encoder.config.hidden_size,
|
324 |
+
).to(self.device, dtype=torch.float16)
|
325 |
+
return image_proj_model
|
326 |
+
|
327 |
+
|
328 |
+
class IPAdapterPlusXL(IPAdapter):
|
329 |
+
"""SDXL"""
|
330 |
+
|
331 |
+
def init_proj(self):
|
332 |
+
image_proj_model = Resampler(
|
333 |
+
dim=1280,
|
334 |
+
depth=4,
|
335 |
+
dim_head=64,
|
336 |
+
heads=20,
|
337 |
+
num_queries=self.num_tokens,
|
338 |
+
embedding_dim=self.image_encoder.config.hidden_size,
|
339 |
+
output_dim=self.pipe.unet.config.cross_attention_dim,
|
340 |
+
ff_mult=4,
|
341 |
+
).to(self.device, dtype=torch.float16)
|
342 |
+
return image_proj_model
|
343 |
+
|
344 |
+
@torch.inference_mode()
|
345 |
+
def get_image_embeds(self, pil_image):
|
346 |
+
if isinstance(pil_image, Image.Image):
|
347 |
+
pil_image = [pil_image]
|
348 |
+
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
|
349 |
+
clip_image = clip_image.to(self.device, dtype=torch.float16)
|
350 |
+
clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
|
351 |
+
image_prompt_embeds = self.image_proj_model(clip_image_embeds)
|
352 |
+
uncond_clip_image_embeds = self.image_encoder(
|
353 |
+
torch.zeros_like(clip_image), output_hidden_states=True
|
354 |
+
).hidden_states[-2]
|
355 |
+
uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds)
|
356 |
+
return image_prompt_embeds, uncond_image_prompt_embeds
|
357 |
+
|
358 |
+
def generate(
|
359 |
+
self,
|
360 |
+
pil_image,
|
361 |
+
prompt=None,
|
362 |
+
negative_prompt=None,
|
363 |
+
scale=1.0,
|
364 |
+
num_samples=4,
|
365 |
+
seed=None,
|
366 |
+
num_inference_steps=30,
|
367 |
+
**kwargs,
|
368 |
+
):
|
369 |
+
self.set_scale(scale)
|
370 |
+
|
371 |
+
num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
|
372 |
+
|
373 |
+
if prompt is None:
|
374 |
+
prompt = "best quality, high quality"
|
375 |
+
if negative_prompt is None:
|
376 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
377 |
+
|
378 |
+
if not isinstance(prompt, List):
|
379 |
+
prompt = [prompt] * num_prompts
|
380 |
+
if not isinstance(negative_prompt, List):
|
381 |
+
negative_prompt = [negative_prompt] * num_prompts
|
382 |
+
|
383 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image)
|
384 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
385 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
386 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
387 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
388 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
389 |
+
|
390 |
+
with torch.inference_mode():
|
391 |
+
(
|
392 |
+
prompt_embeds,
|
393 |
+
negative_prompt_embeds,
|
394 |
+
pooled_prompt_embeds,
|
395 |
+
negative_pooled_prompt_embeds,
|
396 |
+
) = self.pipe.encode_prompt(
|
397 |
+
prompt,
|
398 |
+
num_images_per_prompt=num_samples,
|
399 |
+
do_classifier_free_guidance=True,
|
400 |
+
negative_prompt=negative_prompt,
|
401 |
+
)
|
402 |
+
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
403 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
404 |
+
|
405 |
+
generator = get_generator(seed, self.device)
|
406 |
+
|
407 |
+
images = self.pipe(
|
408 |
+
prompt_embeds=prompt_embeds,
|
409 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
410 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
411 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
412 |
+
num_inference_steps=num_inference_steps,
|
413 |
+
generator=generator,
|
414 |
+
**kwargs,
|
415 |
+
).images
|
416 |
+
|
417 |
+
return images
|
ip_adapter/ip_adapter_faceid.py
ADDED
@@ -0,0 +1,542 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from diffusers import StableDiffusionPipeline
|
6 |
+
from diffusers.pipelines.controlnet import MultiControlNetModel
|
7 |
+
from PIL import Image
|
8 |
+
from safetensors import safe_open
|
9 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
10 |
+
|
11 |
+
from .attention_processor_faceid import LoRAAttnProcessor, LoRAIPAttnProcessor
|
12 |
+
from .utils import is_torch2_available, get_generator
|
13 |
+
|
14 |
+
USE_DAFAULT_ATTN = False # should be True for visualization_attnmap
|
15 |
+
if is_torch2_available() and (not USE_DAFAULT_ATTN):
|
16 |
+
from .attention_processor_faceid import (
|
17 |
+
LoRAAttnProcessor2_0 as LoRAAttnProcessor,
|
18 |
+
)
|
19 |
+
from .attention_processor_faceid import (
|
20 |
+
LoRAIPAttnProcessor2_0 as LoRAIPAttnProcessor,
|
21 |
+
)
|
22 |
+
else:
|
23 |
+
from .attention_processor_faceid import LoRAAttnProcessor, LoRAIPAttnProcessor
|
24 |
+
from .resampler import PerceiverAttention, FeedForward
|
25 |
+
|
26 |
+
|
27 |
+
class FacePerceiverResampler(torch.nn.Module):
|
28 |
+
def __init__(
|
29 |
+
self,
|
30 |
+
*,
|
31 |
+
dim=768,
|
32 |
+
depth=4,
|
33 |
+
dim_head=64,
|
34 |
+
heads=16,
|
35 |
+
embedding_dim=1280,
|
36 |
+
output_dim=768,
|
37 |
+
ff_mult=4,
|
38 |
+
):
|
39 |
+
super().__init__()
|
40 |
+
|
41 |
+
self.proj_in = torch.nn.Linear(embedding_dim, dim)
|
42 |
+
self.proj_out = torch.nn.Linear(dim, output_dim)
|
43 |
+
self.norm_out = torch.nn.LayerNorm(output_dim)
|
44 |
+
self.layers = torch.nn.ModuleList([])
|
45 |
+
for _ in range(depth):
|
46 |
+
self.layers.append(
|
47 |
+
torch.nn.ModuleList(
|
48 |
+
[
|
49 |
+
PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
|
50 |
+
FeedForward(dim=dim, mult=ff_mult),
|
51 |
+
]
|
52 |
+
)
|
53 |
+
)
|
54 |
+
|
55 |
+
def forward(self, latents, x):
|
56 |
+
x = self.proj_in(x)
|
57 |
+
for attn, ff in self.layers:
|
58 |
+
latents = attn(x, latents) + latents
|
59 |
+
latents = ff(latents) + latents
|
60 |
+
latents = self.proj_out(latents)
|
61 |
+
return self.norm_out(latents)
|
62 |
+
|
63 |
+
|
64 |
+
class MLPProjModel(torch.nn.Module):
|
65 |
+
def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, num_tokens=4):
|
66 |
+
super().__init__()
|
67 |
+
|
68 |
+
self.cross_attention_dim = cross_attention_dim
|
69 |
+
self.num_tokens = num_tokens
|
70 |
+
|
71 |
+
self.proj = torch.nn.Sequential(
|
72 |
+
torch.nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
|
73 |
+
torch.nn.GELU(),
|
74 |
+
torch.nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
|
75 |
+
)
|
76 |
+
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
77 |
+
|
78 |
+
def forward(self, id_embeds):
|
79 |
+
x = self.proj(id_embeds)
|
80 |
+
x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
|
81 |
+
x = self.norm(x)
|
82 |
+
return x
|
83 |
+
|
84 |
+
|
85 |
+
class ProjPlusModel(torch.nn.Module):
|
86 |
+
def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, clip_embeddings_dim=1280, num_tokens=4):
|
87 |
+
super().__init__()
|
88 |
+
|
89 |
+
self.cross_attention_dim = cross_attention_dim
|
90 |
+
self.num_tokens = num_tokens
|
91 |
+
|
92 |
+
self.proj = torch.nn.Sequential(
|
93 |
+
torch.nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
|
94 |
+
torch.nn.GELU(),
|
95 |
+
torch.nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
|
96 |
+
)
|
97 |
+
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
98 |
+
|
99 |
+
self.perceiver_resampler = FacePerceiverResampler(
|
100 |
+
dim=cross_attention_dim,
|
101 |
+
depth=4,
|
102 |
+
dim_head=64,
|
103 |
+
heads=cross_attention_dim // 64,
|
104 |
+
embedding_dim=clip_embeddings_dim,
|
105 |
+
output_dim=cross_attention_dim,
|
106 |
+
ff_mult=4,
|
107 |
+
)
|
108 |
+
|
109 |
+
def forward(self, id_embeds, clip_embeds, shortcut=False, scale=1.0):
|
110 |
+
|
111 |
+
x = self.proj(id_embeds)
|
112 |
+
x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
|
113 |
+
x = self.norm(x)
|
114 |
+
out = self.perceiver_resampler(x, clip_embeds)
|
115 |
+
if shortcut:
|
116 |
+
out = x + scale * out
|
117 |
+
return out
|
118 |
+
|
119 |
+
|
120 |
+
class IPAdapterFaceID:
|
121 |
+
def __init__(self, sd_pipe, ip_ckpt, device, lora_rank=128, num_tokens=4, torch_dtype=torch.float16):
|
122 |
+
self.device = device
|
123 |
+
self.ip_ckpt = ip_ckpt
|
124 |
+
self.lora_rank = lora_rank
|
125 |
+
self.num_tokens = num_tokens
|
126 |
+
self.torch_dtype = torch_dtype
|
127 |
+
|
128 |
+
self.pipe = sd_pipe.to(self.device)
|
129 |
+
self.set_ip_adapter()
|
130 |
+
|
131 |
+
# image proj model
|
132 |
+
self.image_proj_model = self.init_proj()
|
133 |
+
|
134 |
+
self.load_ip_adapter()
|
135 |
+
|
136 |
+
def init_proj(self):
|
137 |
+
image_proj_model = MLPProjModel(
|
138 |
+
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
139 |
+
id_embeddings_dim=512,
|
140 |
+
num_tokens=self.num_tokens,
|
141 |
+
).to(self.device, dtype=self.torch_dtype)
|
142 |
+
return image_proj_model
|
143 |
+
|
144 |
+
def set_ip_adapter(self):
|
145 |
+
unet = self.pipe.unet
|
146 |
+
attn_procs = {}
|
147 |
+
for name in unet.attn_processors.keys():
|
148 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
149 |
+
if name.startswith("mid_block"):
|
150 |
+
hidden_size = unet.config.block_out_channels[-1]
|
151 |
+
elif name.startswith("up_blocks"):
|
152 |
+
block_id = int(name[len("up_blocks.")])
|
153 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
154 |
+
elif name.startswith("down_blocks"):
|
155 |
+
block_id = int(name[len("down_blocks.")])
|
156 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
157 |
+
if cross_attention_dim is None:
|
158 |
+
attn_procs[name] = LoRAAttnProcessor(
|
159 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=self.lora_rank,
|
160 |
+
).to(self.device, dtype=self.torch_dtype)
|
161 |
+
else:
|
162 |
+
attn_procs[name] = LoRAIPAttnProcessor(
|
163 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, rank=self.lora_rank, num_tokens=self.num_tokens,
|
164 |
+
).to(self.device, dtype=self.torch_dtype)
|
165 |
+
unet.set_attn_processor(attn_procs)
|
166 |
+
|
167 |
+
def load_ip_adapter(self):
|
168 |
+
if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors":
|
169 |
+
state_dict = {"image_proj": {}, "ip_adapter": {}}
|
170 |
+
with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f:
|
171 |
+
for key in f.keys():
|
172 |
+
if key.startswith("image_proj."):
|
173 |
+
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
|
174 |
+
elif key.startswith("ip_adapter."):
|
175 |
+
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
|
176 |
+
else:
|
177 |
+
state_dict = torch.load(self.ip_ckpt, map_location="cpu")
|
178 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"])
|
179 |
+
ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
|
180 |
+
ip_layers.load_state_dict(state_dict["ip_adapter"])
|
181 |
+
|
182 |
+
@torch.inference_mode()
|
183 |
+
def get_image_embeds(self, faceid_embeds):
|
184 |
+
|
185 |
+
faceid_embeds = faceid_embeds.to(self.device, dtype=self.torch_dtype)
|
186 |
+
image_prompt_embeds = self.image_proj_model(faceid_embeds)
|
187 |
+
uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(faceid_embeds))
|
188 |
+
return image_prompt_embeds, uncond_image_prompt_embeds
|
189 |
+
|
190 |
+
def set_scale(self, scale):
|
191 |
+
for attn_processor in self.pipe.unet.attn_processors.values():
|
192 |
+
if isinstance(attn_processor, LoRAIPAttnProcessor):
|
193 |
+
attn_processor.scale = scale
|
194 |
+
|
195 |
+
def generate(
|
196 |
+
self,
|
197 |
+
faceid_embeds=None,
|
198 |
+
prompt=None,
|
199 |
+
negative_prompt=None,
|
200 |
+
scale=1.0,
|
201 |
+
num_samples=4,
|
202 |
+
seed=None,
|
203 |
+
guidance_scale=7.5,
|
204 |
+
num_inference_steps=30,
|
205 |
+
**kwargs,
|
206 |
+
):
|
207 |
+
self.set_scale(scale)
|
208 |
+
|
209 |
+
|
210 |
+
num_prompts = faceid_embeds.size(0)
|
211 |
+
|
212 |
+
if prompt is None:
|
213 |
+
prompt = "best quality, high quality"
|
214 |
+
if negative_prompt is None:
|
215 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
216 |
+
|
217 |
+
if not isinstance(prompt, List):
|
218 |
+
prompt = [prompt] * num_prompts
|
219 |
+
if not isinstance(negative_prompt, List):
|
220 |
+
negative_prompt = [negative_prompt] * num_prompts
|
221 |
+
|
222 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds)
|
223 |
+
|
224 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
225 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
226 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
227 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
228 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
229 |
+
|
230 |
+
with torch.inference_mode():
|
231 |
+
prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt(
|
232 |
+
prompt,
|
233 |
+
device=self.device,
|
234 |
+
num_images_per_prompt=num_samples,
|
235 |
+
do_classifier_free_guidance=True,
|
236 |
+
negative_prompt=negative_prompt,
|
237 |
+
)
|
238 |
+
prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
|
239 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
|
240 |
+
|
241 |
+
generator = get_generator(seed, self.device)
|
242 |
+
|
243 |
+
images = self.pipe(
|
244 |
+
prompt_embeds=prompt_embeds,
|
245 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
246 |
+
guidance_scale=guidance_scale,
|
247 |
+
num_inference_steps=num_inference_steps,
|
248 |
+
generator=generator,
|
249 |
+
**kwargs,
|
250 |
+
).images
|
251 |
+
|
252 |
+
return images
|
253 |
+
|
254 |
+
|
255 |
+
class IPAdapterFaceIDPlus:
|
256 |
+
def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, lora_rank=128, num_tokens=4, torch_dtype=torch.float16):
|
257 |
+
self.device = device
|
258 |
+
self.image_encoder_path = image_encoder_path
|
259 |
+
self.ip_ckpt = ip_ckpt
|
260 |
+
self.lora_rank = lora_rank
|
261 |
+
self.num_tokens = num_tokens
|
262 |
+
self.torch_dtype = torch_dtype
|
263 |
+
|
264 |
+
self.pipe = sd_pipe.to(self.device)
|
265 |
+
self.set_ip_adapter()
|
266 |
+
|
267 |
+
# load image encoder
|
268 |
+
self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to(
|
269 |
+
self.device, dtype=self.torch_dtype
|
270 |
+
)
|
271 |
+
self.clip_image_processor = CLIPImageProcessor()
|
272 |
+
# image proj model
|
273 |
+
self.image_proj_model = self.init_proj()
|
274 |
+
|
275 |
+
self.load_ip_adapter()
|
276 |
+
|
277 |
+
def init_proj(self):
|
278 |
+
image_proj_model = ProjPlusModel(
|
279 |
+
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
280 |
+
id_embeddings_dim=512,
|
281 |
+
clip_embeddings_dim=self.image_encoder.config.hidden_size,
|
282 |
+
num_tokens=self.num_tokens,
|
283 |
+
).to(self.device, dtype=self.torch_dtype)
|
284 |
+
return image_proj_model
|
285 |
+
|
286 |
+
def set_ip_adapter(self):
|
287 |
+
unet = self.pipe.unet
|
288 |
+
attn_procs = {}
|
289 |
+
for name in unet.attn_processors.keys():
|
290 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
291 |
+
if name.startswith("mid_block"):
|
292 |
+
hidden_size = unet.config.block_out_channels[-1]
|
293 |
+
elif name.startswith("up_blocks"):
|
294 |
+
block_id = int(name[len("up_blocks.")])
|
295 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
296 |
+
elif name.startswith("down_blocks"):
|
297 |
+
block_id = int(name[len("down_blocks.")])
|
298 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
299 |
+
if cross_attention_dim is None:
|
300 |
+
attn_procs[name] = LoRAAttnProcessor(
|
301 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, rank=self.lora_rank,
|
302 |
+
).to(self.device, dtype=self.torch_dtype)
|
303 |
+
else:
|
304 |
+
attn_procs[name] = LoRAIPAttnProcessor(
|
305 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, rank=self.lora_rank, num_tokens=self.num_tokens,
|
306 |
+
).to(self.device, dtype=self.torch_dtype)
|
307 |
+
unet.set_attn_processor(attn_procs)
|
308 |
+
|
309 |
+
def load_ip_adapter(self):
|
310 |
+
if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors":
|
311 |
+
state_dict = {"image_proj": {}, "ip_adapter": {}}
|
312 |
+
with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f:
|
313 |
+
for key in f.keys():
|
314 |
+
if key.startswith("image_proj."):
|
315 |
+
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
|
316 |
+
elif key.startswith("ip_adapter."):
|
317 |
+
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
|
318 |
+
else:
|
319 |
+
state_dict = torch.load(self.ip_ckpt, map_location="cpu")
|
320 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"])
|
321 |
+
ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
|
322 |
+
ip_layers.load_state_dict(state_dict["ip_adapter"])
|
323 |
+
|
324 |
+
@torch.inference_mode()
|
325 |
+
def get_image_embeds(self, faceid_embeds, face_image, s_scale, shortcut):
|
326 |
+
if isinstance(face_image, Image.Image):
|
327 |
+
pil_image = [face_image]
|
328 |
+
clip_image = self.clip_image_processor(images=face_image, return_tensors="pt").pixel_values
|
329 |
+
clip_image = clip_image.to(self.device, dtype=self.torch_dtype)
|
330 |
+
clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
|
331 |
+
uncond_clip_image_embeds = self.image_encoder(
|
332 |
+
torch.zeros_like(clip_image), output_hidden_states=True
|
333 |
+
).hidden_states[-2]
|
334 |
+
|
335 |
+
faceid_embeds = faceid_embeds.to(self.device, dtype=self.torch_dtype)
|
336 |
+
image_prompt_embeds = self.image_proj_model(faceid_embeds, clip_image_embeds, shortcut=shortcut, scale=s_scale)
|
337 |
+
uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(faceid_embeds), uncond_clip_image_embeds, shortcut=shortcut, scale=s_scale)
|
338 |
+
return image_prompt_embeds, uncond_image_prompt_embeds
|
339 |
+
|
340 |
+
def set_scale(self, scale):
|
341 |
+
for attn_processor in self.pipe.unet.attn_processors.values():
|
342 |
+
if isinstance(attn_processor, LoRAIPAttnProcessor):
|
343 |
+
attn_processor.scale = scale
|
344 |
+
|
345 |
+
def generate(
|
346 |
+
self,
|
347 |
+
face_image=None,
|
348 |
+
faceid_embeds=None,
|
349 |
+
prompt=None,
|
350 |
+
negative_prompt=None,
|
351 |
+
scale=1.0,
|
352 |
+
num_samples=4,
|
353 |
+
seed=None,
|
354 |
+
guidance_scale=7.5,
|
355 |
+
num_inference_steps=30,
|
356 |
+
s_scale=1.0,
|
357 |
+
shortcut=False,
|
358 |
+
**kwargs,
|
359 |
+
):
|
360 |
+
self.set_scale(scale)
|
361 |
+
|
362 |
+
|
363 |
+
num_prompts = faceid_embeds.size(0)
|
364 |
+
|
365 |
+
if prompt is None:
|
366 |
+
prompt = "best quality, high quality"
|
367 |
+
if negative_prompt is None:
|
368 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
369 |
+
|
370 |
+
if not isinstance(prompt, List):
|
371 |
+
prompt = [prompt] * num_prompts
|
372 |
+
if not isinstance(negative_prompt, List):
|
373 |
+
negative_prompt = [negative_prompt] * num_prompts
|
374 |
+
|
375 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds, face_image, s_scale, shortcut)
|
376 |
+
|
377 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
378 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
379 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
380 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
381 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
382 |
+
|
383 |
+
with torch.inference_mode():
|
384 |
+
prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt(
|
385 |
+
prompt,
|
386 |
+
device=self.device,
|
387 |
+
num_images_per_prompt=num_samples,
|
388 |
+
do_classifier_free_guidance=True,
|
389 |
+
negative_prompt=negative_prompt,
|
390 |
+
)
|
391 |
+
prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
|
392 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
|
393 |
+
|
394 |
+
generator = get_generator(seed, self.device)
|
395 |
+
|
396 |
+
images = self.pipe(
|
397 |
+
prompt_embeds=prompt_embeds,
|
398 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
399 |
+
guidance_scale=guidance_scale,
|
400 |
+
num_inference_steps=num_inference_steps,
|
401 |
+
generator=generator,
|
402 |
+
**kwargs,
|
403 |
+
).images
|
404 |
+
|
405 |
+
return images
|
406 |
+
|
407 |
+
|
408 |
+
class IPAdapterFaceIDXL(IPAdapterFaceID):
|
409 |
+
"""SDXL"""
|
410 |
+
|
411 |
+
def generate(
|
412 |
+
self,
|
413 |
+
faceid_embeds=None,
|
414 |
+
prompt=None,
|
415 |
+
negative_prompt=None,
|
416 |
+
scale=1.0,
|
417 |
+
num_samples=4,
|
418 |
+
seed=None,
|
419 |
+
num_inference_steps=30,
|
420 |
+
**kwargs,
|
421 |
+
):
|
422 |
+
self.set_scale(scale)
|
423 |
+
|
424 |
+
num_prompts = faceid_embeds.size(0)
|
425 |
+
|
426 |
+
if prompt is None:
|
427 |
+
prompt = "best quality, high quality"
|
428 |
+
if negative_prompt is None:
|
429 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
430 |
+
|
431 |
+
if not isinstance(prompt, List):
|
432 |
+
prompt = [prompt] * num_prompts
|
433 |
+
if not isinstance(negative_prompt, List):
|
434 |
+
negative_prompt = [negative_prompt] * num_prompts
|
435 |
+
|
436 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds)
|
437 |
+
|
438 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
439 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
440 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
441 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
442 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
443 |
+
|
444 |
+
with torch.inference_mode():
|
445 |
+
(
|
446 |
+
prompt_embeds,
|
447 |
+
negative_prompt_embeds,
|
448 |
+
pooled_prompt_embeds,
|
449 |
+
negative_pooled_prompt_embeds,
|
450 |
+
) = self.pipe.encode_prompt(
|
451 |
+
prompt,
|
452 |
+
num_images_per_prompt=num_samples,
|
453 |
+
do_classifier_free_guidance=True,
|
454 |
+
negative_prompt=negative_prompt,
|
455 |
+
)
|
456 |
+
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
457 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
458 |
+
|
459 |
+
generator = get_generator(seed, self.device)
|
460 |
+
|
461 |
+
images = self.pipe(
|
462 |
+
prompt_embeds=prompt_embeds,
|
463 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
464 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
465 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
466 |
+
num_inference_steps=num_inference_steps,
|
467 |
+
generator=generator,
|
468 |
+
**kwargs,
|
469 |
+
).images
|
470 |
+
|
471 |
+
return images
|
472 |
+
|
473 |
+
|
474 |
+
class IPAdapterFaceIDPlusXL(IPAdapterFaceIDPlus):
|
475 |
+
"""SDXL"""
|
476 |
+
|
477 |
+
def generate(
|
478 |
+
self,
|
479 |
+
face_image=None,
|
480 |
+
faceid_embeds=None,
|
481 |
+
prompt=None,
|
482 |
+
negative_prompt=None,
|
483 |
+
scale=1.0,
|
484 |
+
num_samples=4,
|
485 |
+
seed=None,
|
486 |
+
guidance_scale=7.5,
|
487 |
+
num_inference_steps=30,
|
488 |
+
s_scale=1.0,
|
489 |
+
shortcut=True,
|
490 |
+
**kwargs,
|
491 |
+
):
|
492 |
+
self.set_scale(scale)
|
493 |
+
|
494 |
+
num_prompts = faceid_embeds.size(0)
|
495 |
+
|
496 |
+
if prompt is None:
|
497 |
+
prompt = "best quality, high quality"
|
498 |
+
if negative_prompt is None:
|
499 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
500 |
+
|
501 |
+
if not isinstance(prompt, List):
|
502 |
+
prompt = [prompt] * num_prompts
|
503 |
+
if not isinstance(negative_prompt, List):
|
504 |
+
negative_prompt = [negative_prompt] * num_prompts
|
505 |
+
|
506 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds, face_image, s_scale, shortcut)
|
507 |
+
|
508 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
509 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
510 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
511 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
512 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
513 |
+
|
514 |
+
with torch.inference_mode():
|
515 |
+
(
|
516 |
+
prompt_embeds,
|
517 |
+
negative_prompt_embeds,
|
518 |
+
pooled_prompt_embeds,
|
519 |
+
negative_pooled_prompt_embeds,
|
520 |
+
) = self.pipe.encode_prompt(
|
521 |
+
prompt,
|
522 |
+
num_images_per_prompt=num_samples,
|
523 |
+
do_classifier_free_guidance=True,
|
524 |
+
negative_prompt=negative_prompt,
|
525 |
+
)
|
526 |
+
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
527 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
528 |
+
|
529 |
+
generator = get_generator(seed, self.device)
|
530 |
+
|
531 |
+
images = self.pipe(
|
532 |
+
prompt_embeds=prompt_embeds,
|
533 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
534 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
535 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
536 |
+
num_inference_steps=num_inference_steps,
|
537 |
+
generator=generator,
|
538 |
+
guidance_scale=guidance_scale,
|
539 |
+
**kwargs,
|
540 |
+
).images
|
541 |
+
|
542 |
+
return images
|
ip_adapter/ip_adapter_faceid_separate.py
ADDED
@@ -0,0 +1,547 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
from typing import List
|
3 |
+
|
4 |
+
import torch
|
5 |
+
from diffusers import StableDiffusionPipeline
|
6 |
+
from diffusers.pipelines.controlnet import MultiControlNetModel
|
7 |
+
from PIL import Image
|
8 |
+
from safetensors import safe_open
|
9 |
+
from transformers import CLIPImageProcessor, CLIPVisionModelWithProjection
|
10 |
+
|
11 |
+
from .utils import is_torch2_available, get_generator
|
12 |
+
|
13 |
+
USE_DAFAULT_ATTN = False # should be True for visualization_attnmap
|
14 |
+
if is_torch2_available() and (not USE_DAFAULT_ATTN):
|
15 |
+
from .attention_processor import (
|
16 |
+
AttnProcessor2_0 as AttnProcessor,
|
17 |
+
)
|
18 |
+
from .attention_processor import (
|
19 |
+
IPAttnProcessor2_0 as IPAttnProcessor,
|
20 |
+
)
|
21 |
+
else:
|
22 |
+
from .attention_processor import AttnProcessor, IPAttnProcessor
|
23 |
+
from .resampler import PerceiverAttention, FeedForward
|
24 |
+
|
25 |
+
|
26 |
+
class FacePerceiverResampler(torch.nn.Module):
|
27 |
+
def __init__(
|
28 |
+
self,
|
29 |
+
*,
|
30 |
+
dim=768,
|
31 |
+
depth=4,
|
32 |
+
dim_head=64,
|
33 |
+
heads=16,
|
34 |
+
embedding_dim=1280,
|
35 |
+
output_dim=768,
|
36 |
+
ff_mult=4,
|
37 |
+
):
|
38 |
+
super().__init__()
|
39 |
+
|
40 |
+
self.proj_in = torch.nn.Linear(embedding_dim, dim)
|
41 |
+
self.proj_out = torch.nn.Linear(dim, output_dim)
|
42 |
+
self.norm_out = torch.nn.LayerNorm(output_dim)
|
43 |
+
self.layers = torch.nn.ModuleList([])
|
44 |
+
for _ in range(depth):
|
45 |
+
self.layers.append(
|
46 |
+
torch.nn.ModuleList(
|
47 |
+
[
|
48 |
+
PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
|
49 |
+
FeedForward(dim=dim, mult=ff_mult),
|
50 |
+
]
|
51 |
+
)
|
52 |
+
)
|
53 |
+
|
54 |
+
def forward(self, latents, x):
|
55 |
+
x = self.proj_in(x)
|
56 |
+
for attn, ff in self.layers:
|
57 |
+
latents = attn(x, latents) + latents
|
58 |
+
latents = ff(latents) + latents
|
59 |
+
latents = self.proj_out(latents)
|
60 |
+
return self.norm_out(latents)
|
61 |
+
|
62 |
+
|
63 |
+
class MLPProjModel(torch.nn.Module):
|
64 |
+
def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, num_tokens=4):
|
65 |
+
super().__init__()
|
66 |
+
|
67 |
+
self.cross_attention_dim = cross_attention_dim
|
68 |
+
self.num_tokens = num_tokens
|
69 |
+
|
70 |
+
self.proj = torch.nn.Sequential(
|
71 |
+
torch.nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
|
72 |
+
torch.nn.GELU(),
|
73 |
+
torch.nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
|
74 |
+
)
|
75 |
+
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
76 |
+
|
77 |
+
def forward(self, id_embeds):
|
78 |
+
x = self.proj(id_embeds)
|
79 |
+
x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
|
80 |
+
x = self.norm(x)
|
81 |
+
return x
|
82 |
+
|
83 |
+
|
84 |
+
class ProjPlusModel(torch.nn.Module):
|
85 |
+
def __init__(self, cross_attention_dim=768, id_embeddings_dim=512, clip_embeddings_dim=1280, num_tokens=4):
|
86 |
+
super().__init__()
|
87 |
+
|
88 |
+
self.cross_attention_dim = cross_attention_dim
|
89 |
+
self.num_tokens = num_tokens
|
90 |
+
|
91 |
+
self.proj = torch.nn.Sequential(
|
92 |
+
torch.nn.Linear(id_embeddings_dim, id_embeddings_dim*2),
|
93 |
+
torch.nn.GELU(),
|
94 |
+
torch.nn.Linear(id_embeddings_dim*2, cross_attention_dim*num_tokens),
|
95 |
+
)
|
96 |
+
self.norm = torch.nn.LayerNorm(cross_attention_dim)
|
97 |
+
|
98 |
+
self.perceiver_resampler = FacePerceiverResampler(
|
99 |
+
dim=cross_attention_dim,
|
100 |
+
depth=4,
|
101 |
+
dim_head=64,
|
102 |
+
heads=cross_attention_dim // 64,
|
103 |
+
embedding_dim=clip_embeddings_dim,
|
104 |
+
output_dim=cross_attention_dim,
|
105 |
+
ff_mult=4,
|
106 |
+
)
|
107 |
+
|
108 |
+
def forward(self, id_embeds, clip_embeds, shortcut=False, scale=1.0):
|
109 |
+
|
110 |
+
x = self.proj(id_embeds)
|
111 |
+
x = x.reshape(-1, self.num_tokens, self.cross_attention_dim)
|
112 |
+
x = self.norm(x)
|
113 |
+
out = self.perceiver_resampler(x, clip_embeds)
|
114 |
+
if shortcut:
|
115 |
+
out = x + scale * out
|
116 |
+
return out
|
117 |
+
|
118 |
+
|
119 |
+
class IPAdapterFaceID:
|
120 |
+
def __init__(self, sd_pipe, ip_ckpt, device, num_tokens=4, n_cond=1, torch_dtype=torch.float16):
|
121 |
+
self.device = device
|
122 |
+
self.ip_ckpt = ip_ckpt
|
123 |
+
self.num_tokens = num_tokens
|
124 |
+
self.n_cond = n_cond
|
125 |
+
self.torch_dtype = torch_dtype
|
126 |
+
|
127 |
+
self.pipe = sd_pipe.to(self.device)
|
128 |
+
self.set_ip_adapter()
|
129 |
+
|
130 |
+
# image proj model
|
131 |
+
self.image_proj_model = self.init_proj()
|
132 |
+
|
133 |
+
self.load_ip_adapter()
|
134 |
+
|
135 |
+
def init_proj(self):
|
136 |
+
image_proj_model = MLPProjModel(
|
137 |
+
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
138 |
+
id_embeddings_dim=512,
|
139 |
+
num_tokens=self.num_tokens,
|
140 |
+
).to(self.device, dtype=self.torch_dtype)
|
141 |
+
return image_proj_model
|
142 |
+
|
143 |
+
def set_ip_adapter(self):
|
144 |
+
unet = self.pipe.unet
|
145 |
+
attn_procs = {}
|
146 |
+
for name in unet.attn_processors.keys():
|
147 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
148 |
+
if name.startswith("mid_block"):
|
149 |
+
hidden_size = unet.config.block_out_channels[-1]
|
150 |
+
elif name.startswith("up_blocks"):
|
151 |
+
block_id = int(name[len("up_blocks.")])
|
152 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
153 |
+
elif name.startswith("down_blocks"):
|
154 |
+
block_id = int(name[len("down_blocks.")])
|
155 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
156 |
+
if cross_attention_dim is None:
|
157 |
+
attn_procs[name] = AttnProcessor()
|
158 |
+
else:
|
159 |
+
attn_procs[name] = IPAttnProcessor(
|
160 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, num_tokens=self.num_tokens*self.n_cond,
|
161 |
+
).to(self.device, dtype=self.torch_dtype)
|
162 |
+
unet.set_attn_processor(attn_procs)
|
163 |
+
|
164 |
+
def load_ip_adapter(self):
|
165 |
+
if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors":
|
166 |
+
state_dict = {"image_proj": {}, "ip_adapter": {}}
|
167 |
+
with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f:
|
168 |
+
for key in f.keys():
|
169 |
+
if key.startswith("image_proj."):
|
170 |
+
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
|
171 |
+
elif key.startswith("ip_adapter."):
|
172 |
+
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
|
173 |
+
else:
|
174 |
+
state_dict = torch.load(self.ip_ckpt, map_location="cpu")
|
175 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"])
|
176 |
+
ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
|
177 |
+
ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False)
|
178 |
+
|
179 |
+
@torch.inference_mode()
|
180 |
+
def get_image_embeds(self, faceid_embeds):
|
181 |
+
|
182 |
+
multi_face = False
|
183 |
+
if faceid_embeds.dim() == 3:
|
184 |
+
multi_face = True
|
185 |
+
b, n, c = faceid_embeds.shape
|
186 |
+
faceid_embeds = faceid_embeds.reshape(b*n, c)
|
187 |
+
|
188 |
+
faceid_embeds = faceid_embeds.to(self.device, dtype=self.torch_dtype)
|
189 |
+
image_prompt_embeds = self.image_proj_model(faceid_embeds)
|
190 |
+
uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(faceid_embeds))
|
191 |
+
if multi_face:
|
192 |
+
c = image_prompt_embeds.size(-1)
|
193 |
+
image_prompt_embeds = image_prompt_embeds.reshape(b, -1, c)
|
194 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.reshape(b, -1, c)
|
195 |
+
|
196 |
+
return image_prompt_embeds, uncond_image_prompt_embeds
|
197 |
+
|
198 |
+
def set_scale(self, scale):
|
199 |
+
for attn_processor in self.pipe.unet.attn_processors.values():
|
200 |
+
if isinstance(attn_processor, IPAttnProcessor):
|
201 |
+
attn_processor.scale = scale
|
202 |
+
|
203 |
+
def generate(
|
204 |
+
self,
|
205 |
+
faceid_embeds=None,
|
206 |
+
prompt=None,
|
207 |
+
negative_prompt=None,
|
208 |
+
scale=1.0,
|
209 |
+
num_samples=4,
|
210 |
+
seed=None,
|
211 |
+
guidance_scale=7.5,
|
212 |
+
num_inference_steps=30,
|
213 |
+
**kwargs,
|
214 |
+
):
|
215 |
+
self.set_scale(scale)
|
216 |
+
|
217 |
+
|
218 |
+
num_prompts = faceid_embeds.size(0)
|
219 |
+
|
220 |
+
if prompt is None:
|
221 |
+
prompt = "best quality, high quality"
|
222 |
+
if negative_prompt is None:
|
223 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
224 |
+
|
225 |
+
if not isinstance(prompt, List):
|
226 |
+
prompt = [prompt] * num_prompts
|
227 |
+
if not isinstance(negative_prompt, List):
|
228 |
+
negative_prompt = [negative_prompt] * num_prompts
|
229 |
+
|
230 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds)
|
231 |
+
|
232 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
233 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
234 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
235 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
236 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
237 |
+
|
238 |
+
with torch.inference_mode():
|
239 |
+
prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt(
|
240 |
+
prompt,
|
241 |
+
device=self.device,
|
242 |
+
num_images_per_prompt=num_samples,
|
243 |
+
do_classifier_free_guidance=True,
|
244 |
+
negative_prompt=negative_prompt,
|
245 |
+
)
|
246 |
+
prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
|
247 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
|
248 |
+
|
249 |
+
generator = get_generator(seed, self.device)
|
250 |
+
|
251 |
+
images = self.pipe(
|
252 |
+
prompt_embeds=prompt_embeds,
|
253 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
254 |
+
guidance_scale=guidance_scale,
|
255 |
+
num_inference_steps=num_inference_steps,
|
256 |
+
generator=generator,
|
257 |
+
**kwargs,
|
258 |
+
).images
|
259 |
+
|
260 |
+
return images
|
261 |
+
|
262 |
+
|
263 |
+
class IPAdapterFaceIDPlus:
|
264 |
+
def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_tokens=4, torch_dtype=torch.float16):
|
265 |
+
self.device = device
|
266 |
+
self.image_encoder_path = image_encoder_path
|
267 |
+
self.ip_ckpt = ip_ckpt
|
268 |
+
self.num_tokens = num_tokens
|
269 |
+
self.torch_dtype = torch_dtype
|
270 |
+
|
271 |
+
self.pipe = sd_pipe.to(self.device)
|
272 |
+
self.set_ip_adapter()
|
273 |
+
|
274 |
+
# load image encoder
|
275 |
+
self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to(
|
276 |
+
self.device, dtype=self.torch_dtype
|
277 |
+
)
|
278 |
+
self.clip_image_processor = CLIPImageProcessor()
|
279 |
+
# image proj model
|
280 |
+
self.image_proj_model = self.init_proj()
|
281 |
+
|
282 |
+
self.load_ip_adapter()
|
283 |
+
|
284 |
+
def init_proj(self):
|
285 |
+
image_proj_model = ProjPlusModel(
|
286 |
+
cross_attention_dim=self.pipe.unet.config.cross_attention_dim,
|
287 |
+
id_embeddings_dim=512,
|
288 |
+
clip_embeddings_dim=self.image_encoder.config.hidden_size,
|
289 |
+
num_tokens=self.num_tokens,
|
290 |
+
).to(self.device, dtype=self.torch_dtype)
|
291 |
+
return image_proj_model
|
292 |
+
|
293 |
+
def set_ip_adapter(self):
|
294 |
+
unet = self.pipe.unet
|
295 |
+
attn_procs = {}
|
296 |
+
for name in unet.attn_processors.keys():
|
297 |
+
cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim
|
298 |
+
if name.startswith("mid_block"):
|
299 |
+
hidden_size = unet.config.block_out_channels[-1]
|
300 |
+
elif name.startswith("up_blocks"):
|
301 |
+
block_id = int(name[len("up_blocks.")])
|
302 |
+
hidden_size = list(reversed(unet.config.block_out_channels))[block_id]
|
303 |
+
elif name.startswith("down_blocks"):
|
304 |
+
block_id = int(name[len("down_blocks.")])
|
305 |
+
hidden_size = unet.config.block_out_channels[block_id]
|
306 |
+
if cross_attention_dim is None:
|
307 |
+
attn_procs[name] = AttnProcessor()
|
308 |
+
else:
|
309 |
+
attn_procs[name] = IPAttnProcessor(
|
310 |
+
hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, num_tokens=self.num_tokens,
|
311 |
+
).to(self.device, dtype=self.torch_dtype)
|
312 |
+
unet.set_attn_processor(attn_procs)
|
313 |
+
|
314 |
+
def load_ip_adapter(self):
|
315 |
+
if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors":
|
316 |
+
state_dict = {"image_proj": {}, "ip_adapter": {}}
|
317 |
+
with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f:
|
318 |
+
for key in f.keys():
|
319 |
+
if key.startswith("image_proj."):
|
320 |
+
state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key)
|
321 |
+
elif key.startswith("ip_adapter."):
|
322 |
+
state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key)
|
323 |
+
else:
|
324 |
+
state_dict = torch.load(self.ip_ckpt, map_location="cpu")
|
325 |
+
self.image_proj_model.load_state_dict(state_dict["image_proj"])
|
326 |
+
ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values())
|
327 |
+
ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False)
|
328 |
+
|
329 |
+
@torch.inference_mode()
|
330 |
+
def get_image_embeds(self, faceid_embeds, face_image, s_scale, shortcut):
|
331 |
+
if isinstance(face_image, Image.Image):
|
332 |
+
pil_image = [face_image]
|
333 |
+
clip_image = self.clip_image_processor(images=face_image, return_tensors="pt").pixel_values
|
334 |
+
clip_image = clip_image.to(self.device, dtype=self.torch_dtype)
|
335 |
+
clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2]
|
336 |
+
uncond_clip_image_embeds = self.image_encoder(
|
337 |
+
torch.zeros_like(clip_image), output_hidden_states=True
|
338 |
+
).hidden_states[-2]
|
339 |
+
|
340 |
+
faceid_embeds = faceid_embeds.to(self.device, dtype=self.torch_dtype)
|
341 |
+
image_prompt_embeds = self.image_proj_model(faceid_embeds, clip_image_embeds, shortcut=shortcut, scale=s_scale)
|
342 |
+
uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(faceid_embeds), uncond_clip_image_embeds, shortcut=shortcut, scale=s_scale)
|
343 |
+
return image_prompt_embeds, uncond_image_prompt_embeds
|
344 |
+
|
345 |
+
def set_scale(self, scale):
|
346 |
+
for attn_processor in self.pipe.unet.attn_processors.values():
|
347 |
+
if isinstance(attn_processor, LoRAIPAttnProcessor):
|
348 |
+
attn_processor.scale = scale
|
349 |
+
|
350 |
+
def generate(
|
351 |
+
self,
|
352 |
+
face_image=None,
|
353 |
+
faceid_embeds=None,
|
354 |
+
prompt=None,
|
355 |
+
negative_prompt=None,
|
356 |
+
scale=1.0,
|
357 |
+
num_samples=4,
|
358 |
+
seed=None,
|
359 |
+
guidance_scale=7.5,
|
360 |
+
num_inference_steps=30,
|
361 |
+
s_scale=1.0,
|
362 |
+
shortcut=False,
|
363 |
+
**kwargs,
|
364 |
+
):
|
365 |
+
self.set_scale(scale)
|
366 |
+
|
367 |
+
|
368 |
+
num_prompts = faceid_embeds.size(0)
|
369 |
+
|
370 |
+
if prompt is None:
|
371 |
+
prompt = "best quality, high quality"
|
372 |
+
if negative_prompt is None:
|
373 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
374 |
+
|
375 |
+
if not isinstance(prompt, List):
|
376 |
+
prompt = [prompt] * num_prompts
|
377 |
+
if not isinstance(negative_prompt, List):
|
378 |
+
negative_prompt = [negative_prompt] * num_prompts
|
379 |
+
|
380 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds, face_image, s_scale, shortcut)
|
381 |
+
|
382 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
383 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
384 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
385 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
386 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
387 |
+
|
388 |
+
with torch.inference_mode():
|
389 |
+
prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt(
|
390 |
+
prompt,
|
391 |
+
device=self.device,
|
392 |
+
num_images_per_prompt=num_samples,
|
393 |
+
do_classifier_free_guidance=True,
|
394 |
+
negative_prompt=negative_prompt,
|
395 |
+
)
|
396 |
+
prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1)
|
397 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
|
398 |
+
|
399 |
+
generator = get_generator(seed, self.device)
|
400 |
+
|
401 |
+
images = self.pipe(
|
402 |
+
prompt_embeds=prompt_embeds,
|
403 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
404 |
+
guidance_scale=guidance_scale,
|
405 |
+
num_inference_steps=num_inference_steps,
|
406 |
+
generator=generator,
|
407 |
+
**kwargs,
|
408 |
+
).images
|
409 |
+
|
410 |
+
return images
|
411 |
+
|
412 |
+
|
413 |
+
class IPAdapterFaceIDXL(IPAdapterFaceID):
|
414 |
+
"""SDXL"""
|
415 |
+
|
416 |
+
def generate(
|
417 |
+
self,
|
418 |
+
faceid_embeds=None,
|
419 |
+
prompt=None,
|
420 |
+
negative_prompt=None,
|
421 |
+
scale=1.0,
|
422 |
+
num_samples=4,
|
423 |
+
seed=None,
|
424 |
+
num_inference_steps=30,
|
425 |
+
**kwargs,
|
426 |
+
):
|
427 |
+
self.set_scale(scale)
|
428 |
+
|
429 |
+
num_prompts = faceid_embeds.size(0)
|
430 |
+
|
431 |
+
if prompt is None:
|
432 |
+
prompt = "best quality, high quality"
|
433 |
+
if negative_prompt is None:
|
434 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
435 |
+
|
436 |
+
if not isinstance(prompt, List):
|
437 |
+
prompt = [prompt] * num_prompts
|
438 |
+
if not isinstance(negative_prompt, List):
|
439 |
+
negative_prompt = [negative_prompt] * num_prompts
|
440 |
+
|
441 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds)
|
442 |
+
|
443 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
444 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
445 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
446 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
447 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
448 |
+
|
449 |
+
with torch.inference_mode():
|
450 |
+
(
|
451 |
+
prompt_embeds,
|
452 |
+
negative_prompt_embeds,
|
453 |
+
pooled_prompt_embeds,
|
454 |
+
negative_pooled_prompt_embeds,
|
455 |
+
) = self.pipe.encode_prompt(
|
456 |
+
prompt,
|
457 |
+
num_images_per_prompt=num_samples,
|
458 |
+
do_classifier_free_guidance=True,
|
459 |
+
negative_prompt=negative_prompt,
|
460 |
+
)
|
461 |
+
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
462 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
463 |
+
|
464 |
+
generator = get_generator(seed, self.device)
|
465 |
+
|
466 |
+
images = self.pipe(
|
467 |
+
prompt_embeds=prompt_embeds,
|
468 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
469 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
470 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
471 |
+
num_inference_steps=num_inference_steps,
|
472 |
+
generator=generator,
|
473 |
+
**kwargs,
|
474 |
+
).images
|
475 |
+
|
476 |
+
return images
|
477 |
+
|
478 |
+
|
479 |
+
class IPAdapterFaceIDPlusXL(IPAdapterFaceIDPlus):
|
480 |
+
"""SDXL"""
|
481 |
+
|
482 |
+
def generate(
|
483 |
+
self,
|
484 |
+
face_image=None,
|
485 |
+
faceid_embeds=None,
|
486 |
+
prompt=None,
|
487 |
+
negative_prompt=None,
|
488 |
+
scale=1.0,
|
489 |
+
num_samples=4,
|
490 |
+
seed=None,
|
491 |
+
guidance_scale=7.5,
|
492 |
+
num_inference_steps=30,
|
493 |
+
s_scale=1.0,
|
494 |
+
shortcut=True,
|
495 |
+
**kwargs,
|
496 |
+
):
|
497 |
+
self.set_scale(scale)
|
498 |
+
|
499 |
+
num_prompts = faceid_embeds.size(0)
|
500 |
+
|
501 |
+
if prompt is None:
|
502 |
+
prompt = "best quality, high quality"
|
503 |
+
if negative_prompt is None:
|
504 |
+
negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
|
505 |
+
|
506 |
+
if not isinstance(prompt, List):
|
507 |
+
prompt = [prompt] * num_prompts
|
508 |
+
if not isinstance(negative_prompt, List):
|
509 |
+
negative_prompt = [negative_prompt] * num_prompts
|
510 |
+
|
511 |
+
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(faceid_embeds, face_image, s_scale, shortcut)
|
512 |
+
|
513 |
+
bs_embed, seq_len, _ = image_prompt_embeds.shape
|
514 |
+
image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1)
|
515 |
+
image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
516 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1)
|
517 |
+
uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
|
518 |
+
|
519 |
+
with torch.inference_mode():
|
520 |
+
(
|
521 |
+
prompt_embeds,
|
522 |
+
negative_prompt_embeds,
|
523 |
+
pooled_prompt_embeds,
|
524 |
+
negative_pooled_prompt_embeds,
|
525 |
+
) = self.pipe.encode_prompt(
|
526 |
+
prompt,
|
527 |
+
num_images_per_prompt=num_samples,
|
528 |
+
do_classifier_free_guidance=True,
|
529 |
+
negative_prompt=negative_prompt,
|
530 |
+
)
|
531 |
+
prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1)
|
532 |
+
negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
|
533 |
+
|
534 |
+
generator = get_generator(seed, self.device)
|
535 |
+
|
536 |
+
images = self.pipe(
|
537 |
+
prompt_embeds=prompt_embeds,
|
538 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
539 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
540 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
541 |
+
num_inference_steps=num_inference_steps,
|
542 |
+
generator=generator,
|
543 |
+
guidance_scale=guidance_scale,
|
544 |
+
**kwargs,
|
545 |
+
).images
|
546 |
+
|
547 |
+
return images
|
ip_adapter/resampler.py
ADDED
@@ -0,0 +1,158 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py
|
2 |
+
# and https://github.com/lucidrains/imagen-pytorch/blob/main/imagen_pytorch/imagen_pytorch.py
|
3 |
+
|
4 |
+
import math
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn as nn
|
8 |
+
from einops import rearrange
|
9 |
+
from einops.layers.torch import Rearrange
|
10 |
+
|
11 |
+
|
12 |
+
# FFN
|
13 |
+
def FeedForward(dim, mult=4):
|
14 |
+
inner_dim = int(dim * mult)
|
15 |
+
return nn.Sequential(
|
16 |
+
nn.LayerNorm(dim),
|
17 |
+
nn.Linear(dim, inner_dim, bias=False),
|
18 |
+
nn.GELU(),
|
19 |
+
nn.Linear(inner_dim, dim, bias=False),
|
20 |
+
)
|
21 |
+
|
22 |
+
|
23 |
+
def reshape_tensor(x, heads):
|
24 |
+
bs, length, width = x.shape
|
25 |
+
# (bs, length, width) --> (bs, length, n_heads, dim_per_head)
|
26 |
+
x = x.view(bs, length, heads, -1)
|
27 |
+
# (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head)
|
28 |
+
x = x.transpose(1, 2)
|
29 |
+
# (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head)
|
30 |
+
x = x.reshape(bs, heads, length, -1)
|
31 |
+
return x
|
32 |
+
|
33 |
+
|
34 |
+
class PerceiverAttention(nn.Module):
|
35 |
+
def __init__(self, *, dim, dim_head=64, heads=8):
|
36 |
+
super().__init__()
|
37 |
+
self.scale = dim_head**-0.5
|
38 |
+
self.dim_head = dim_head
|
39 |
+
self.heads = heads
|
40 |
+
inner_dim = dim_head * heads
|
41 |
+
|
42 |
+
self.norm1 = nn.LayerNorm(dim)
|
43 |
+
self.norm2 = nn.LayerNorm(dim)
|
44 |
+
|
45 |
+
self.to_q = nn.Linear(dim, inner_dim, bias=False)
|
46 |
+
self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False)
|
47 |
+
self.to_out = nn.Linear(inner_dim, dim, bias=False)
|
48 |
+
|
49 |
+
def forward(self, x, latents):
|
50 |
+
"""
|
51 |
+
Args:
|
52 |
+
x (torch.Tensor): image features
|
53 |
+
shape (b, n1, D)
|
54 |
+
latent (torch.Tensor): latent features
|
55 |
+
shape (b, n2, D)
|
56 |
+
"""
|
57 |
+
x = self.norm1(x)
|
58 |
+
latents = self.norm2(latents)
|
59 |
+
|
60 |
+
b, l, _ = latents.shape
|
61 |
+
|
62 |
+
q = self.to_q(latents)
|
63 |
+
kv_input = torch.cat((x, latents), dim=-2)
|
64 |
+
k, v = self.to_kv(kv_input).chunk(2, dim=-1)
|
65 |
+
|
66 |
+
q = reshape_tensor(q, self.heads)
|
67 |
+
k = reshape_tensor(k, self.heads)
|
68 |
+
v = reshape_tensor(v, self.heads)
|
69 |
+
|
70 |
+
# attention
|
71 |
+
scale = 1 / math.sqrt(math.sqrt(self.dim_head))
|
72 |
+
weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards
|
73 |
+
weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
|
74 |
+
out = weight @ v
|
75 |
+
|
76 |
+
out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
|
77 |
+
|
78 |
+
return self.to_out(out)
|
79 |
+
|
80 |
+
|
81 |
+
class Resampler(nn.Module):
|
82 |
+
def __init__(
|
83 |
+
self,
|
84 |
+
dim=1024,
|
85 |
+
depth=8,
|
86 |
+
dim_head=64,
|
87 |
+
heads=16,
|
88 |
+
num_queries=8,
|
89 |
+
embedding_dim=768,
|
90 |
+
output_dim=1024,
|
91 |
+
ff_mult=4,
|
92 |
+
max_seq_len: int = 257, # CLIP tokens + CLS token
|
93 |
+
apply_pos_emb: bool = False,
|
94 |
+
num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence
|
95 |
+
):
|
96 |
+
super().__init__()
|
97 |
+
self.pos_emb = nn.Embedding(max_seq_len, embedding_dim) if apply_pos_emb else None
|
98 |
+
|
99 |
+
self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
|
100 |
+
|
101 |
+
self.proj_in = nn.Linear(embedding_dim, dim)
|
102 |
+
|
103 |
+
self.proj_out = nn.Linear(dim, output_dim)
|
104 |
+
self.norm_out = nn.LayerNorm(output_dim)
|
105 |
+
|
106 |
+
self.to_latents_from_mean_pooled_seq = (
|
107 |
+
nn.Sequential(
|
108 |
+
nn.LayerNorm(dim),
|
109 |
+
nn.Linear(dim, dim * num_latents_mean_pooled),
|
110 |
+
Rearrange("b (n d) -> b n d", n=num_latents_mean_pooled),
|
111 |
+
)
|
112 |
+
if num_latents_mean_pooled > 0
|
113 |
+
else None
|
114 |
+
)
|
115 |
+
|
116 |
+
self.layers = nn.ModuleList([])
|
117 |
+
for _ in range(depth):
|
118 |
+
self.layers.append(
|
119 |
+
nn.ModuleList(
|
120 |
+
[
|
121 |
+
PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads),
|
122 |
+
FeedForward(dim=dim, mult=ff_mult),
|
123 |
+
]
|
124 |
+
)
|
125 |
+
)
|
126 |
+
|
127 |
+
def forward(self, x):
|
128 |
+
if self.pos_emb is not None:
|
129 |
+
n, device = x.shape[1], x.device
|
130 |
+
pos_emb = self.pos_emb(torch.arange(n, device=device))
|
131 |
+
x = x + pos_emb
|
132 |
+
|
133 |
+
latents = self.latents.repeat(x.size(0), 1, 1)
|
134 |
+
|
135 |
+
x = self.proj_in(x)
|
136 |
+
|
137 |
+
if self.to_latents_from_mean_pooled_seq:
|
138 |
+
meanpooled_seq = masked_mean(x, dim=1, mask=torch.ones(x.shape[:2], device=x.device, dtype=torch.bool))
|
139 |
+
meanpooled_latents = self.to_latents_from_mean_pooled_seq(meanpooled_seq)
|
140 |
+
latents = torch.cat((meanpooled_latents, latents), dim=-2)
|
141 |
+
|
142 |
+
for attn, ff in self.layers:
|
143 |
+
latents = attn(x, latents) + latents
|
144 |
+
latents = ff(latents) + latents
|
145 |
+
|
146 |
+
latents = self.proj_out(latents)
|
147 |
+
return self.norm_out(latents)
|
148 |
+
|
149 |
+
|
150 |
+
def masked_mean(t, *, dim, mask=None):
|
151 |
+
if mask is None:
|
152 |
+
return t.mean(dim=dim)
|
153 |
+
|
154 |
+
denom = mask.sum(dim=dim, keepdim=True)
|
155 |
+
mask = rearrange(mask, "b n -> b n 1")
|
156 |
+
masked_t = t.masked_fill(~mask, 0.0)
|
157 |
+
|
158 |
+
return masked_t.sum(dim=dim) / denom.clamp(min=1e-5)
|
ip_adapter/test_resampler.py
ADDED
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
from resampler import Resampler
|
3 |
+
from transformers import CLIPVisionModel
|
4 |
+
|
5 |
+
BATCH_SIZE = 2
|
6 |
+
OUTPUT_DIM = 1280
|
7 |
+
NUM_QUERIES = 8
|
8 |
+
NUM_LATENTS_MEAN_POOLED = 4 # 0 for no mean pooling (previous behavior)
|
9 |
+
APPLY_POS_EMB = True # False for no positional embeddings (previous behavior)
|
10 |
+
IMAGE_ENCODER_NAME_OR_PATH = "laion/CLIP-ViT-H-14-laion2B-s32B-b79K"
|
11 |
+
|
12 |
+
|
13 |
+
def main():
|
14 |
+
image_encoder = CLIPVisionModel.from_pretrained(IMAGE_ENCODER_NAME_OR_PATH)
|
15 |
+
embedding_dim = image_encoder.config.hidden_size
|
16 |
+
print(f"image_encoder hidden size: ", embedding_dim)
|
17 |
+
|
18 |
+
image_proj_model = Resampler(
|
19 |
+
dim=1024,
|
20 |
+
depth=2,
|
21 |
+
dim_head=64,
|
22 |
+
heads=16,
|
23 |
+
num_queries=NUM_QUERIES,
|
24 |
+
embedding_dim=embedding_dim,
|
25 |
+
output_dim=OUTPUT_DIM,
|
26 |
+
ff_mult=2,
|
27 |
+
max_seq_len=257,
|
28 |
+
apply_pos_emb=APPLY_POS_EMB,
|
29 |
+
num_latents_mean_pooled=NUM_LATENTS_MEAN_POOLED,
|
30 |
+
)
|
31 |
+
|
32 |
+
dummy_images = torch.randn(BATCH_SIZE, 3, 224, 224)
|
33 |
+
with torch.no_grad():
|
34 |
+
image_embeds = image_encoder(dummy_images, output_hidden_states=True).hidden_states[-2]
|
35 |
+
print("image_embds shape: ", image_embeds.shape)
|
36 |
+
|
37 |
+
with torch.no_grad():
|
38 |
+
ip_tokens = image_proj_model(image_embeds)
|
39 |
+
print("ip_tokens shape:", ip_tokens.shape)
|
40 |
+
assert ip_tokens.shape == (BATCH_SIZE, NUM_QUERIES + NUM_LATENTS_MEAN_POOLED, OUTPUT_DIM)
|
41 |
+
|
42 |
+
|
43 |
+
if __name__ == "__main__":
|
44 |
+
main()
|
ip_adapter/utils.py
ADDED
@@ -0,0 +1,93 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import torch
|
2 |
+
import torch.nn.functional as F
|
3 |
+
import numpy as np
|
4 |
+
from PIL import Image
|
5 |
+
|
6 |
+
attn_maps = {}
|
7 |
+
def hook_fn(name):
|
8 |
+
def forward_hook(module, input, output):
|
9 |
+
if hasattr(module.processor, "attn_map"):
|
10 |
+
attn_maps[name] = module.processor.attn_map
|
11 |
+
del module.processor.attn_map
|
12 |
+
|
13 |
+
return forward_hook
|
14 |
+
|
15 |
+
def register_cross_attention_hook(unet):
|
16 |
+
for name, module in unet.named_modules():
|
17 |
+
if name.split('.')[-1].startswith('attn2'):
|
18 |
+
module.register_forward_hook(hook_fn(name))
|
19 |
+
|
20 |
+
return unet
|
21 |
+
|
22 |
+
def upscale(attn_map, target_size):
|
23 |
+
attn_map = torch.mean(attn_map, dim=0)
|
24 |
+
attn_map = attn_map.permute(1,0)
|
25 |
+
temp_size = None
|
26 |
+
|
27 |
+
for i in range(0,5):
|
28 |
+
scale = 2 ** i
|
29 |
+
if ( target_size[0] // scale ) * ( target_size[1] // scale) == attn_map.shape[1]*64:
|
30 |
+
temp_size = (target_size[0]//(scale*8), target_size[1]//(scale*8))
|
31 |
+
break
|
32 |
+
|
33 |
+
assert temp_size is not None, "temp_size cannot is None"
|
34 |
+
|
35 |
+
attn_map = attn_map.view(attn_map.shape[0], *temp_size)
|
36 |
+
|
37 |
+
attn_map = F.interpolate(
|
38 |
+
attn_map.unsqueeze(0).to(dtype=torch.float32),
|
39 |
+
size=target_size,
|
40 |
+
mode='bilinear',
|
41 |
+
align_corners=False
|
42 |
+
)[0]
|
43 |
+
|
44 |
+
attn_map = torch.softmax(attn_map, dim=0)
|
45 |
+
return attn_map
|
46 |
+
def get_net_attn_map(image_size, batch_size=2, instance_or_negative=False, detach=True):
|
47 |
+
|
48 |
+
idx = 0 if instance_or_negative else 1
|
49 |
+
net_attn_maps = []
|
50 |
+
|
51 |
+
for name, attn_map in attn_maps.items():
|
52 |
+
attn_map = attn_map.cpu() if detach else attn_map
|
53 |
+
attn_map = torch.chunk(attn_map, batch_size)[idx].squeeze()
|
54 |
+
attn_map = upscale(attn_map, image_size)
|
55 |
+
net_attn_maps.append(attn_map)
|
56 |
+
|
57 |
+
net_attn_maps = torch.mean(torch.stack(net_attn_maps,dim=0),dim=0)
|
58 |
+
|
59 |
+
return net_attn_maps
|
60 |
+
|
61 |
+
def attnmaps2images(net_attn_maps):
|
62 |
+
|
63 |
+
#total_attn_scores = 0
|
64 |
+
images = []
|
65 |
+
|
66 |
+
for attn_map in net_attn_maps:
|
67 |
+
attn_map = attn_map.cpu().numpy()
|
68 |
+
#total_attn_scores += attn_map.mean().item()
|
69 |
+
|
70 |
+
normalized_attn_map = (attn_map - np.min(attn_map)) / (np.max(attn_map) - np.min(attn_map)) * 255
|
71 |
+
normalized_attn_map = normalized_attn_map.astype(np.uint8)
|
72 |
+
#print("norm: ", normalized_attn_map.shape)
|
73 |
+
image = Image.fromarray(normalized_attn_map)
|
74 |
+
|
75 |
+
#image = fix_save_attn_map(attn_map)
|
76 |
+
images.append(image)
|
77 |
+
|
78 |
+
#print(total_attn_scores)
|
79 |
+
return images
|
80 |
+
def is_torch2_available():
|
81 |
+
return hasattr(F, "scaled_dot_product_attention")
|
82 |
+
|
83 |
+
def get_generator(seed, device):
|
84 |
+
|
85 |
+
if seed is not None:
|
86 |
+
if isinstance(seed, list):
|
87 |
+
generator = [torch.Generator(device).manual_seed(seed_item) for seed_item in seed]
|
88 |
+
else:
|
89 |
+
generator = torch.Generator(device).manual_seed(seed)
|
90 |
+
else:
|
91 |
+
generator = None
|
92 |
+
|
93 |
+
return generator
|