MCPcopy Create free account
hub / github.com/Monalissaa/DisenDiff / CustomDiffusionXFormersAttnProcessor

Class CustomDiffusionXFormersAttnProcessor

src/diffusers_model_pipeline.py:321–362  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

319
320
321class CustomDiffusionXFormersAttnProcessor:
322 def __init__(self, attention_op: Optional[Callable] = None):
323 self.attention_op = attention_op
324
325 def __call__(self, attn: CrossAttention, hidden_states, encoder_hidden_states=None, attention_mask=None):
326 batch_size, sequence_length, _ = hidden_states.shape
327
328 attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
329
330 query = attn.to_q(hidden_states)
331
332 crossattn = False
333 if encoder_hidden_states is None:
334 encoder_hidden_states = hidden_states
335 else:
336 crossattn = True
337 if attn.cross_attention_norm:
338 encoder_hidden_states = attn.norm_cross(encoder_hidden_states)
339
340 key = attn.to_k(encoder_hidden_states)
341 value = attn.to_v(encoder_hidden_states)
342 if crossattn:
343 detach = torch.ones_like(key)
344 detach[:, :1, :] = detach[:, :1, :]*0.
345 key = detach*key + (1-detach)*key.detach()
346 value = detach*value + (1-detach)*value.detach()
347
348 query = attn.head_to_batch_dim(query).contiguous()
349 key = attn.head_to_batch_dim(key).contiguous()
350 value = attn.head_to_batch_dim(value).contiguous()
351
352 hidden_states = xformers.ops.memory_efficient_attention(
353 query, key, value, attn_bias=attention_mask, op=self.attention_op
354 )
355 hidden_states = hidden_states.to(query.dtype)
356 hidden_states = attn.batch_to_head_dim(hidden_states)
357
358 # linear proj
359 hidden_states = attn.to_out[0](hidden_states)
360 # dropout
361 hidden_states = attn.to_out[1](hidden_states)
362 return hidden_states
363
364
365class CustomDiffusionPipeline(StableDiffusionPipeline):

Calls

no outgoing calls

Tested by

no test coverage detected