Spaces:
Runtime error
Runtime error
Commit ·
3b2b77a
1
Parent(s): eae0f7a
stylestudio
Browse filesFiles changed (19)
- app.pyAdded+238
- assets/style1.jpgAdded
- assets/style2.jpgAdded
- ip_adapter/__init__.pyAdded+15
- ip_adapter/__pycache__/__init__.cpython-310.pycAdded
- ip_adapter/__pycache__/__init__.cpython-39.pycAdded
- ip_adapter/__pycache__/attention_processor.cpython-310.pycAdded
- ip_adapter/__pycache__/attention_processor.cpython-39.pycAdded
- ip_adapter/__pycache__/ip_adapter.cpython-310.pycAdded
- ip_adapter/__pycache__/ip_adapter.cpython-39.pycAdded
- ip_adapter/__pycache__/resampler.cpython-310.pycAdded
- ip_adapter/__pycache__/resampler.cpython-39.pycAdded
- ip_adapter/__pycache__/utils.cpython-310.pycAdded
- ip_adapter/__pycache__/utils.cpython-39.pycAdded
- ip_adapter/attention_processor.pyAdded+1645
- ip_adapter/ip_adapter.pyAdded+1757
- ip_adapter/resampler.pyAdded+158
- ip_adapter/utils.pyAdded+142
- requirements.txtAdded+18
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238import syssys.path.append("./")import gradio as grimport torchfrom ip_adapter.utils import BLOCKS as BLOCKSimport numpy as npimport randomfrom diffusers import ( AutoencoderKL, StableDiffusionXLPipeline,)from ip_adapter import StyleStudio_Adapter
device = "cuda" if torch.cuda.is_available() else "cpu"dtype = torch.float16 if str(device).__contains__("cuda") else torch.float32import osos.system("git lfs install")os.system("git clone https://huggingface.co/h94/IP-Adapter")os.system("mv IP-Adapter/sdxl_models sdxl_models")
from huggingface_hub import hf_hub_download
# hf_hub_download(repo_id="h94/IP-Adapter", filename="sdxl_models/image_encoder", local_dir="./sdxl_models/image_encoder")hf_hub_download(repo_id="InstantX/CSGO", filename="csgo_4_32.bin", local_dir="./CSGO/")os.system('rm -rf IP-Adapter/models')base_model_path = "stabilityai/stable-diffusion-xl-base-1.0"image_encoder_path = "sdxl_models/image_encoder"csgo_ckpt ='./CSGO/csgo_4_32.bin'pretrained_vae_name_or_path ='madebyollin/sdxl-vae-fp16-fix'weight_dtype = torch.float16
vae = AutoencoderKL.from_pretrained(pretrained_vae_name_or_path,torch_dtype=torch.float16)pipe = StableDiffusionXLPipeline.from_pretrained( base_model_path, torch_dtype=torch.float16, add_watermarker=False, vae=vae)pipe.enable_vae_tiling()
target_style_blocks = BLOCKS['style']
csgo = StyleStudio_Adapter( pipe, image_encoder_path, csgo_ckpt, device, num_style_tokens=32, target_style_blocks=target_style_blocks, controlnet_adapter=False, style_model_resampler=True,
fuSAttn=True, end_fusion=20, adainIP=True, )
MAX_SEED = np.iinfo(np.int32).max
def get_example(): case = [ [ './assets/style1.jpg', "Text-Driven Style Synthesis", "A red apple", 7.0, 42, 20, ], ] return case
def run_for_examples(style_image_pil, target, prompt, guidance_scale, seed, end_fusion): return create_image( style_image_pil=style_image_pil, prompt=prompt, guidance_scale=7.0, num_inference_steps=50, seed=42, end_fusion=end_fusion, use_SAttn=True, crossModalAdaIN=True, )
def randomize_seed_fn(seed: int, randomize_seed: bool) -> int: if randomize_seed: seed = random.randint(0, MAX_SEED) return seed
def create_image( style_image_pil, prompt, guidance_scale, num_inference_steps, end_fusion, crossModalAdaIN, use_SAttn, seed, negative_prompt="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry",):
style_image = style_image_pil
generator = torch.Generator(device).manual_seed(seed) init_latents = torch.randn((1, 4, 128, 128), generator=generator, device="cuda", dtype=torch.float16) num_sample=1 if use_SAttn: num_sample=2 init_latents = init_latents.repeat(num_sample, 1, 1, 1) with torch.no_grad(): images = csgo.generate(pil_style_image=style_image, prompt=prompt, negative_prompt=negative_prompt, height=1024, width=1024, guidance_scale=guidance_scale, num_images_per_prompt=1, num_samples=num_sample, num_inference_steps=num_inference_steps, end_fusion=end_fusion, cross_modal_adain=crossModalAdaIN, use_SAttn=use_SAttn, generator=generator, )
if use_SAttn: return [images[1]] else: return [images[0]]
# Descriptiontitle = r"""<h1 align="center">StyleStudio: Text-Driven Style Transfer with Selective Control of Style Elements</h1>"""
description = r"""<b>Official 🤗 Gradio demo</b> for <a href='https://github.com/MingKunLei/StyleStudio' target='_blank'><b>StyleStudio: Text-Driven Style Transfer with Selective Control of Style Elements</b></a>.<br>How to use:<br>1. Upload a style image.2. <b>Enter your desired prompt<b>.3. Click the <b>Submit</b> button to begin customization.4. Share your stylized photo with your friends and enjoy! 😊
Advanced usage:<br>1. Click advanced options.2. Choose different guidance and steps.3. Set the timing for the Teacher Model's participation """
article = r"""---📝 **Tips**As the value of end_fusion increases, the style gradually diminishes.---📝 **Citation**<br>If our work is helpful for your research or applications, please cite us via:```bibtex
```📧 **Contact**<br>If you have any questions, please feel free to open an issue or directly reach us out at <b>leimingkun@westlake.edu.cn</b>."""
block = gr.Blocks(css="footer {visibility: hidden}").queue(max_size=10, api_open=False)with block: gr.Markdown(title) gr.Markdown(description)
with gr.Tabs(): with gr.Row(): with gr.Column(): with gr.Row(): with gr.Column(): style_image_pil = gr.Image(label="Style Image", type='pil')
target = gr.Radio(["Text-Driven Style Synthesis"], value="Text-Driven Style Synthesis", label="task")
prompt = gr.Textbox(label="Prompt", value="A red apple") neg_prompt = gr.Textbox(label="Negative Prompt", value="text, watermark, lowres, low quality, worst quality, deformed, glitch, low contrast, noisy, saturation, blurry")
with gr.Accordion(open=True, label="Advanced Options"):
guidance_scale = gr.Slider(minimum=1, maximum=15.0, step=0.01, value=7.0, label="guidance scale") num_inference_steps = gr.Slider(minimum=5, maximum=100.0, step=1.0, value=50, label="num inference steps") end_fusion = gr.Slider(minimum=0, maximum=num_inference_steps, step=1.0, value=20.0, label="end fusion") seed = gr.Slider(minimum=-1000000, maximum=1000000, value=1, step=1, label="Seed Value") randomize_seed = gr.Checkbox(label="Randomize seed", value=True) crossModalAdaIN = gr.Checkbox(label="Cross Modal AdaIN", value=True) use_SAttn = gr.Checkbox(label="Teacher Model", value=True)
generate_button = gr.Button("Generate Image")
with gr.Column(): generated_image = gr.Gallery(label="Generated Image")
generate_button.click( fn=randomize_seed_fn, inputs=[seed, randomize_seed], outputs=seed, queue=False, api_name=False, ).then( fn=create_image, inputs=[ style_image_pil, prompt, guidance_scale, num_inference_steps, end_fusion, crossModalAdaIN, use_SAttn, seed, neg_prompt,], outputs=[generated_image])
gr.Examples( examples=get_example(), inputs=[style_image_pil, target, prompt, guidance_scale, seed, end_fusion], fn=run_for_examples, outputs=[generated_image], cache_examples=True, )
gr.Markdown(article)
block.launch()123456789101112131415from .ip_adapter import IPAdapter, IPAdapterPlus, IPAdapterPlusXL, IPAdapterXL, IPAdapterFull,IPAdapterXL_CS,IPAdapter_CSfrom .ip_adapter import CSGOfrom .ip_adapter import StyleStudio_Adapter, StyleStudio_Adapter_expfrom .ip_adapter import IPAdapterXL_cross_modal__all__ = [ "IPAdapter", "IPAdapterPlus", "IPAdapterPlusXL", "IPAdapterXL", "CSGO", "StyleStudio_Adapter", "StyleStudio_Adapter_exp", "IPAdapterXL_cross_modal", "IPAdapterFull",]1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645# modified from https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.pyimport mathimport torchimport torch.nn as nnimport torch.nn.functional as Fimport torch.fft as fftimport pdb
class AttnProcessor(nn.Module): r""" Default processor for performing attention-related computations. """
def __init__( self, hidden_size=None, cross_attention_dim=None, save_in_unet='down', atten_control=None, ): super().__init__() self.atten_control = atten_control self.save_in_unet = save_in_unet
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape ) attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states elif attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
query = attn.head_to_batch_dim(query) key = attn.head_to_batch_dim(key) value = attn.head_to_batch_dim(value)
attention_probs = attn.get_attention_scores(query, key, attention_mask) hidden_states = torch.bmm(attention_probs, value) hidden_states = attn.batch_to_head_dim(hidden_states)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class IPAttnProcessor(nn.Module): r""" Attention processor for IP-Adapater. Args: hidden_size (`int`): The hidden size of the attention layer. cross_attention_dim (`int`): The number of channels in the `encoder_hidden_states`. scale (`float`, defaults to 1.0): the weight scale of image prompt. num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): The context length of the image features. """
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4, skip=False,save_in_unet='down', atten_control=None): super().__init__()
self.hidden_size = hidden_size self.cross_attention_dim = cross_attention_dim self.scale = scale self.num_tokens = num_tokens self.skip = skip
self.atten_control = atten_control self.save_in_unet = save_in_unet
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape ) attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] - self.num_tokens encoder_hidden_states, ip_hidden_states = ( encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :], ) if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
query = attn.head_to_batch_dim(query) key = attn.head_to_batch_dim(key) value = attn.head_to_batch_dim(value)
attention_probs = attn.get_attention_scores(query, key, attention_mask) hidden_states = torch.bmm(attention_probs, value) hidden_states = attn.batch_to_head_dim(hidden_states)
if not self.skip: # for ip-adapter ip_key = self.to_k_ip(ip_hidden_states) ip_value = self.to_v_ip(ip_hidden_states)
ip_key = attn.head_to_batch_dim(ip_key) ip_value = attn.head_to_batch_dim(ip_value)
ip_attention_probs = attn.get_attention_scores(query, ip_key, None) self.attn_map = ip_attention_probs ip_hidden_states = torch.bmm(ip_attention_probs, ip_value) ip_hidden_states = attn.batch_to_head_dim(ip_hidden_states)
hidden_states = hidden_states + self.scale * ip_hidden_states
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class AttnProcessor2_0(torch.nn.Module): r""" Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). """
def __init__( self, hidden_size=None, cross_attention_dim=None, save_in_unet='down', atten_control=None, ): super().__init__() if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") self.atten_control = atten_control self.save_in_unet = save_in_unet
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states elif attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class IPAttnProcessor2_0(torch.nn.Module): r""" Attention processor for IP-Adapater for PyTorch 2.0. Args: hidden_size (`int`): The hidden size of the attention layer. cross_attention_dim (`int`): The number of channels in the `encoder_hidden_states`. scale (`float`, defaults to 1.0): the weight scale of image prompt. num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): The context length of the image features. """
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4, skip=False,save_in_unet='down', atten_control=None): super().__init__()
if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
self.hidden_size = hidden_size self.cross_attention_dim = cross_attention_dim self.scale = scale self.num_tokens = num_tokens self.skip = skip
self.atten_control = atten_control self.save_in_unet = save_in_unet
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] - self.num_tokens encoder_hidden_states, ip_hidden_states = ( encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :], ) if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype)
if not self.skip: # for ip-adapter ip_key = self.to_k_ip(ip_hidden_states) ip_value = self.to_v_ip(ip_hidden_states)
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 ip_hidden_states = F.scaled_dot_product_attention( query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False ) with torch.no_grad(): self.attn_map = query @ ip_key.transpose(-2, -1).softmax(dim=-1) #print(self.attn_map.shape)
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) ip_hidden_states = ip_hidden_states.to(query.dtype)
hidden_states = hidden_states + self.scale * ip_hidden_states
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class IP_CS_AttnProcessor2_0(torch.nn.Module): r""" Attention processor for IP-Adapater for PyTorch 2.0. Args: hidden_size (`int`): The hidden size of the attention layer. cross_attention_dim (`int`): The number of channels in the `encoder_hidden_states`. scale (`float`, defaults to 1.0): the weight scale of image prompt. num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): The context length of the image features. """
def __init__(self, hidden_size, cross_attention_dim=None, content_scale=1.0,style_scale=1.0, num_content_tokens=4,num_style_tokens=4, skip=False,content=False, style=False): super().__init__()
if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
self.hidden_size = hidden_size self.cross_attention_dim = cross_attention_dim self.content_scale = content_scale self.style_scale = style_scale self.num_content_tokens = num_content_tokens self.num_style_tokens = num_style_tokens self.skip = skip
self.content = content self.style = style
if self.content or self.style: self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_k_ip_content =None self.to_v_ip_content =None
def set_content_ipa(self,content_scale=1.0):
self.to_k_ip_content = nn.Linear(self.cross_attention_dim or self.hidden_size, self.hidden_size, bias=False) self.to_v_ip_content = nn.Linear(self.cross_attention_dim or self.hidden_size, self.hidden_size, bias=False) self.content_scale=content_scale self.content =True
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] - self.num_content_tokens-self.num_style_tokens encoder_hidden_states, ip_content_hidden_states,ip_style_hidden_states = ( encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:end_pos + self.num_content_tokens, :], encoder_hidden_states[:, end_pos + self.num_content_tokens:, :], ) if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype)
if self.content is True: exit() if not self.skip and self.content is True: # print('content#####################################################') # for ip-content-adapter if self.to_k_ip_content is None:
ip_content_key = self.to_k_ip(ip_content_hidden_states) ip_content_value = self.to_v_ip(ip_content_hidden_states) else: ip_content_key = self.to_k_ip_content(ip_content_hidden_states) ip_content_value = self.to_v_ip_content(ip_content_hidden_states)
ip_content_key = ip_content_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) ip_content_value = ip_content_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 ip_content_hidden_states = F.scaled_dot_product_attention( query, ip_content_key, ip_content_value, attn_mask=None, dropout_p=0.0, is_causal=False )
ip_content_hidden_states = ip_content_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) ip_content_hidden_states = ip_content_hidden_states.to(query.dtype)
hidden_states = hidden_states + self.content_scale * ip_content_hidden_states
if not self.skip and self.style is True: # for ip-style-adapter ip_style_key = self.to_k_ip(ip_style_hidden_states) ip_style_value = self.to_v_ip(ip_style_hidden_states)
ip_style_key = ip_style_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) ip_style_value = ip_style_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 ip_style_hidden_states = F.scaled_dot_product_attention( query, ip_style_key, ip_style_value, attn_mask=None, dropout_p=0.0, is_causal=False )
ip_style_hidden_states = ip_style_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) ip_style_hidden_states = ip_style_hidden_states.to(query.dtype)
hidden_states = hidden_states + self.style_scale * ip_style_hidden_states
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
## for controlnetclass CNAttnProcessor: r""" Default processor for performing attention-related computations. """
def __init__(self, num_tokens=4,save_in_unet='down',atten_control=None): self.num_tokens = num_tokens self.atten_control = atten_control self.save_in_unet = save_in_unet
def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape ) attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: end_pos = encoder_hidden_states.shape[1] - self.num_tokens encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
query = attn.head_to_batch_dim(query) key = attn.head_to_batch_dim(key) value = attn.head_to_batch_dim(value)
attention_probs = attn.get_attention_scores(query, key, attention_mask) hidden_states = torch.bmm(attention_probs, value) hidden_states = attn.batch_to_head_dim(hidden_states)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class CNAttnProcessor2_0: r""" Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). """
def __init__(self, num_tokens=4, save_in_unet='down', atten_control=None): if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") self.num_tokens = num_tokens self.atten_control = atten_control self.save_in_unet = save_in_unet
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: end_pos = encoder_hidden_states.shape[1] - self.num_tokens encoder_hidden_states = encoder_hidden_states[:, :end_pos] # only use text if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
return hidden_states
class IP_FuAd_AttnProcessor2_0(torch.nn.Module): r""" Attention processor for IP-Adapater for PyTorch 2.0. Args: hidden_size (`int`): The hidden size of the attention layer. cross_attention_dim (`int`): The number of channels in the `encoder_hidden_states`. scale (`float`, defaults to 1.0): the weight scale of image prompt. num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): The context length of the image features. """
def __init__(self, hidden_size, cross_attention_dim=None, content_scale=1.0,style_scale=1.0, num_content_tokens=4,num_style_tokens=4, skip=False,content=False, style=False, fuAttn=False, fuIPAttn=False, adainIP=False, fuScale=0, end_fusion=0, attn_name=None): super().__init__()
if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
self.hidden_size = hidden_size self.cross_attention_dim = cross_attention_dim self.content_scale = content_scale self.style_scale = style_scale self.num_style_tokens = num_style_tokens self.skip = skip
self.content = content self.style = style
self.fuAttn = fuAttn self.fuIPAttn = fuIPAttn self.adainIP = adainIP self.fuScale = fuScale self.denoise_step = 0 self.end_fusion = end_fusion self.name = attn_name
if self.content or self.style: self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_k_ip_content =None self.to_v_ip_content =None
# def set_content_ipa(self,content_scale=1.0):
# self.to_k_ip_content = nn.Linear(self.cross_attention_dim or self.hidden_size, self.hidden_size, bias=False) # self.to_v_ip_content = nn.Linear(self.cross_attention_dim or self.hidden_size, self.hidden_size, bias=False) # self.content_scale=content_scale # self.content =True def reset_denoise_step(self): if self.denoise_step == 50: self.denoise_step = 0 # if "up_blocks.0.attentions.1.transformer_blocks.0.attn2" in self.name: # print("attn2 reset successful") def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): self.denoise_step += 1 residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] -self.num_style_tokens encoder_hidden_states, ip_style_hidden_states = ( encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :], ) if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 # # modified the attnMap of the Stylization Image if self.fuAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) text_attn_probs = (torch.matmul(query, key.transpose(-2, -1)) * scale_factor).softmax(dim=-1) text_attn_probs[1] = self.fuScale*text_attn_probs[1] + (1-self.fuScale)*text_attn_probs[0] text_attn_probs[3] = self.fuScale*text_attn_probs[3] + (1-self.fuScale)*text_attn_probs[2] hidden_states = torch.matmul(text_attn_probs, value) else: hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype) raw_hidden_states = hidden_states
if not self.skip and self.style is True: # for ip-style-adapter ip_style_key = self.to_k_ip(ip_style_hidden_states) ip_style_value = self.to_v_ip(ip_style_hidden_states)
ip_style_key = ip_style_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) ip_style_value = ip_style_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 if self.fuIPAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 if "down" in self.name: print("wrong! coding") exit() scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) ip_attn_probs = torch.matmul(query, ip_style_key.transpose(-2, -1)) * scale_factor ip_attn_probs = F.softmax(ip_attn_probs, dim=-1) ip_attn_probs[1] = self.fuScale*ip_attn_probs[1] + (1-self.fuScale)*ip_attn_probs[0] ip_attn_probs[3] = self.fuScale*ip_attn_probs[3] + (1-self.fuScale)*ip_attn_probs[2] ip_style_hidden_states = torch.matmul(ip_attn_probs, ip_style_value) else: ip_style_hidden_states = F.scaled_dot_product_attention( query, ip_style_key, ip_style_value, attn_mask=None, dropout_p=0.0, is_causal=False )
ip_style_hidden_states = ip_style_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) ip_style_hidden_states = ip_style_hidden_states.to(query.dtype)
if not self.adainIP: hidden_states = hidden_states + self.style_scale * ip_style_hidden_states else: # print("adain") def adain(content, style): content_mean = content.mean(dim=1, keepdim=True) content_std = content.std(dim=1, keepdim=True) style_mean = style.mean(dim=1, keepdim=True) style_std = style.std(dim=1, keepdim=True) normalized_content = (content - content_mean) / content_std stylized_content = normalized_content * style_std + style_mean return stylized_content hidden_states = adain(content=hidden_states, style=ip_style_hidden_states)
if hidden_states.shape[0] == 4: hidden_states[0] = raw_hidden_states[0] hidden_states[2] = raw_hidden_states[2] # hidden_states = raw_hidden_states
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
self.reset_denoise_step() return hidden_states
class IP_FuAd_AttnProcessor2_0_exp(torch.nn.Module): r""" Attention processor for IP-Adapater for PyTorch 2.0. Args: hidden_size (`int`): The hidden size of the attention layer. cross_attention_dim (`int`): The number of channels in the `encoder_hidden_states`. scale (`float`, defaults to 1.0): the weight scale of image prompt. num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): The context length of the image features. """
def __init__(self, hidden_size, cross_attention_dim=None, content_scale=1.0,style_scale=1.0, num_content_tokens=4,num_style_tokens=4, skip=False,content=False, style=False, fuAttn=False, fuIPAttn=False, adainIP=False, fuScale=0, end_fusion=0, attn_name=None, save_attn_map=False): super().__init__()
if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
self.hidden_size = hidden_size self.cross_attention_dim = cross_attention_dim self.content_scale = content_scale self.style_scale = style_scale self.num_style_tokens = num_style_tokens self.skip = skip
self.content = content self.style = style
self.fuAttn = fuAttn self.fuIPAttn = fuIPAttn self.adainIP = adainIP self.fuScale = fuScale self.denoise_step = 0 self.end_fusion = end_fusion self.name = attn_name
self.save_attn_map = save_attn_map
if self.content or self.style: self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_k_ip_content =None self.to_v_ip_content =None
# def set_content_ipa(self,content_scale=1.0):
# self.to_k_ip_content = nn.Linear(self.cross_attention_dim or self.hidden_size, self.hidden_size, bias=False) # self.to_v_ip_content = nn.Linear(self.cross_attention_dim or self.hidden_size, self.hidden_size, bias=False) # self.content_scale=content_scale # self.content =True def reset_denoise_step(self): if self.denoise_step == 50: self.denoise_step = 0 # if "up_blocks.0.attentions.1.transformer_blocks.0.attn2" in self.name: # print("attn2 reset successful") def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): self.denoise_step += 1 residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2) query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] - self.num_content_tokens-self.num_style_tokens encoder_hidden_states, ip_style_hidden_states = ( encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :], ) if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
## attention map if self.save_attn_map: attention_probs = attn.get_attention_scores(attn.head_to_batch_dim(query), attn.head_to_batch_dim(value), attention_mask) if attention_probs is not None: if not hasattr(attn, "attn_map"): setattr(attn, "attn_map", {}) setattr(attn, "inference_step", 0) else: attn.inference_step += 1 # # maybe we need to save all the timestep # if attn.inference_step in self.attn_map_save_steps: attn.attn_map[attn.inference_step] = attention_probs.clone().cpu().detach() # attn.attn_map[attn.inference_step] = attention_probs.detach() ## end of attention map else: print(f"{attn} didn't get the attention probs") inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 # # modified the attnMap of the Stylization Image if self.fuAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) text_attn_probs = (torch.matmul(query, key.transpose(-2, -1)) * scale_factor).softmax(dim=-1) text_attn_probs[1] = self.fuScale*text_attn_probs[1] + (1-self.fuScale)*text_attn_probs[0] text_attn_probs[3] = self.fuScale*text_attn_probs[3] + (1-self.fuScale)*text_attn_probs[2] hidden_states = torch.matmul(text_attn_probs, value) else: hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype) raw_hidden_states = hidden_states
if not self.skip and self.style is True: # for ip-style-adapter ip_style_key = self.to_k_ip(ip_style_hidden_states) ip_style_value = self.to_v_ip(ip_style_hidden_states)
ip_style_key = ip_style_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) ip_style_value = ip_style_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 if self.fuIPAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 if "down" in self.name: print("wrong! coding") exit() scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) ip_attn_probs = torch.matmul(query, ip_style_key.transpose(-2, -1)) * scale_factor ip_attn_probs = F.softmax(ip_attn_probs, dim=-1) ip_attn_probs[1] = self.fuScale*ip_attn_probs[1] + (1-self.fuScale)*ip_attn_probs[0] ip_attn_probs[3] = self.fuScale*ip_attn_probs[3] + (1-self.fuScale)*ip_attn_probs[2] ip_style_hidden_states = torch.matmul(ip_attn_probs, ip_style_value) else: ip_style_hidden_states = F.scaled_dot_product_attention( query, ip_style_key, ip_style_value, attn_mask=None, dropout_p=0.0, is_causal=False )
ip_style_hidden_states = ip_style_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) ip_style_hidden_states = ip_style_hidden_states.to(query.dtype)
# if self.adainIP and self.denoise_step >= self.start_adain: if self.adainIP: # print("adain") # if self.denoise_step == 1 and "up_blocks.1.attentions.2.transformer_blocks.1" in self.name: # print("adain") def adain(content, style): content_mean = content.mean(dim=1, keepdim=True) content_std = content.std(dim=1, keepdim=True) print("exp code") pdb.set_trace() style_mean = style.mean(dim=1, keepdim=True) style_std = style.std(dim=1, keepdim=True) normalized_content = (content - content_mean) / content_std stylized_content = normalized_content * style_std + style_mean return stylized_content pdb.set_trace() hidden_states = adain(content=hidden_states, style=ip_style_hidden_states) else: hidden_states = hidden_states + self.style_scale * ip_style_hidden_states
if hidden_states.shape[0] == 4: hidden_states[0] = raw_hidden_states[0] hidden_states[2] = raw_hidden_states[2] # hidden_states = raw_hidden_states
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
self.reset_denoise_step() return hidden_states
class AttnProcessor2_0_hijack(torch.nn.Module): r""" Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). """
def __init__( self, hidden_size=None, cross_attention_dim=None, save_in_unet='down', atten_control=None, fuSAttn=False, fuScale=0, end_fusion=0, attn_name=None, ): super().__init__() if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") self.atten_control = atten_control self.save_in_unet = save_in_unet self.fuSAttn = fuSAttn self.fuScale = fuScale self.denoise_step = 0 self.end_fusion = end_fusion self.name = attn_name
def reset_denoise_step(self): if self.denoise_step == 50: self.denoise_step = 0 # if "up_blocks.0.attentions.1.transformer_blocks.0.attn1" in self.name: # print("attn1 reset successful")
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): self.denoise_step += 1 residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states elif attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 if self.fuSAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 if "up_blocks.1.attentions.2.transformer_blocks.1" in self.name and self.denoise_step == self.end_fusion: print("now: ", self.denoise_step, "end now:", self.end_fusion, "scale: ", self.fuScale) # pdb.set_trace() scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) attn_probs = (torch.matmul(query, key.transpose(-2, -1)) * scale_factor).softmax(dim=-1) attn_probs[1] = self.fuScale*attn_probs[1] + (1-self.fuScale)*attn_probs[0] attn_probs[3] = self.fuScale*attn_probs[3] + (1-self.fuScale)*attn_probs[2] hidden_states = torch.matmul(attn_probs, value) else: hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
if self.denoise_step == 50: self.reset_denoise_step() return hidden_states class AttnProcessor2_0_exp(torch.nn.Module): r""" Processor for implementing scaled dot-product attention (enabled by default if you're using PyTorch 2.0). """
def __init__( self, hidden_size=None, cross_attention_dim=None, save_in_unet='down', atten_control=None, fuSAttn=False, fuScale=0, end_fusion=0, attn_name=None, ): super().__init__() if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.") self.atten_control = atten_control self.save_in_unet = save_in_unet self.fuSAttn = fuSAttn self.fuScale = fuScale self.denoise_step = 0 self.end_fusion = end_fusion self.name = attn_name
def reset_denoise_step(self): if self.denoise_step == 50: self.denoise_step = 0 # if "up_blocks.0.attentions.1.transformer_blocks.0.attn1" in self.name: # print("attn1 reset successful")
def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): self.denoise_step += 1 residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states elif attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 if self.fuSAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 if "up_blocks.1.attentions.2.transformer_blocks.1" in self.name and self.denoise_step == self.end_fusion: print("now: ", self.denoise_step, "end now:", self.end_fusion, "scale: ", self.fuScale) # pdb.set_trace() scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) attn_probs = (torch.matmul(query, key.transpose(-2, -1)) * scale_factor).softmax(dim=-1) attn_probs[1] = self.fuScale*attn_probs[1] + (1-self.fuScale)*attn_probs[0] attn_probs[3] = self.fuScale*attn_probs[3] + (1-self.fuScale)*attn_probs[2] print("exp code") pdb.set_trace() def adain(content, style): content_mean = content.mean(dim=1, keepdim=True) content_std = content.std(dim=1, keepdim=True) style_mean = style.mean(dim=1, keepdim=True) style_std = style.std(dim=1, keepdim=True) normalized_content = (content - content_mean) / content_std stylized_content = normalized_content * style_std + style_mean return stylized_content value[1] = adain(content=value[0], style=value[1]) value[3] = adain(content=value[2], style=value[3]) hidden_states = torch.matmul(attn_probs, value) else: hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype)
# linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
self.reset_denoise_step() return hidden_states class IPAttnProcessor2_0_cross_modal(torch.nn.Module): r""" Attention processor for IP-Adapater for PyTorch 2.0. Args: hidden_size (`int`): The hidden size of the attention layer. cross_attention_dim (`int`): The number of channels in the `encoder_hidden_states`. scale (`float`, defaults to 1.0): the weight scale of image prompt. num_tokens (`int`, defaults to 4 when do ip_adapter_plus it should be 16): The context length of the image features. """
def __init__(self, hidden_size, cross_attention_dim=None, scale=1.0, num_tokens=4, skip=False, fuAttn=False, fuIPAttn=False, adainIP=False, end_fusion=0, fuScale=0, attn_name=None): super().__init__()
if not hasattr(F, "scaled_dot_product_attention"): raise ImportError("AttnProcessor2_0 requires PyTorch 2.0, to use it, please upgrade PyTorch to 2.0.")
self.hidden_size = hidden_size self.cross_attention_dim = cross_attention_dim self.scale = scale self.num_tokens = num_tokens self.skip = skip
self.fuAttn = fuAttn self.fuIPAttn = fuIPAttn self.adainIP = adainIP self.denoise_step = fuScale self.end_fusion = end_fusion self.fuScale = fuScale self.name = attn_name
self.to_k_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False) self.to_v_ip = nn.Linear(cross_attention_dim or hidden_size, hidden_size, bias=False)
def reset_denoise_step(self): if self.denoise_step == 50: self.denoise_step = 0 # if "up_blocks.0.attentions.1.transformer_blocks.0.attn2" in self.name: # print("attn2 reset successful") def __call__( self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, temb=None, ): self.denoise_step += 1 residual = hidden_states
if attn.spatial_norm is not None: hidden_states = attn.spatial_norm(hidden_states, temb)
input_ndim = hidden_states.ndim
if input_ndim == 4: batch_size, channel, height, width = hidden_states.shape hidden_states = hidden_states.view(batch_size, channel, height * width).transpose(1, 2)
batch_size, sequence_length, _ = ( hidden_states.shape if encoder_hidden_states is None else encoder_hidden_states.shape )
if attention_mask is not None: attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) # scaled_dot_product_attention expects attention_mask shape to be # (batch, heads, source_length, target_length) attention_mask = attention_mask.view(batch_size, attn.heads, -1, attention_mask.shape[-1])
if attn.group_norm is not None: hidden_states = attn.group_norm(hidden_states.transpose(1, 2)).transpose(1, 2)
query = attn.to_q(hidden_states)
if encoder_hidden_states is None: encoder_hidden_states = hidden_states else: # get encoder_hidden_states, ip_hidden_states end_pos = encoder_hidden_states.shape[1] - self.num_tokens encoder_hidden_states, ip_hidden_states = ( encoder_hidden_states[:, :end_pos, :], encoder_hidden_states[:, end_pos:, :], ) if attn.norm_cross: encoder_hidden_states = attn.norm_encoder_hidden_states(encoder_hidden_states)
key = attn.to_k(encoder_hidden_states) value = attn.to_v(encoder_hidden_states)
inner_dim = key.shape[-1] head_dim = inner_dim // attn.heads
query = query.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
key = key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) value = value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 if self.fuAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 if "up_blocks.1.attentions.2.transformer_blocks.1" in self.name and self.denoise_step == self.end_fusion: print("fuAttn") print("now: ", self.denoise_step, "end now:", self.end_fusion, "scale: ", self.fuScale) scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) text_attn_probs = (torch.matmul(query, key.transpose(-2, -1)) * scale_factor).softmax(dim=-1) text_attn_probs[1] = self.fuScale*text_attn_probs[1] + (1-self.fuScale)*text_attn_probs[0] text_attn_probs[3] = self.fuScale*text_attn_probs[3] + (1-self.fuScale)*text_attn_probs[2] hidden_states = torch.matmul(text_attn_probs, value) else: hidden_states = F.scaled_dot_product_attention( query, key, value, attn_mask=attention_mask, dropout_p=0.0, is_causal=False )
hidden_states = hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) hidden_states = hidden_states.to(query.dtype)
raw_hidden_states = hidden_states
if not self.skip: # for ip-adapter ip_key = self.to_k_ip(ip_hidden_states) ip_value = self.to_v_ip(ip_hidden_states)
ip_key = ip_key.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2) ip_value = ip_value.view(batch_size, -1, attn.heads, head_dim).transpose(1, 2)
# the output of sdp = (batch, num_heads, seq_len, head_dim) # TODO: add support for attn.scale when we move to Torch 2.1 if self.fuIPAttn and self.denoise_step <= self.end_fusion: assert query.shape[0] == 4 print("fuIPAttn") if "down" in self.name: print("wrong! coding") exit() scale_factor = 1 / math.sqrt(torch.tensor(head_dim, dtype=query.dtype)) ip_attn_probs = torch.matmul(query, ip_key.transpose(-2, -1)) * scale_factor ip_attn_probs = F.softmax(ip_attn_probs, dim=-1) ip_attn_probs[1] = self.fuScale*ip_attn_probs[1] + (1-self.fuScale)*ip_attn_probs[0] ip_attn_probs[3] = self.fuScale*ip_attn_probs[3] + (1-self.fuScale)*ip_attn_probs[2] ip_hidden_states = torch.matmul(ip_attn_probs, ip_value) else: ip_hidden_states = F.scaled_dot_product_attention( query, ip_key, ip_value, attn_mask=None, dropout_p=0.0, is_causal=False )
with torch.no_grad(): self.attn_map = query @ ip_key.transpose(-2, -1).softmax(dim=-1) #print(self.attn_map.shape)
ip_hidden_states = ip_hidden_states.transpose(1, 2).reshape(batch_size, -1, attn.heads * head_dim) ip_hidden_states = ip_hidden_states.to(query.dtype) if self.adainIP: def adain(content, style): # 计算内容特征的均值和标准差 content_mean = content.mean(dim=1, keepdim=True) content_std = content.std(dim=1, keepdim=True) # 计算风格特征的均值和标准差 style_mean = style.mean(dim=1, keepdim=True) style_std = style.std(dim=1, keepdim=True) # 归一化内容特征并应用风格特征的均值和方差 normalized_content = (content - content_mean) / content_std stylized_content = normalized_content * style_std + style_mean return stylized_content hidden_states = adain(content=hidden_states, style=ip_hidden_states) else: hidden_states = hidden_states + self.scale * ip_hidden_states if hidden_states.shape[0] == 4: hidden_states[0] = raw_hidden_states[0] hidden_states[2] = raw_hidden_states[2] # linear proj hidden_states = attn.to_out[0](hidden_states) # dropout hidden_states = attn.to_out[1](hidden_states)
if input_ndim == 4: hidden_states = hidden_states.transpose(-1, -2).reshape(batch_size, channel, height, width)
if attn.residual_connection: hidden_states = hidden_states + residual
hidden_states = hidden_states / attn.rescale_output_factor
if self.denoise_step == 50: self.reset_denoise_step()
return hidden_states12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757import torch.nn.functional as Fimport osfrom typing import List
import torchfrom diffusers import StableDiffusionPipelinefrom diffusers.pipelines.controlnet import MultiControlNetModelfrom PIL import Imagefrom safetensors import safe_openfrom transformers import CLIPImageProcessor, CLIPVisionModelWithProjectionfrom torchvision import transformsfrom .utils import is_torch2_available, get_generator
if is_torch2_available(): from .attention_processor import ( AttnProcessor2_0 as AttnProcessor, ) from .attention_processor import ( CNAttnProcessor2_0 as CNAttnProcessor, ) from .attention_processor import ( IPAttnProcessor2_0 as IPAttnProcessor, ) from .attention_processor import IP_CS_AttnProcessor2_0 as IP_CS_AttnProcessor from .attention_processor import IP_FuAd_AttnProcessor2_0 as IP_FuAd_AttnProcessor from .attention_processor import IP_FuAd_AttnProcessor2_0_exp as IP_FuAd_AttnProcessor_exp from .attention_processor import AttnProcessor2_0_exp as AttnProcessor_exp from .attention_processor import AttnProcessor2_0_hijack as AttnProcessor_hijack from .attention_processor import IPAttnProcessor2_0_cross_modal as IPAttnProcessor_cross_modalelse: from .attention_processor import AttnProcessor, CNAttnProcessor, IPAttnProcessor
from .resampler import Resampler
from transformers import AutoImageProcessor, AutoModel
class ImageProjModel(torch.nn.Module): """Projection Model"""
def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024, clip_extra_context_tokens=4): super().__init__()
self.generator = None self.cross_attention_dim = cross_attention_dim self.clip_extra_context_tokens = clip_extra_context_tokens # print(clip_embeddings_dim, self.clip_extra_context_tokens, cross_attention_dim) self.proj = torch.nn.Linear(clip_embeddings_dim, self.clip_extra_context_tokens * cross_attention_dim) self.norm = torch.nn.LayerNorm(cross_attention_dim)
def forward(self, image_embeds): embeds = image_embeds clip_extra_context_tokens = self.proj(embeds).reshape( -1, self.clip_extra_context_tokens, self.cross_attention_dim ) clip_extra_context_tokens = self.norm(clip_extra_context_tokens) return clip_extra_context_tokens
class MLPProjModel(torch.nn.Module): """SD model with image prompt"""
def __init__(self, cross_attention_dim=1024, clip_embeddings_dim=1024): super().__init__()
self.proj = torch.nn.Sequential( torch.nn.Linear(clip_embeddings_dim, clip_embeddings_dim), torch.nn.GELU(), torch.nn.Linear(clip_embeddings_dim, cross_attention_dim), torch.nn.LayerNorm(cross_attention_dim) )
def forward(self, image_embeds): clip_extra_context_tokens = self.proj(image_embeds) return clip_extra_context_tokens
class IPAdapter: def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_tokens=4, target_blocks=["block"]): self.device = device self.image_encoder_path = image_encoder_path self.ip_ckpt = ip_ckpt self.num_tokens = num_tokens self.target_blocks = target_blocks
self.pipe = sd_pipe.to(self.device) self.set_ip_adapter()
# load image encoder self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to( self.device, dtype=torch.float16 ) self.clip_image_processor = CLIPImageProcessor() # image proj model self.image_proj_model = self.init_proj()
self.load_ip_adapter()
def init_proj(self): image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.projection_dim, clip_extra_context_tokens=self.num_tokens, ).to(self.device, dtype=torch.float16) return image_proj_model
def set_ip_adapter(self): unet = self.pipe.unet attn_procs = {} for name in unet.attn_processors.keys(): cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim if name.startswith("mid_block"): hidden_size = unet.config.block_out_channels[-1] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(unet.config.block_out_channels))[block_id] elif name.startswith("down_blocks"): block_id = int(name[len("down_blocks.")]) hidden_size = unet.config.block_out_channels[block_id] if cross_attention_dim is None: attn_procs[name] = AttnProcessor() else: selected = False for block_name in self.target_blocks: if block_name in name: selected = True break if selected: attn_procs[name] = IPAttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, num_tokens=self.num_tokens, ).to(self.device, dtype=torch.float16) else: attn_procs[name] = IPAttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, num_tokens=self.num_tokens, skip=True ).to(self.device, dtype=torch.float16) unet.set_attn_processor(attn_procs) if hasattr(self.pipe, "controlnet"): if isinstance(self.pipe.controlnet, MultiControlNetModel): for controlnet in self.pipe.controlnet.nets: controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens)) else: self.pipe.controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
def load_ip_adapter(self): if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors": state_dict = {"image_proj": {}, "ip_adapter": {}} with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f: for key in f.keys(): if key.startswith("image_proj."): state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key) elif key.startswith("ip_adapter."): state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key) else: state_dict = torch.load(self.ip_ckpt, map_location="cpu") self.image_proj_model.load_state_dict(state_dict["image_proj"]) ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values()) ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False)
@torch.inference_mode() def get_image_embeds(self, pil_image=None, clip_image_embeds=None, content_prompt_embeds=None): if pil_image is not None: if isinstance(pil_image, Image.Image): pil_image = [pil_image] clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds else: clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16)
if content_prompt_embeds is not None: clip_image_embeds = clip_image_embeds - content_prompt_embeds
image_prompt_embeds = self.image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(clip_image_embeds)) return image_prompt_embeds, uncond_image_prompt_embeds
def set_scale(self, scale): for attn_processor in self.pipe.unet.attn_processors.values(): if isinstance(attn_processor, IPAttnProcessor): attn_processor.scale = scale
def generate( self, pil_image=None, clip_image_embeds=None, prompt=None, negative_prompt=None, scale=1.0, num_samples=4, seed=None, guidance_scale=7.5, num_inference_steps=30, neg_content_emb=None, **kwargs, ): self.set_scale(scale)
if pil_image is not None: num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image) else: num_prompts = clip_image_embeds.size(0)
if prompt is None: prompt = "best quality, high quality" if negative_prompt is None: negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
if not isinstance(prompt, List): prompt = [prompt] * num_prompts if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * num_prompts
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds( pil_image=pil_image, clip_image_embeds=clip_image_embeds, content_prompt_embeds=neg_content_emb ) bs_embed, seq_len, _ = image_prompt_embeds.shape image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1) image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
with torch.inference_mode(): prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt( prompt, device=self.device, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt_embeds = torch.cat([prompt_embeds_, image_prompt_embeds], dim=1) negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_image_prompt_embeds], dim=1)
generator = get_generator(seed, self.device)
images = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, generator=generator, **kwargs, ).images
return images
class IPAdapter_CS: def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_content_tokens=4, num_style_tokens=4, target_content_blocks=["block"], target_style_blocks=["block"], content_image_encoder_path=None, controlnet_adapter=False, controlnet_target_content_blocks=None, controlnet_target_style_blocks=None, content_model_resampler=False, style_model_resampler=False, ): self.device = device self.image_encoder_path = image_encoder_path self.ip_ckpt = ip_ckpt self.num_content_tokens = num_content_tokens self.num_style_tokens = num_style_tokens self.content_target_blocks = target_content_blocks self.style_target_blocks = target_style_blocks
self.content_model_resampler = content_model_resampler self.style_model_resampler = style_model_resampler
self.controlnet_adapter = controlnet_adapter self.controlnet_target_content_blocks = controlnet_target_content_blocks self.controlnet_target_style_blocks = controlnet_target_style_blocks
self.pipe = sd_pipe.to(self.device) self.set_ip_adapter() self.content_image_encoder_path = content_image_encoder_path
# load image encoder if content_image_encoder_path is not None: self.content_image_encoder = AutoModel.from_pretrained(content_image_encoder_path).to(self.device, dtype=torch.float16) self.content_image_processor = AutoImageProcessor.from_pretrained(content_image_encoder_path) else: self.content_image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to( self.device, dtype=torch.float16 ) self.content_image_processor = CLIPImageProcessor() # model.requires_grad_(False)
self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to( self.device, dtype=torch.float16 ) # if self.use_CSD is not None: # self.style_image_encoder = CSD_CLIP("vit_large", "default",self.use_CSD+"/ViT-L-14.pt") # model_path = self.use_CSD+"/checkpoint.pth" # checkpoint = torch.load(model_path, map_location="cpu") # state_dict = convert_state_dict(checkpoint['model_state_dict']) # self.style_image_encoder.load_state_dict(state_dict, strict=False) # # normalize = transforms.Normalize((0.48145466, 0.4578275, 0.40821073), (0.26862954, 0.26130258, 0.27577711)) # self.style_preprocess = transforms.Compose([ # transforms.Resize(size=224, interpolation=Func.InterpolationMode.BICUBIC), # transforms.CenterCrop(224), # transforms.ToTensor(), # normalize, # ])
self.clip_image_processor = CLIPImageProcessor() # image proj model self.content_image_proj_model = self.init_proj(self.num_content_tokens, content_or_style_='content', model_resampler=self.content_model_resampler) self.style_image_proj_model = self.init_proj(self.num_style_tokens, content_or_style_='style', model_resampler=self.style_model_resampler)
self.load_ip_adapter()
def init_proj(self, num_tokens, content_or_style_='content', model_resampler=False):
# print('@@@@',self.pipe.unet.config.cross_attention_dim,self.image_encoder.config.projection_dim) if content_or_style_ == 'content' and self.content_image_encoder_path is not None: image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.content_image_encoder.config.projection_dim, clip_extra_context_tokens=num_tokens, ).to(self.device, dtype=torch.float16) return image_proj_model
image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.projection_dim, clip_extra_context_tokens=num_tokens, ).to(self.device, dtype=torch.float16) return image_proj_model
def set_ip_adapter(self): unet = self.pipe.unet attn_procs = {} for name in unet.attn_processors.keys(): cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim if name.startswith("mid_block"): hidden_size = unet.config.block_out_channels[-1] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(unet.config.block_out_channels))[block_id] elif name.startswith("down_blocks"): block_id = int(name[len("down_blocks.")]) hidden_size = unet.config.block_out_channels[block_id] if cross_attention_dim is None: attn_procs[name] = AttnProcessor() else: # layername_id += 1 selected = False for block_name in self.style_target_blocks: if block_name in name: selected = True # print(name) attn_procs[name] = IP_CS_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, style_scale=1.0, style=True, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, ) for block_name in self.content_target_blocks: if block_name in name: # selected = True if selected is False: attn_procs[name] = IP_CS_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, content_scale=1.0, content=True, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, ) else: attn_procs[name].set_content_ipa(content_scale=1.0) # attn_procs[name].content=True
if selected is False: attn_procs[name] = IP_CS_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, skip=True, )
attn_procs[name].to(self.device, dtype=torch.float16) unet.set_attn_processor(attn_procs) if hasattr(self.pipe, "controlnet"): if self.controlnet_adapter is False: if isinstance(self.pipe.controlnet, MultiControlNetModel): for controlnet in self.pipe.controlnet.nets: controlnet.set_attn_processor(CNAttnProcessor( num_tokens=self.num_content_tokens + self.num_style_tokens)) else: self.pipe.controlnet.set_attn_processor(CNAttnProcessor( num_tokens=self.num_content_tokens + self.num_style_tokens))
else: controlnet_attn_procs = {} controlnet_style_target_blocks = self.controlnet_target_style_blocks controlnet_content_target_blocks = self.controlnet_target_content_blocks for name in self.pipe.controlnet.attn_processors.keys(): # print(name) cross_attention_dim = None if name.endswith( "attn1.processor") else self.pipe.controlnet.config.cross_attention_dim if name.startswith("mid_block"): hidden_size = self.pipe.controlnet.config.block_out_channels[-1] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(self.pipe.controlnet.config.block_out_channels))[block_id] elif name.startswith("down_blocks"): block_id = int(name[len("down_blocks.")]) hidden_size = self.pipe.controlnet.config.block_out_channels[block_id] if cross_attention_dim is None: # layername_id += 1 controlnet_attn_procs[name] = AttnProcessor()
else: # layername_id += 1 selected = False for block_name in controlnet_style_target_blocks: if block_name in name: selected = True # print(name) controlnet_attn_procs[name] = IP_CS_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, style_scale=1.0, style=True, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, )
for block_name in controlnet_content_target_blocks: if block_name in name: if selected is False: controlnet_attn_procs[name] = IP_CS_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, content_scale=1.0, content=True, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, )
selected = True elif selected is True: controlnet_attn_procs[name].set_content_ipa(content_scale=1.0)
# if args.content_image_encoder_type !='dinov2': # weights = { # "to_k_ip.weight": state_dict["ip_adapter"][str(layername_id) + ".to_k_ip.weight"], # "to_v_ip.weight": state_dict["ip_adapter"][str(layername_id) + ".to_v_ip.weight"], # } # attn_procs[name].load_state_dict(weights) if selected is False: controlnet_attn_procs[name] = IP_CS_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, skip=True, ) controlnet_attn_procs[name].to(self.device, dtype=torch.float16) # layer_name = name.split(".processor")[0] # # print(state_dict["ip_adapter"].keys()) # weights = { # "to_k_ip.weight": state_dict["ip_adapter"][str(layername_id) + ".to_k_ip.weight"], # "to_v_ip.weight": state_dict["ip_adapter"][str(layername_id) + ".to_v_ip.weight"], # } # attn_procs[name].load_state_dict(weights) self.pipe.controlnet.set_attn_processor(controlnet_attn_procs)
def load_ip_adapter(self): if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors": state_dict = {"content_image_proj": {}, "style_image_proj": {}, "ip_adapter": {}} with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f: for key in f.keys(): if key.startswith("content_image_proj."): state_dict["content_image_proj"][key.replace("content_image_proj.", "")] = f.get_tensor(key) elif key.startswith("style_image_proj."): state_dict["style_image_proj"][key.replace("style_image_proj.", "")] = f.get_tensor(key) elif key.startswith("ip_adapter."): state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key) else: state_dict = torch.load(self.ip_ckpt, map_location="cpu") self.content_image_proj_model.load_state_dict(state_dict["content_image_proj"]) self.style_image_proj_model.load_state_dict(state_dict["style_image_proj"])
if 'conv_in_unet_sd' in state_dict.keys(): self.pipe.unet.conv_in.load_state_dict(state_dict["conv_in_unet_sd"], strict=True) ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values()) ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False)
if self.controlnet_adapter is True: print('loading controlnet_adapter') self.pipe.controlnet.load_state_dict(state_dict["controlnet_adapter_modules"], strict=False)
@torch.inference_mode() def get_image_embeds(self, pil_image=None, clip_image_embeds=None, content_prompt_embeds=None, content_or_style_=''): # if pil_image is not None: # if isinstance(pil_image, Image.Image): # pil_image = [pil_image] # clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values # clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds # else: # clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16)
# if content_prompt_embeds is not None: # clip_image_embeds = clip_image_embeds - content_prompt_embeds
if content_or_style_ == 'content': if pil_image is not None: if isinstance(pil_image, Image.Image): pil_image = [pil_image] if self.content_image_proj_model is not None: clip_image = self.content_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.content_image_encoder( clip_image.to(self.device, dtype=torch.float16)).image_embeds else: clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds else: clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16)
image_prompt_embeds = self.content_image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.content_image_proj_model(torch.zeros_like(clip_image_embeds)) return image_prompt_embeds, uncond_image_prompt_embeds if content_or_style_ == 'style': if pil_image is not None: if self.use_CSD is not None: clip_image = self.style_preprocess(pil_image).unsqueeze(0).to(self.device, dtype=torch.float32) clip_image_embeds = self.style_image_encoder(clip_image) else: if isinstance(pil_image, Image.Image): pil_image = [pil_image] clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds
else: clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16) image_prompt_embeds = self.style_image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.style_image_proj_model(torch.zeros_like(clip_image_embeds)) return image_prompt_embeds, uncond_image_prompt_embeds
def set_scale(self, content_scale, style_scale): for attn_processor in self.pipe.unet.attn_processors.values(): if isinstance(attn_processor, IP_CS_AttnProcessor): if attn_processor.content is True: attn_processor.content_scale = content_scale
if attn_processor.style is True: attn_processor.style_scale = style_scale # print('style_scale:',style_scale) if self.controlnet_adapter is not None: for attn_processor in self.pipe.controlnet.attn_processors.values():
if isinstance(attn_processor, IP_CS_AttnProcessor): if attn_processor.content is True: attn_processor.content_scale = content_scale # print(content_scale)
if attn_processor.style is True: attn_processor.style_scale = style_scale
def generate( self, pil_content_image=None, pil_style_image=None, clip_content_image_embeds=None, clip_style_image_embeds=None, prompt=None, negative_prompt=None, content_scale=1.0, style_scale=1.0, num_samples=4, seed=None, guidance_scale=7.5, num_inference_steps=30, neg_content_emb=None, **kwargs, ): self.set_scale(content_scale, style_scale)
if pil_content_image is not None: num_prompts = 1 if isinstance(pil_content_image, Image.Image) else len(pil_content_image) else: num_prompts = clip_content_image_embeds.size(0)
if prompt is None: prompt = "best quality, high quality" if negative_prompt is None: negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
if not isinstance(prompt, List): prompt = [prompt] * num_prompts if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * num_prompts
content_image_prompt_embeds, uncond_content_image_prompt_embeds = self.get_image_embeds( pil_image=pil_content_image, clip_image_embeds=clip_content_image_embeds ) style_image_prompt_embeds, uncond_style_image_prompt_embeds = self.get_image_embeds( pil_image=pil_style_image, clip_image_embeds=clip_style_image_embeds )
bs_embed, seq_len, _ = content_image_prompt_embeds.shape content_image_prompt_embeds = content_image_prompt_embeds.repeat(1, num_samples, 1) content_image_prompt_embeds = content_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1) uncond_content_image_prompt_embeds = uncond_content_image_prompt_embeds.repeat(1, num_samples, 1) uncond_content_image_prompt_embeds = uncond_content_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
bs_style_embed, seq_style_len, _ = content_image_prompt_embeds.shape style_image_prompt_embeds = style_image_prompt_embeds.repeat(1, num_samples, 1) style_image_prompt_embeds = style_image_prompt_embeds.view(bs_embed * num_samples, seq_style_len, -1) uncond_style_image_prompt_embeds = uncond_style_image_prompt_embeds.repeat(1, num_samples, 1) uncond_style_image_prompt_embeds = uncond_style_image_prompt_embeds.view(bs_embed * num_samples, seq_style_len, -1)
with torch.inference_mode(): prompt_embeds_, negative_prompt_embeds_ = self.pipe.encode_prompt( prompt, device=self.device, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt_embeds = torch.cat([prompt_embeds_, content_image_prompt_embeds, style_image_prompt_embeds], dim=1) negative_prompt_embeds = torch.cat([negative_prompt_embeds_, uncond_content_image_prompt_embeds, uncond_style_image_prompt_embeds], dim=1)
generator = get_generator(seed, self.device)
images = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps, generator=generator, **kwargs, ).images
return images
class IPAdapterXL_CS(IPAdapter_CS): """SDXL"""
def generate( self, pil_content_image, pil_style_image, prompt=None, negative_prompt=None, content_scale=1.0, style_scale=1.0, num_samples=4, seed=None, content_image_embeds=None, style_image_embeds=None, num_inference_steps=30, neg_content_emb=None, neg_content_prompt=None, neg_content_scale=1.0,
**kwargs, ): self.set_scale(content_scale, style_scale)
num_prompts = 1 if isinstance(pil_content_image, Image.Image) else len(pil_content_image)
if prompt is None: prompt = "best quality, high quality" if negative_prompt is None: negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
if not isinstance(prompt, List): prompt = [prompt] * num_prompts if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * num_prompts
content_image_prompt_embeds, uncond_content_image_prompt_embeds = self.get_image_embeds(pil_content_image, content_image_embeds, content_or_style_='content')
style_image_prompt_embeds, uncond_style_image_prompt_embeds = self.get_image_embeds(pil_style_image, style_image_embeds, content_or_style_='style')
bs_embed, seq_len, _ = content_image_prompt_embeds.shape
content_image_prompt_embeds = content_image_prompt_embeds.repeat(1, num_samples, 1) content_image_prompt_embeds = content_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
uncond_content_image_prompt_embeds = uncond_content_image_prompt_embeds.repeat(1, num_samples, 1) uncond_content_image_prompt_embeds = uncond_content_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1) bs_style_embed, seq_style_len, _ = style_image_prompt_embeds.shape style_image_prompt_embeds = style_image_prompt_embeds.repeat(1, num_samples, 1) style_image_prompt_embeds = style_image_prompt_embeds.view(bs_embed * num_samples, seq_style_len, -1) uncond_style_image_prompt_embeds = uncond_style_image_prompt_embeds.repeat(1, num_samples, 1) uncond_style_image_prompt_embeds = uncond_style_image_prompt_embeds.view(bs_embed * num_samples, seq_style_len, -1)
with torch.inference_mode(): ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = self.pipe.encode_prompt( prompt, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt_embeds = torch.cat([prompt_embeds, content_image_prompt_embeds, style_image_prompt_embeds], dim=1) negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_content_image_prompt_embeds, uncond_style_image_prompt_embeds], dim=1)
# self.generator = get_generator(seed, self.device) # latents = torch.randn((1, 4, 128, 128), generator=self.generator, device="cuda", dtype=torch.float16).to("cuda") # latents = latents.repeat(2, 1, 1, 1) # print(latents.shape) images = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, num_inference_steps=num_inference_steps, # generator=self.generator, **kwargs, ).images return images
class CSGO(IPAdapterXL_CS): """SDXL"""
def init_proj(self, num_tokens, content_or_style_='content', model_resampler=False): if content_or_style_ == 'content': if model_resampler: image_proj_model = Resampler( dim=self.pipe.unet.config.cross_attention_dim, depth=4, dim_head=64, heads=12, num_queries=num_tokens, embedding_dim=self.content_image_encoder.config.hidden_size, output_dim=self.pipe.unet.config.cross_attention_dim, ff_mult=4, ).to(self.device, dtype=torch.float16) else: image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.projection_dim, clip_extra_context_tokens=num_tokens, ).to(self.device, dtype=torch.float16) if content_or_style_ == 'style': if model_resampler: image_proj_model = Resampler( dim=self.pipe.unet.config.cross_attention_dim, depth=4, dim_head=64, heads=12, num_queries=num_tokens, embedding_dim=self.content_image_encoder.config.hidden_size, output_dim=self.pipe.unet.config.cross_attention_dim, ff_mult=4, ).to(self.device, dtype=torch.float16) else: image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.projection_dim, clip_extra_context_tokens=num_tokens, ).to(self.device, dtype=torch.float16) return image_proj_model
@torch.inference_mode() def get_image_embeds(self, pil_image=None, clip_image_embeds=None, content_or_style_=''): if isinstance(pil_image, Image.Image): pil_image = [pil_image] if content_or_style_ == 'style': if self.style_model_resampler: clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16), output_hidden_states=True).hidden_states[-2] image_prompt_embeds = self.style_image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.style_image_proj_model(torch.zeros_like(clip_image_embeds)) else:
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds image_prompt_embeds = self.style_image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.style_image_proj_model(torch.zeros_like(clip_image_embeds)) return image_prompt_embeds, uncond_image_prompt_embeds
else:
if self.content_image_encoder_path is not None: clip_image = self.content_image_processor(images=pil_image, return_tensors="pt").pixel_values outputs = self.content_image_encoder(clip_image.to(self.device, dtype=torch.float16), output_hidden_states=True) clip_image_embeds = outputs.last_hidden_state image_prompt_embeds = self.content_image_proj_model(clip_image_embeds)
# uncond_clip_image_embeds = self.image_encoder( # torch.zeros_like(clip_image), output_hidden_states=True # ).last_hidden_state uncond_image_prompt_embeds = self.content_image_proj_model(torch.zeros_like(clip_image_embeds)) return image_prompt_embeds, uncond_image_prompt_embeds
else: if self.content_model_resampler:
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values
clip_image = clip_image.to(self.device, dtype=torch.float16) clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2] # clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16) image_prompt_embeds = self.content_image_proj_model(clip_image_embeds) # uncond_clip_image_embeds = self.image_encoder( # torch.zeros_like(clip_image), output_hidden_states=True # ).hidden_states[-2] uncond_image_prompt_embeds = self.content_image_proj_model(torch.zeros_like(clip_image_embeds)) else: clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds image_prompt_embeds = self.content_image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.content_image_proj_model(torch.zeros_like(clip_image_embeds))
return image_prompt_embeds, uncond_image_prompt_embeds
# # clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values # clip_image = clip_image.to(self.device, dtype=torch.float16) # clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2] # image_prompt_embeds = self.content_image_proj_model(clip_image_embeds) # uncond_clip_image_embeds = self.image_encoder( # torch.zeros_like(clip_image), output_hidden_states=True # ).hidden_states[-2] # uncond_image_prompt_embeds = self.content_image_proj_model(uncond_clip_image_embeds) # return image_prompt_embeds, uncond_image_prompt_embeds
class StyleStudio_Adapter(CSGO): def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_style_tokens=4, target_style_blocks=["block"], controlnet_adapter=False, controlnet_target_content_blocks=None, controlnet_target_style_blocks=None, style_model_resampler=False, fuAttn=False, fuSAttn=False, fuIPAttn=False, fuScale=0, adainIP=False, end_fusion=0, save_attn_map=False, ): self.fuAttn = fuAttn self.fuSAttn = fuSAttn self.fuIPAttn = fuIPAttn self.adainIP = adainIP self.fuScale = fuScale # if self.adainIP: # print("use the cross modal adain") if self.fuSAttn: print(f"hijack Self AttnMap in {end_fusion} steps", "fuScale is: ", fuScale) if self.fuAttn: print(f"hijack Cross AttnMap in {end_fusion} steps", "fuScale is: ", fuScale) if self.fuIPAttn: print(f"hijack IP AttnMap in {end_fusion} steps", "fuScale is: ", fuScale) self.end_fusion = end_fusion self.save_attn_map = save_attn_map
self.device = device self.image_encoder_path = image_encoder_path self.ip_ckpt = ip_ckpt self.num_style_tokens = num_style_tokens self.style_target_blocks = target_style_blocks
self.style_model_resampler = style_model_resampler
self.controlnet_adapter = controlnet_adapter self.controlnet_target_content_blocks = controlnet_target_content_blocks self.controlnet_target_style_blocks = controlnet_target_style_blocks
self.pipe = sd_pipe.to(self.device) self.set_ip_adapter()
# load image encoder # model.requires_grad_(False)
self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to( self.device, dtype=torch.float16 )
self.clip_image_processor = CLIPImageProcessor() # image proj model self.style_image_proj_model = self.init_proj(self.num_style_tokens, content_or_style_='style', model_resampler=self.style_model_resampler) self.load_ip_adapter()
def set_ip_adapter(self): unet = self.pipe.unet attn_procs = {} for name in unet.attn_processors.keys(): cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim if name.startswith("mid_block"): hidden_size = unet.config.block_out_channels[-1] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(unet.config.block_out_channels))[block_id] elif name.startswith("down_blocks"): block_id = int(name[len("down_blocks.")]) hidden_size = unet.config.block_out_channels[block_id] if cross_attention_dim is None: attn_procs[name] = AttnProcessor_hijack( fuSAttn=self.fuSAttn, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name) else: # layername_id += 1 selected = False for block_name in self.style_target_blocks: if block_name in name: selected = True # print(name) attn_procs[name] = IP_FuAd_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, style_scale=1.0, style=True, num_style_tokens=self.num_style_tokens, fuAttn=self.fuAttn, fuIPAttn=self.fuIPAttn, adainIP=self.adainIP, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name, ) if selected is False: attn_procs[name] = IP_FuAd_AttnProcessor( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_style_tokens=self.num_style_tokens, skip=True, fuAttn=self.fuAttn,
fuIPAttn=self.fuIPAttn, adainIP=self.adainIP, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name, )
attn_procs[name].to(self.device, dtype=torch.float16) unet.set_attn_processor(attn_procs) if hasattr(self.pipe, "controlnet"): if self.controlnet_adapter is False: if isinstance(self.pipe.controlnet, MultiControlNetModel): for controlnet in self.pipe.controlnet.nets: controlnet.set_attn_processor(CNAttnProcessor( num_tokens=self.num_content_tokens + self.num_style_tokens)) else: self.pipe.controlnet.set_attn_processor(CNAttnProcessor( num_tokens=self.num_content_tokens + self.num_style_tokens))
def load_ip_adapter(self): if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors": state_dict = {"content_image_proj": {}, "style_image_proj": {}, "ip_adapter": {}} with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f: for key in f.keys(): if key.startswith("content_image_proj."): state_dict["content_image_proj"][key.replace("content_image_proj.", "")] = f.get_tensor(key) elif key.startswith("style_image_proj."): state_dict["style_image_proj"][key.replace("style_image_proj.", "")] = f.get_tensor(key) elif key.startswith("ip_adapter."): state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key) else: state_dict = torch.load(self.ip_ckpt, map_location="cpu") self.style_image_proj_model.load_state_dict(state_dict["style_image_proj"])
if 'conv_in_unet_sd' in state_dict.keys(): self.pipe.unet.conv_in.load_state_dict(state_dict["conv_in_unet_sd"], strict=True) ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values()) ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False) def set_scale(self, style_scale): for attn_processor in self.pipe.unet.attn_processors.values(): if isinstance(attn_processor, IP_FuAd_AttnProcessor): if attn_processor.style is True: attn_processor.style_scale = style_scale # print('style_scale:',style_scale) def init_proj(self, num_tokens, content_or_style_='content', model_resampler=False): if content_or_style_ == 'content': if model_resampler: image_proj_model = Resampler( dim=self.pipe.unet.config.cross_attention_dim, depth=4, dim_head=64, heads=12, num_queries=num_tokens, embedding_dim=self.image_encoder.config.hidden_size, output_dim=self.pipe.unet.config.cross_attention_dim, ff_mult=4, ).to(self.device, dtype=torch.float16) else: image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.projection_dim, clip_extra_context_tokens=num_tokens, ).to(self.device, dtype=torch.float16) if content_or_style_ == 'style': if model_resampler: image_proj_model = Resampler( dim=self.pipe.unet.config.cross_attention_dim, depth=4, dim_head=64, heads=12, num_queries=num_tokens, embedding_dim=self.image_encoder.config.hidden_size, output_dim=self.pipe.unet.config.cross_attention_dim, ff_mult=4, ).to(self.device, dtype=torch.float16) else: image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.projection_dim, clip_extra_context_tokens=num_tokens, ).to(self.device, dtype=torch.float16) return image_proj_model
@torch.inference_mode() def get_image_embeds(self, pil_image=None, clip_image_embeds=None): if isinstance(pil_image, Image.Image): pil_image = [pil_image] if self.style_model_resampler: clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16), output_hidden_states=True).hidden_states[-2] image_prompt_embeds = self.style_image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.style_image_proj_model(torch.zeros_like(clip_image_embeds)) else:
clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds image_prompt_embeds = self.style_image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.style_image_proj_model(torch.zeros_like(clip_image_embeds)) return image_prompt_embeds, uncond_image_prompt_embeds @torch.inference_mode() def get_neg_image_embeds(self, pil_image=None, clip_image_embeds=None): if isinstance(pil_image, Image.Image): pil_image = [pil_image]
if self.style_model_resampler: clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16), output_hidden_states=True).hidden_states[-2] neg_image_prompt_embeds = self.style_image_proj_model(clip_image_embeds) else: clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds neg_image_prompt_embeds = self.style_image_proj_model(clip_image_embeds) return neg_image_prompt_embeds def set_endFusion(self, end_T): for attn_processor in self.pipe.unet.attn_processors.values(): if isinstance(attn_processor, AttnProcessor_hijack): attn_processor.end_fusion = end_T def set_SAttn(self, use_SAttn): for attn_processor in self.pipe.unet.attn_processors.values(): if isinstance(attn_processor, AttnProcessor_hijack): attn_processor.fuSAttn = use_SAttn def set_adain(self, use_CMA): for attn_processor in self.pipe.unet.attn_processors.values(): if isinstance(attn_processor, IP_FuAd_AttnProcessor): attn_processor.adainIP = use_CMA
def generate( self, pil_style_image,
neg_pil_style_image=None, prompt=None, negative_prompt=None, num_samples=2, style_image_embeds=None, num_inference_steps=30, end_fusion=20, cross_modal_adain=True, use_SAttn=True, **kwargs, ): self.set_endFusion(end_T = end_fusion) self.set_adain(use_CMA=cross_modal_adain) self.set_SAttn(use_SAttn=use_SAttn) # self.set_scale(style_scale=style_scale) num_prompts = 1 if isinstance(pil_style_image, Image.Image) else len(pil_style_image)
if prompt is None: prompt = "best quality, high quality" if negative_prompt is None: negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
if not isinstance(prompt, List): prompt = [prompt] * num_prompts if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * num_prompts
style_image_prompt_embeds, uncond_style_image_prompt_embeds = self.get_image_embeds( pil_style_image, style_image_embeds, )
if neg_pil_style_image is not None: print("using neg style image") neg_style_image_prompt_embeds = self.get_neg_image_embeds(neg_pil_style_image, style_image_embeds,) cos_sim_neg = F.cosine_similarity(style_image_prompt_embeds, neg_style_image_prompt_embeds.squeeze(0).unsqueeze(1), dim=-1) cos_sim_uncond = F.cosine_similarity(style_image_prompt_embeds, uncond_style_image_prompt_embeds.squeeze(0).unsqueeze(1), dim=-1) print(f"neg cos sim is: {cos_sim_neg.diagonal()}") print(f"uncond cos sim is: {cos_sim_uncond.diagonal()}") uncond_style_image_prompt_embeds = neg_style_image_prompt_embeds
bs_embed, seq_style_len, _ = style_image_prompt_embeds.shape style_image_prompt_embeds = style_image_prompt_embeds.repeat(1, num_samples, 1) style_image_prompt_embeds = style_image_prompt_embeds.view(bs_embed * num_samples, seq_style_len, -1) uncond_style_image_prompt_embeds = uncond_style_image_prompt_embeds.repeat(1, num_samples, 1) uncond_style_image_prompt_embeds = uncond_style_image_prompt_embeds.view(bs_embed * num_samples, seq_style_len, -1)
with torch.inference_mode(): ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = self.pipe.encode_prompt( prompt, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt_embeds = torch.cat([prompt_embeds, style_image_prompt_embeds], dim=1) negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_style_image_prompt_embeds], dim=1)
images = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, num_inference_steps=num_inference_steps, **kwargs, ).images return images
# StyleStudio_Adapter experiment codeclass StyleStudio_Adapter_exp(StyleStudio_Adapter): def set_ip_adapter(self): unet = self.pipe.unet attn_procs = {} for name in unet.attn_processors.keys(): cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim if name.startswith("mid_block"): hidden_size = unet.config.block_out_channels[-1] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(unet.config.block_out_channels))[block_id] elif name.startswith("down_blocks"): block_id = int(name[len("down_blocks.")]) hidden_size = unet.config.block_out_channels[block_id] if cross_attention_dim is None: attn_procs[name] = AttnProcessor_exp( fuSAttn=self.fuSAttn, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name) else: # layername_id += 1 selected = False for block_name in self.style_target_blocks: if block_name in name: selected = True # print(name) # 将所有的StyleBlock中的都改为FuAdAttn attn_procs[name] = IP_FuAd_AttnProcessor_exp( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, style_scale=1.0, style=True, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, fuAttn=self.fuAttn, fuIPAttn=self.fuIPAttn, adainIP=self.adainIP, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name, save_attn_map=self.save_attn_map, ) # 没有CSGO中关于Content Control的需求 因此就将这个处理Content tokens Cross Attention 删除 # 并且这里应该是CSGO代码中 有问题的部分 不论如何这里都会被之后的重置 # 并且在CSGO的设计里Content Block和Style Block是没有子集的 # selected False表明不是Style Block 关键是 Skip = True if selected is False: attn_procs[name] = IP_FuAd_AttnProcessor_exp( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, num_content_tokens=self.num_content_tokens, num_style_tokens=self.num_style_tokens, skip=True, fuAttn=self.fuAttn, fuIPAttn=self.fuIPAttn, adainIP=self.adainIP, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name, save_attn_map=self.save_attn_map, ) # attn_procs[name] = IP_FuAd_AttnProcessor_exp( # hidden_size=hidden_size, # cross_attention_dim=cross_attention_dim, # num_content_tokens=self.num_content_tokens, # num_style_tokens=self.num_style_tokens, # skip=True, # fuAttn=self.fuAttn, # fuIPAttn=self.fuIPAttn, # )
attn_procs[name].to(self.device, dtype=torch.float16) unet.set_attn_processor(attn_procs) if hasattr(self.pipe, "controlnet"): if self.controlnet_adapter is False: if isinstance(self.pipe.controlnet, MultiControlNetModel): for controlnet in self.pipe.controlnet.nets: controlnet.set_attn_processor(CNAttnProcessor( num_tokens=self.num_content_tokens + self.num_style_tokens)) else: self.pipe.controlnet.set_attn_processor(CNAttnProcessor( num_tokens=self.num_content_tokens + self.num_style_tokens)) # 因为我们的代码中没有controlnet需要将Style 注入 这并不是一个I2I的任务 # 因此我们将原本CSGO中和ControlNet中注入Style的部分给删除了
class IPAdapterXL(IPAdapter): """SDXL"""
def generate( self, pil_image, prompt=None, negative_prompt=None, scale=1.0, num_samples=4, seed=None, num_inference_steps=30, neg_content_emb=None, neg_content_prompt=None, neg_content_scale=1.0, **kwargs, ): self.set_scale(scale)
num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
if prompt is None: prompt = "best quality, high quality" if negative_prompt is None: negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
if not isinstance(prompt, List): prompt = [prompt] * num_prompts if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * num_prompts
if neg_content_emb is None: if neg_content_prompt is not None: with torch.inference_mode(): ( prompt_embeds_, # torch.Size([1, 77, 2048]) negative_prompt_embeds_, pooled_prompt_embeds_, # torch.Size([1, 1280]) negative_pooled_prompt_embeds_, ) = self.pipe.encode_prompt( neg_content_prompt, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) pooled_prompt_embeds_ *= neg_content_scale else: pooled_prompt_embeds_ = neg_content_emb else: pooled_prompt_embeds_ = None
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image, content_prompt_embeds=pooled_prompt_embeds_) bs_embed, seq_len, _ = image_prompt_embeds.shape image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1) image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
with torch.inference_mode(): ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = self.pipe.encode_prompt( prompt, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1) negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
self.generator = get_generator(seed, self.device)
images = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, num_inference_steps=num_inference_steps, generator=self.generator, **kwargs, ).images
return images
class IPAdapterXL_cross_modal(IPAdapterXL): def __init__(self, sd_pipe, image_encoder_path, ip_ckpt, device, num_tokens=4, target_blocks=["block"], fuAttn=False, fuSAttn=False, fuIPAttn=False, fuScale=0, adainIP=False, end_fusion=0, save_attn_map=False,): self.fuAttn = fuAttn self.fuSAttn = fuSAttn self.fuIPAttn = fuIPAttn self.adainIP = adainIP self.fuScale = fuScale if self.fuSAttn: print(f"hijack Self AttnMap in {end_fusion} steps", "fuScale is: ", fuScale) if self.fuAttn: print(f"hijack Cross AttnMap in {end_fusion} steps", "fuScale is: ", fuScale) if self.fuIPAttn: print(f"hijack IP AttnMap in {end_fusion} steps", "fuScale is: ", fuScale) self.end_fusion = end_fusion self.save_attn_map = save_attn_map
self.device = device self.image_encoder_path = image_encoder_path self.ip_ckpt = ip_ckpt self.num_tokens = num_tokens self.target_blocks = target_blocks
self.pipe = sd_pipe.to(self.device) self.set_ip_adapter()
# load image encoder self.image_encoder = CLIPVisionModelWithProjection.from_pretrained(self.image_encoder_path).to( self.device, dtype=torch.float16 ) self.clip_image_processor = CLIPImageProcessor() # image proj model self.image_proj_model = self.init_proj()
self.load_ip_adapter()
def init_proj(self): image_proj_model = ImageProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.projection_dim, clip_extra_context_tokens=self.num_tokens, ).to(self.device, dtype=torch.float16) return image_proj_model def set_ip_adapter(self): unet = self.pipe.unet attn_procs = {} for name in unet.attn_processors.keys(): cross_attention_dim = None if name.endswith("attn1.processor") else unet.config.cross_attention_dim if name.startswith("mid_block"): hidden_size = unet.config.block_out_channels[-1] elif name.startswith("up_blocks"): block_id = int(name[len("up_blocks.")]) hidden_size = list(reversed(unet.config.block_out_channels))[block_id] elif name.startswith("down_blocks"): block_id = int(name[len("down_blocks.")]) hidden_size = unet.config.block_out_channels[block_id] if cross_attention_dim is None: attn_procs[name] = AttnProcessor_hijack( fuSAttn=self.fuSAttn, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name) # Self Attention else: # Cross Attention selected = False for block_name in self.target_blocks: if block_name in name: selected = True break if selected: attn_procs[name] = IPAttnProcessor_cross_modal( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, num_tokens=self.num_tokens, fuAttn=self.fuAttn, fuIPAttn=self.fuIPAttn, adainIP=self.adainIP, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name, ).to(self.device, dtype=torch.float16) else: attn_procs[name] = IPAttnProcessor_cross_modal( hidden_size=hidden_size, cross_attention_dim=cross_attention_dim, scale=1.0, num_tokens=self.num_tokens, skip=True, fuAttn=self.fuAttn, fuIPAttn=self.fuIPAttn, adainIP=self.adainIP, fuScale=self.fuScale, end_fusion=self.end_fusion, attn_name=name, ).to(self.device, dtype=torch.float16) unet.set_attn_processor(attn_procs) if hasattr(self.pipe, "controlnet"): if isinstance(self.pipe.controlnet, MultiControlNetModel): for controlnet in self.pipe.controlnet.nets: controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens)) else: self.pipe.controlnet.set_attn_processor(CNAttnProcessor(num_tokens=self.num_tokens))
def load_ip_adapter(self): if os.path.splitext(self.ip_ckpt)[-1] == ".safetensors": state_dict = {"image_proj": {}, "ip_adapter": {}} with safe_open(self.ip_ckpt, framework="pt", device="cpu") as f: for key in f.keys(): if key.startswith("image_proj."): state_dict["image_proj"][key.replace("image_proj.", "")] = f.get_tensor(key) elif key.startswith("ip_adapter."): state_dict["ip_adapter"][key.replace("ip_adapter.", "")] = f.get_tensor(key) else: state_dict = torch.load(self.ip_ckpt, map_location="cpu") self.image_proj_model.load_state_dict(state_dict["image_proj"]) ip_layers = torch.nn.ModuleList(self.pipe.unet.attn_processors.values()) ip_layers.load_state_dict(state_dict["ip_adapter"], strict=False)
@torch.inference_mode() def get_image_embeds(self, pil_image=None, clip_image_embeds=None, content_prompt_embeds=None): if pil_image is not None: if isinstance(pil_image, Image.Image): pil_image = [pil_image] clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds else: clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16) if content_prompt_embeds is not None: clip_image_embeds = clip_image_embeds - content_prompt_embeds
image_prompt_embeds = self.image_proj_model(clip_image_embeds) uncond_image_prompt_embeds = self.image_proj_model(torch.zeros_like(clip_image_embeds)) return image_prompt_embeds, uncond_image_prompt_embeds
def set_scale(self, scale): for attn_processor in self.pipe.unet.attn_processors.values(): if isinstance(attn_processor, IPAttnProcessor_cross_modal): attn_processor.scale = scale
@torch.inference_mode() def get_neg_image_embeds(self, pil_image=None, clip_image_embeds=None, content_prompt_embeds=None): if pil_image is not None: if isinstance(pil_image, Image.Image): pil_image = [pil_image] clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image_embeds = self.image_encoder(clip_image.to(self.device, dtype=torch.float16)).image_embeds else: clip_image_embeds = clip_image_embeds.to(self.device, dtype=torch.float16) if content_prompt_embeds is not None: clip_image_embeds = clip_image_embeds - content_prompt_embeds
neg_image_prompt_embeds = self.image_proj_model(clip_image_embeds) return neg_image_prompt_embeds def generate( self, pil_image, neg_pil_image=None, prompt=None, negative_prompt=None, scale=1.0, num_samples=4, seed=None, num_inference_steps=30, neg_content_emb=None, neg_content_prompt=None, neg_content_scale=1.0, **kwargs, ): self.set_scale(scale)
num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
if prompt is None: prompt = "best quality, high quality" if negative_prompt is None: negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
if not isinstance(prompt, List): prompt = [prompt] * num_prompts if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * num_prompts if neg_content_emb is None: if neg_content_prompt is not None: with torch.inference_mode(): ( prompt_embeds_, # torch.Size([1, 77, 2048]) negative_prompt_embeds_, pooled_prompt_embeds_, # torch.Size([1, 1280]) negative_pooled_prompt_embeds_, ) = self.pipe.encode_prompt( neg_content_prompt, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) pooled_prompt_embeds_ *= neg_content_scale else: pooled_prompt_embeds_ = neg_content_emb else: pooled_prompt_embeds_ = None
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image, content_prompt_embeds=pooled_prompt_embeds_) if neg_pil_image is not None: neg_image_prompt_embeds = self.get_neg_image_embeds(neg_pil_image) cos_sim_neg = F.cosine_similarity(image_prompt_embeds, neg_image_prompt_embeds.squeeze(0).unsqueeze(1), dim=-1) cos_sim_uncond = F.cosine_similarity(image_prompt_embeds, uncond_image_prompt_embeds.squeeze(0).unsqueeze(1), dim=-1) print(f"neg cos sim is: {cos_sim_neg.diagonal()}") print(f"uncond cos sim is: {cos_sim_uncond.diagonal()}") uncond_image_prompt_embeds = neg_image_prompt_embeds bs_embed, seq_len, _ = image_prompt_embeds.shape image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1) image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
with torch.inference_mode(): ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = self.pipe.encode_prompt( prompt, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1) negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
# self.generator = get_generator(seed, self.device) images = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, num_inference_steps=num_inference_steps, # generator=self.generator, **kwargs, ).images
return images
class IPAdapterPlus(IPAdapter): """IP-Adapter with fine-grained features"""
def init_proj(self): image_proj_model = Resampler( dim=self.pipe.unet.config.cross_attention_dim, depth=4, dim_head=64, heads=12, num_queries=self.num_tokens, embedding_dim=self.image_encoder.config.hidden_size, output_dim=self.pipe.unet.config.cross_attention_dim, ff_mult=4, ).to(self.device, dtype=torch.float16) return image_proj_model
@torch.inference_mode() def get_image_embeds(self, pil_image=None, clip_image_embeds=None): if isinstance(pil_image, Image.Image): pil_image = [pil_image] clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image = clip_image.to(self.device, dtype=torch.float16) clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2] image_prompt_embeds = self.image_proj_model(clip_image_embeds) uncond_clip_image_embeds = self.image_encoder( torch.zeros_like(clip_image), output_hidden_states=True ).hidden_states[-2] uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds) return image_prompt_embeds, uncond_image_prompt_embeds
class IPAdapterFull(IPAdapterPlus): """IP-Adapter with full features"""
def init_proj(self): image_proj_model = MLPProjModel( cross_attention_dim=self.pipe.unet.config.cross_attention_dim, clip_embeddings_dim=self.image_encoder.config.hidden_size, ).to(self.device, dtype=torch.float16) return image_proj_model
class IPAdapterPlusXL(IPAdapter): """SDXL"""
def init_proj(self): image_proj_model = Resampler( dim=1280, depth=4, dim_head=64, heads=20, num_queries=self.num_tokens, embedding_dim=self.image_encoder.config.hidden_size, output_dim=self.pipe.unet.config.cross_attention_dim, ff_mult=4, ).to(self.device, dtype=torch.float16) return image_proj_model
@torch.inference_mode() def get_image_embeds(self, pil_image): if isinstance(pil_image, Image.Image): pil_image = [pil_image] clip_image = self.clip_image_processor(images=pil_image, return_tensors="pt").pixel_values clip_image = clip_image.to(self.device, dtype=torch.float16) clip_image_embeds = self.image_encoder(clip_image, output_hidden_states=True).hidden_states[-2] image_prompt_embeds = self.image_proj_model(clip_image_embeds) uncond_clip_image_embeds = self.image_encoder( torch.zeros_like(clip_image), output_hidden_states=True ).hidden_states[-2] uncond_image_prompt_embeds = self.image_proj_model(uncond_clip_image_embeds) return image_prompt_embeds, uncond_image_prompt_embeds
def generate( self, pil_image, prompt=None, negative_prompt=None, scale=1.0, num_samples=4, seed=None, num_inference_steps=30, **kwargs, ): self.set_scale(scale)
num_prompts = 1 if isinstance(pil_image, Image.Image) else len(pil_image)
if prompt is None: prompt = "best quality, high quality" if negative_prompt is None: negative_prompt = "monochrome, lowres, bad anatomy, worst quality, low quality"
if not isinstance(prompt, List): prompt = [prompt] * num_prompts if not isinstance(negative_prompt, List): negative_prompt = [negative_prompt] * num_prompts
image_prompt_embeds, uncond_image_prompt_embeds = self.get_image_embeds(pil_image) bs_embed, seq_len, _ = image_prompt_embeds.shape image_prompt_embeds = image_prompt_embeds.repeat(1, num_samples, 1) image_prompt_embeds = image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.repeat(1, num_samples, 1) uncond_image_prompt_embeds = uncond_image_prompt_embeds.view(bs_embed * num_samples, seq_len, -1)
with torch.inference_mode(): ( prompt_embeds, negative_prompt_embeds, pooled_prompt_embeds, negative_pooled_prompt_embeds, ) = self.pipe.encode_prompt( prompt, num_images_per_prompt=num_samples, do_classifier_free_guidance=True, negative_prompt=negative_prompt, ) prompt_embeds = torch.cat([prompt_embeds, image_prompt_embeds], dim=1) negative_prompt_embeds = torch.cat([negative_prompt_embeds, uncond_image_prompt_embeds], dim=1)
generator = get_generator(seed, self.device)
images = self.pipe( prompt_embeds=prompt_embeds, negative_prompt_embeds=negative_prompt_embeds, pooled_prompt_embeds=pooled_prompt_embeds, negative_pooled_prompt_embeds=negative_pooled_prompt_embeds, num_inference_steps=num_inference_steps, generator=generator, **kwargs, ).images
return images123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158# modified from https://github.com/mlfoundations/open_flamingo/blob/main/open_flamingo/src/helpers.py# and https://github.com/lucidrains/imagen-pytorch/blob/main/imagen_pytorch/imagen_pytorch.py
import math
import torchimport torch.nn as nnfrom einops import rearrangefrom einops.layers.torch import Rearrange
# FFNdef FeedForward(dim, mult=4): inner_dim = int(dim * mult) return nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, inner_dim, bias=False), nn.GELU(), nn.Linear(inner_dim, dim, bias=False), )
def reshape_tensor(x, heads): bs, length, width = x.shape # (bs, length, width) --> (bs, length, n_heads, dim_per_head) x = x.view(bs, length, heads, -1) # (bs, length, n_heads, dim_per_head) --> (bs, n_heads, length, dim_per_head) x = x.transpose(1, 2) # (bs, n_heads, length, dim_per_head) --> (bs*n_heads, length, dim_per_head) x = x.reshape(bs, heads, length, -1) return x
class PerceiverAttention(nn.Module): def __init__(self, *, dim, dim_head=64, heads=8): super().__init__() self.scale = dim_head**-0.5 self.dim_head = dim_head self.heads = heads inner_dim = dim_head * heads
self.norm1 = nn.LayerNorm(dim) self.norm2 = nn.LayerNorm(dim)
self.to_q = nn.Linear(dim, inner_dim, bias=False) self.to_kv = nn.Linear(dim, inner_dim * 2, bias=False) self.to_out = nn.Linear(inner_dim, dim, bias=False)
def forward(self, x, latents): """ Args: x (torch.Tensor): image features shape (b, n1, D) latent (torch.Tensor): latent features shape (b, n2, D) """ x = self.norm1(x) latents = self.norm2(latents)
b, l, _ = latents.shape
q = self.to_q(latents) kv_input = torch.cat((x, latents), dim=-2) k, v = self.to_kv(kv_input).chunk(2, dim=-1)
q = reshape_tensor(q, self.heads) k = reshape_tensor(k, self.heads) v = reshape_tensor(v, self.heads)
# attention scale = 1 / math.sqrt(math.sqrt(self.dim_head)) weight = (q * scale) @ (k * scale).transpose(-2, -1) # More stable with f16 than dividing afterwards weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype) out = weight @ v
out = out.permute(0, 2, 1, 3).reshape(b, l, -1)
return self.to_out(out)
class Resampler(nn.Module): def __init__( self, dim=1024, depth=8, dim_head=64, heads=16, num_queries=8, embedding_dim=768, output_dim=1024, ff_mult=4, max_seq_len: int = 257, # CLIP tokens + CLS token apply_pos_emb: bool = False, num_latents_mean_pooled: int = 0, # number of latents derived from mean pooled representation of the sequence ): super().__init__() self.pos_emb = nn.Embedding(max_seq_len, embedding_dim) if apply_pos_emb else None
self.latents = nn.Parameter(torch.randn(1, num_queries, dim) / dim**0.5)
self.proj_in = nn.Linear(embedding_dim, dim)
self.proj_out = nn.Linear(dim, output_dim) self.norm_out = nn.LayerNorm(output_dim)
self.to_latents_from_mean_pooled_seq = ( nn.Sequential( nn.LayerNorm(dim), nn.Linear(dim, dim * num_latents_mean_pooled), Rearrange("b (n d) -> b n d", n=num_latents_mean_pooled), ) if num_latents_mean_pooled > 0 else None )
self.layers = nn.ModuleList([]) for _ in range(depth): self.layers.append( nn.ModuleList( [ PerceiverAttention(dim=dim, dim_head=dim_head, heads=heads), FeedForward(dim=dim, mult=ff_mult), ] ) )
def forward(self, x): if self.pos_emb is not None: n, device = x.shape[1], x.device pos_emb = self.pos_emb(torch.arange(n, device=device)) x = x + pos_emb
latents = self.latents.repeat(x.size(0), 1, 1)
x = self.proj_in(x)
if self.to_latents_from_mean_pooled_seq: meanpooled_seq = masked_mean(x, dim=1, mask=torch.ones(x.shape[:2], device=x.device, dtype=torch.bool)) meanpooled_latents = self.to_latents_from_mean_pooled_seq(meanpooled_seq) latents = torch.cat((meanpooled_latents, latents), dim=-2)
for attn, ff in self.layers: latents = attn(x, latents) + latents latents = ff(latents) + latents
latents = self.proj_out(latents) return self.norm_out(latents)
def masked_mean(t, *, dim, mask=None): if mask is None: return t.mean(dim=dim)
denom = mask.sum(dim=dim, keepdim=True) mask = rearrange(mask, "b n -> b n 1") masked_t = t.masked_fill(~mask, 0.0)
return masked_t.sum(dim=dim) / denom.clamp(min=1e-5)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142import torchimport torch.nn.functional as Fimport numpy as npfrom PIL import Image
BLOCKS = { 'content': ['down_blocks'], 'style': ["up_blocks"],
}
controlnet_BLOCKS = { 'content': [], 'style': ["down_blocks"],}
def resize_width_height(width, height, min_short_side=512, max_long_side=1024):
if width < height:
if width < min_short_side: scale_factor = min_short_side / width new_width = min_short_side new_height = int(height * scale_factor) else: new_width, new_height = width, height else:
if height < min_short_side: scale_factor = min_short_side / height new_width = int(width * scale_factor) new_height = min_short_side else: new_width, new_height = width, height
if max(new_width, new_height) > max_long_side: scale_factor = max_long_side / max(new_width, new_height) new_width = int(new_width * scale_factor) new_height = int(new_height * scale_factor) return new_width, new_height
def resize_content(content_image): max_long_side = 1024 min_short_side = 1024
new_width, new_height = resize_width_height(content_image.size[0], content_image.size[1], min_short_side=min_short_side, max_long_side=max_long_side) height = new_height // 16 * 16 width = new_width // 16 * 16 content_image = content_image.resize((width, height))
return width,height,content_image
attn_maps = {}def hook_fn(name): def forward_hook(module, input, output): if hasattr(module.processor, "attn_map"): attn_maps[name] = module.processor.attn_map del module.processor.attn_map
return forward_hook
def register_cross_attention_hook(unet): for name, module in unet.named_modules(): if name.split('.')[-1].startswith('attn2'): module.register_forward_hook(hook_fn(name))
return unet
def upscale(attn_map, target_size): attn_map = torch.mean(attn_map, dim=0) attn_map = attn_map.permute(1,0) temp_size = None
for i in range(0,5): scale = 2 ** i if ( target_size[0] // scale ) * ( target_size[1] // scale) == attn_map.shape[1]*64: temp_size = (target_size[0]//(scale*8), target_size[1]//(scale*8)) break
assert temp_size is not None, "temp_size cannot is None"
attn_map = attn_map.view(attn_map.shape[0], *temp_size)
attn_map = F.interpolate( attn_map.unsqueeze(0).to(dtype=torch.float32), size=target_size, mode='bilinear', align_corners=False )[0]
attn_map = torch.softmax(attn_map, dim=0) return attn_mapdef get_net_attn_map(image_size, batch_size=2, instance_or_negative=False, detach=True):
idx = 0 if instance_or_negative else 1 net_attn_maps = []
for name, attn_map in attn_maps.items(): attn_map = attn_map.cpu() if detach else attn_map attn_map = torch.chunk(attn_map, batch_size)[idx].squeeze() attn_map = upscale(attn_map, image_size) net_attn_maps.append(attn_map)
net_attn_maps = torch.mean(torch.stack(net_attn_maps,dim=0),dim=0)
return net_attn_maps
def attnmaps2images(net_attn_maps):
#total_attn_scores = 0 images = []
for attn_map in net_attn_maps: attn_map = attn_map.cpu().numpy() #total_attn_scores += attn_map.mean().item()
normalized_attn_map = (attn_map - np.min(attn_map)) / (np.max(attn_map) - np.min(attn_map)) * 255 normalized_attn_map = normalized_attn_map.astype(np.uint8) #print("norm: ", normalized_attn_map.shape) image = Image.fromarray(normalized_attn_map)
#image = fix_save_attn_map(attn_map) images.append(image)
#print(total_attn_scores) return imagesdef is_torch2_available(): return hasattr(F, "scaled_dot_product_attention")
def get_generator(seed, device):
if seed is not None: if isinstance(seed, list): generator = [torch.Generator(device).manual_seed(seed_item) for seed_item in seed] else: generator = torch.Generator(device).manual_seed(seed) else: generator = None
return generator123456789101112131415161718diffusers==0.25.1torch==2.0.1torchaudio==2.0.2torchvision==0.15.2transformers==4.40.2acceleratesafetensorseinopsspaces==0.19.4omegaconfpefthuggingface-hub==0.24.5opencv-pythoninsightfacegradiocontrolnet_auxgdownpeftapp.pyAdded+238
assets/style1.jpgAdded

assets/style2.jpgAdded

ip_adapter/__init__.pyAdded+15
ip_adapter/__pycache__/__init__.cpython-310.pycAdded
ip_adapter/__pycache__/__init__.cpython-39.pycAdded
ip_adapter/__pycache__/attention_processor.cpython-310.pycAdded
ip_adapter/__pycache__/attention_processor.cpython-39.pycAdded
ip_adapter/__pycache__/ip_adapter.cpython-310.pycAdded
ip_adapter/__pycache__/ip_adapter.cpython-39.pycAdded
ip_adapter/__pycache__/resampler.cpython-310.pycAdded
ip_adapter/__pycache__/resampler.cpython-39.pycAdded
ip_adapter/__pycache__/utils.cpython-310.pycAdded
ip_adapter/__pycache__/utils.cpython-39.pycAdded
ip_adapter/attention_processor.pyAdded+1645
ip_adapter/ip_adapter.pyAdded+1757
ip_adapter/resampler.pyAdded+158
ip_adapter/utils.pyAdded+142
requirements.txtAdded+18