
    bi-i                         d dl mZmZmZmZ d dlZd dlZd dlmZ d dlm	Z	 ddl
mZ ddlmZmZmZmZ  e       rd dlmZmZ  e       r
d d	lmZmZmZ  ej0                  e      Zd
ZdZed        Z G d d      Zy)    )DictListOptionalUnionN)validate_hf_hub_args)nn   )load_state_dict)_get_model_fileis_accelerate_availableis_transformers_availablelogging)PreTrainedModelPreTrainedTokenizer)AlignDevicesHook
CpuOffloadremove_hook_from_modulezlearned_embeds.binzlearned_embeds.safetensorsc                    |j                  dd       }|j                  dd      }|j                  dd       }|j                  dd       }|j                  dd       }|j                  dd       }|j                  dd       }|j                  d	d       }	|j                  d
d       }
d}|
d}
d}ddd}g }| D ]  }t        |t        t        j                  f      sd }|
r|	|	P|	j                  d      r?	 t        ||	xs t        ||||||||
      }t        j                  j                  |d      }|+t        ||	xs t        ||||||||
      }t        |      }n|}|j                          |S # t        $ r}|s|d }Y d }~Vd }~ww xY w)N	cache_dirforce_downloadFproxieslocal_files_onlyhf_tokenrevision	subfolderweight_nameuse_safetensorsTtext_inversionpytorch)	file_type	frameworkz.safetensors)	weights_namer   r   r   r   tokenr   r   
user_agentcpudevice)pop
isinstancedicttorchTensorendswithr   TEXT_INVERSION_NAME_SAFEsafetensors	load_file	ExceptionTEXT_INVERSION_NAMEr
   append)pretrained_model_name_or_pathskwargsr   r   r   r   r   r   r   r   r   allow_pickler$   state_dictspretrained_model_name_or_path
model_file
state_dictes                     ^/home/cdr/jupyterlab/.venv/lib/python3.12/site-packages/diffusers/loaders/textual_inversion.py"load_textual_inversion_state_dictsr=   %   s   

;-IZZ 0%8NjjD)Gzz"4d;zz*d+Hzz*d+H

;-I**]D1Kjj!2D9OL &J K)G .'%7$9MNJ  K$7'K,@,@,P&!05%0%L4L"+'5 ')9&!)"+#-"J "-!2!2!<!<ZPU!<!VJ !,1!,!C0C'#1#%5"%')
 -Z8
6J:&].'` 3 ! &'!%J	&s   1>E11	F
:FF
c                   F   e Zd ZdZdeeee   f   ddfdZdeddfdZd Z	e
d        Ze
d	        Ze	 	 	 ddeeee   eeej                   f   eeeej                   f      f   deeeee   f      ded   ded   fd       Z	 	 	 ddeeeee   f      ded   ded   fdZy
)TextualInversionLoaderMixinzY
    Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
    prompt	tokenizerr   c                     t        |t              s|g}n|}|D cg c]  }| j                  ||       }}t        |t              s|d   S |S c c}w )a  
        Processes prompts that include a special token corresponding to a multi-vector textual inversion embedding to
        be replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
        inversion token or if the textual inversion token is a single vector, the input prompt is returned.

        Parameters:
            prompt (`str` or list of `str`):
                The prompt or prompts to guide the image generation.
            tokenizer (`PreTrainedTokenizer`):
                The tokenizer responsible for encoding the prompt into input tokens.

        Returns:
            `str` or list of `str`: The converted prompt
        r   )r)   r   _maybe_convert_prompt)selfr@   rA   promptsps        r<   maybe_convert_promptz0TextualInversionLoaderMixin.maybe_convert_prompts   sY     &$'hGGELM4--a;MM&$'1: Ns   Ac                    |j                  |      }t        |      }|D ]^  }||j                  v s|}d}| d| |j                  v r$|d| d| z  }|dz  }| d| |j                  v r$|j                  ||      }` |S )a  
        Maybe convert a prompt into a "multi vector"-compatible prompt. If the prompt includes a token that corresponds
        to a multi-vector textual inversion embedding, this function will process the prompt so that the special token
        is replaced with multiple special tokens each corresponding to one of the vectors. If the prompt has no textual
        inversion token or a textual inversion token that is a single vector, the input prompt is simply returned.

        Parameters:
            prompt (`str`):
                The prompt to guide the image generation.
            tokenizer (`PreTrainedTokenizer`):
                The tokenizer responsible for encoding the prompt into input tokens.

        Returns:
            `str`: The converted prompt
           _ )tokenizesetadded_tokens_encoderreplace)rD   r@   rA   tokensunique_tokensr#   replacementis           r<   rC   z1TextualInversionLoaderMixin._maybe_convert_prompt   s      ##F+F" 	<E	666#qn	(F(FFQugQqc?2KFA qn	(F(FF  {;	<     c                    |9t        | j                  j                   d| j                  j                   d      |9t        | j                  j                   d| j                  j                   d      t	        |      dkD  r;t	        |      t	        |      k7  r$t        dt	        |       dt	        |       d      |D cg c]  }||	 }}t	        t        |            t	        |      k  rt        d|       y c c}w )	Nz_ requires `self.tokenizer` or passing a `tokenizer` of type `PreTrainedTokenizer` for calling ``za requires `self.text_encoder` or passing a `text_encoder` of type `PreTrainedModel` for calling `rI   z+You have passed a list of models of length z, and list of tokens of length z+ Make sure both lists have the same length.z;You have passed a list of tokens that contains duplicates: )
ValueError	__class____name__load_textual_inversionlenrM   )rD   rA   text_encoderr4   rP   tvalid_tokenss          r<   _check_text_inv_inputsz2TextualInversionLoaderMixin._check_text_inv_inputs   sB   >>**+ ,0099:!= 
 >>**+ ,0099:!= 
 -.2s;Y7Z^abh^i7i=cB`>a=b  cB  CF  GM  CN  BO O= > 
 $*;aQ];;s< !C$55Z[aZbcdd 6 <s   DDc                    g }g }t        ||       D ]  \  }}t        |t        j                        r|t	        d      |}|}nUt        |      dk(  r&t        t        |j                                     \  }}n!d|v r|d   }|d   d   }nt	        d| d      |"||k7  rt        j                  d| d	| d
       n|}||j                         v rt	        d| d| d      |j                  |       |j                  |        ||fS )NzYou are trying to load a textual inversion embedding that has been saved as a PyTorch tensor. Make sure to pass the name of the corresponding token in this case: `token=...`.rI   string_to_paramname*z&Loaded state dictionary is incorrect: z. 

Please verify that the loaded state dictionary of the textual embedding either only has a single key or includes the `string_to_param` input key.zThe loaded token: z$ is overwritten by the passed token .zToken zQ already in tokenizer vocabulary. Please choose a different token name or remove 3 and embedding from the tokenizer and text encoder.)zipr)   r+   r,   rW   r[   nextiteritemsloggerinfo	get_vocabr3   )	rP   r7   rA   
all_tokensall_embeddingsr:   r#   loaded_token	embeddings	            r<   _retrieve_tokens_and_embeddingsz;TextualInversionLoaderMixin._retrieve_tokens_and_embeddings   s_   
!$[&!9 !	-J*ell3=$ I   %&	ZA%*.tJ4D4D4F/G*H'i"j0)&1&'89#>	 <ZL I" "   \U%:0>bchbiijkl$	++-- UG#tuzt{  |o  p  e$!!),C!	-F >))rT   c           	      l   g }g }t        ||       D ]  \  }}| d|j                         v rY|g}d}| d| |j                  v r/|j                  | d|        |dz  }| d| |j                  v r/t	        d| d| d      t        |j                        dkD  xr |j                  d   dkD  }	|	rG||gt        d|j                  d         D cg c]	  }| d|  c}z   z  }||D 
cg c]  }
|
 c}
z  }||gz  }|t        |j                        dkD  r|d   gn|gz  } ||fS c c}w c c}
w )N_1rI   rJ   zMulti-vector Token zU already in tokenizer vocabulary. Please choose a different token name or remove the re   r   )rf   rl   rN   r3   rW   r[   shaperange)rP   
embeddingsrA   rm   rn   rp   r#   multi_vector_tokensrS   is_multi_vectorr;   s              r<   _extend_tokens_and_embeddingsz9TextualInversionLoaderMixin._extend_tokens_and_embeddings   s   
 #J 7 	^Iu|y2244',g#qn	(F(FF'..%!~>FA qn	(F(FF !)*=)>  ?T  Uh  Ti  i\  ]  ")//2Q6Q9??1;MPQ;QOugq)//Z[J\A](^AE7!A3(^^^
i"81"88ug%
C	4H14L9Q<.S\R]]%	^( >)) )_"8s   D,
,	D1Nr8   r#   r\   r   c                    |xs t        | dd      }|xs t        | dd      }t        |t              s|gn|}t        |t              s|gn|}|d   |t        |      z  }| j	                  ||||       t        |fi |}t        |      dkD  rtt        |      dk(  rft        |d   t        j                        rIt        |d         }t        |      t        |      k7  r$t        dt        |       dt        |       d      | j                  |||      \  }}	| j                  ||	|      \  }}	|j                         j                  j                  d	   t        fd
|	D              rt        d      d}
d}| j                  | j                   j#                         D ]  \  }}t        |t$        j&                        s!t)        |d      s.t        t        |d      t*              }
t        t        |d      t,              xs? t)        |j.                  d      xr' t        |j.                  j0                  d   t,              }t2        j5                  d       |s|
st7        ||        |j8                  }|j:                  }|j=                  t        |      t        |      z          |j                         j                  }t?        ||	      D ]O  \  }}|jA                  |       |jC                  |      }||jD                  |<   t2        j5                  d| d       Q |jG                  ||       |
r| jI                  |       y|r| jK                  |       yy)u  
        Load Textual Inversion embeddings into the text encoder of [`StableDiffusionPipeline`] (both 🤗 Diffusers and
        Automatic1111 formats are supported).

        Parameters:
            pretrained_model_name_or_path (`str` or `os.PathLike` or `List[str or os.PathLike]` or `Dict` or `List[Dict]`):
                Can be either one of the following or a list of them:

                    - A string, the *model id* (for example `sd-concepts-library/low-poly-hd-logos-icons`) of a
                      pretrained model hosted on the Hub.
                    - A path to a *directory* (for example `./my_text_inversion_directory/`) containing the textual
                      inversion weights.
                    - A path to a *file* (for example `./my_text_inversions.pt`) containing textual inversion weights.
                    - A [torch state
                      dict](https://pytorch.org/tutorials/beginner/saving_loading_models.html#what-is-a-state-dict).

            token (`str` or `List[str]`, *optional*):
                Override the token to use for the textual inversion weights. If `pretrained_model_name_or_path` is a
                list, then `token` must also be a list of equal length.
            text_encoder ([`~transformers.CLIPTextModel`], *optional*):
                Frozen text-encoder ([clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14)).
                If not specified, function will take self.tokenizer.
            tokenizer ([`~transformers.CLIPTokenizer`], *optional*):
                A `CLIPTokenizer` to tokenize text. If not specified, function will take self.tokenizer.
            weight_name (`str`, *optional*):
                Name of a custom weight file. This should be used when:

                    - The saved textual inversion file is in 🤗 Diffusers format, but was saved under a specific weight
                      name such as `text_inv.bin`.
                    - The saved textual inversion file is in the Automatic1111 format.
            cache_dir (`Union[str, os.PathLike]`, *optional*):
                Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
                is not used.
            force_download (`bool`, *optional*, defaults to `False`):
                Whether or not to force the (re-)download of the model weights and configuration files, overriding the
                cached versions if they exist.

            proxies (`Dict[str, str]`, *optional*):
                A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
                'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
            local_files_only (`bool`, *optional*, defaults to `False`):
                Whether to only load local model weights and configuration files or not. If set to `True`, the model
                won't be downloaded from the Hub.
            hf_token (`str` or *bool*, *optional*):
                The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
                `diffusers-cli login` (stored in `~/.huggingface`) is used.
            revision (`str`, *optional*, defaults to `"main"`):
                The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
                allowed by Git.
            subfolder (`str`, *optional*, defaults to `""`):
                The subfolder location of a model file within a larger model repository on the Hub or locally.
            mirror (`str`, *optional*):
                Mirror source to resolve accessibility issues if you're downloading a model in China. We do not
                guarantee the timeliness or safety of the source, and you should refer to the mirror site for more
                information.

        Example:

        To load a Textual Inversion embedding vector in 🤗 Diffusers format:

        ```py
        from diffusers import StableDiffusionPipeline
        import torch

        model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
        pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

        pipe.load_textual_inversion("sd-concepts-library/cat-toy")

        prompt = "A <cat-toy> backpack"

        image = pipe(prompt, num_inference_steps=50).images[0]
        image.save("cat-backpack.png")
        ```

        To load a Textual Inversion embedding vector in Automatic1111 format, make sure to download the vector first
        (for example from [civitAI](https://civitai.com/models/3036?modelVersionId=9857)) and then load the vector
        locally:

        ```py
        from diffusers import StableDiffusionPipeline
        import torch

        model_id = "stable-diffusion-v1-5/stable-diffusion-v1-5"
        pipe = StableDiffusionPipeline.from_pretrained(model_id, torch_dtype=torch.float16).to("cuda")

        pipe.load_textual_inversion("./charturnerv2.pt", token="charturnerv2")

        prompt = "charturnerv2, multiple views of the same character in the same outfit, a character turnaround of a woman wearing a black jacket and red shirt, best quality, intricate details."

        image = pipe(prompt, num_inference_steps=50).images[0]
        image.save("character.png")
        ```

        rA   Nr\   r   rI   z&You have passed a state_dict contains z* embeddings, and list of tokens of length z% Make sure both have the same length.c              3   B   K   | ]  }|j                   d    k7    yw)r{   N)rt   ).0embexpected_emb_dims     r<   	<genexpr>zETextualInversionLoaderMixin.load_textual_inversion.<locals>.<genexpr>  s     GS399R=0Gs   zLoaded embeddings are of incorrect shape. Expected each textual inversion embedding to be of shape {input_embeddings.shape[-1]}, but are {embeddings.shape[-1]} F_hf_hookhookszAccelerate hooks detected. Since you have called `load_textual_inversion()`, the previous hooks will be first removed. Then the textual inversion parameters will be loaded and the hooks will be applied again.)recursez'Loaded textual inversion embedding for rd   )dtyper'   r&   )&getattrr)   listr[   r_   r=   r+   r,   rW   rq   ry   get_input_embeddingsweightrt   anyhf_device_map
componentsri   r   Modulehasattrr   r   r   r   rj   rk   r   r'   r   resize_token_embeddingsrf   
add_tokensconvert_tokens_to_idsdatatoenable_model_cpu_offloadenable_sequential_cpu_offload)rD   r8   r#   rA   r\   r5   r4   rP   r7   rv   is_model_cpu_offloadis_sequential_cpu_offloadrJ   	componentr'   r   input_embeddingsrp   token_idr   s                      @r<   rZ   z2TextualInversionLoaderMixin.load_textual_inversion  s}   R A{D!A	#Jwt^T'J
 ;TB ++. 	'
 !+5$ 7%U!9c"@AAF 	##I|=[]cd 99Wb[ab v;?s;/14+a.%,,7";q>2v;#k"22$@[AQ@RR|  ~A  BH  ~I  }J J? @  "AA&+W`a
 "??
T]^
 (<<>EEKKBOGJGG_   %$)!% $ 5 5 7 b9i3y*5/9')Z:XZd/e,&wy*'EGWX Z&y'9'97C  Z *9+=+=+C+CA+FHX Y 2
  o 58L3IG`ab  $$"" 	,,S^c&k-IJ'<<>EE !$FJ 7 	LE9  ' 66u=H.7!!(+KKA%JK	L 	%7  )))8&..f.= 'rT   rP   c                    |xs t        | dd      }|xs t        | dd      }g }d}|r}t        |t              r|g}|j                  j	                         D ]4  \  }}|j
                  s!|j                  |v s!|j                  |       3|}6 t        |      dk(  rjt        d      g }|j                  j	                         D ]@  \  }}|j
                  s-|j                  |       |j                  |j                         ?|}B t        ||      D ]  \  }}	|j                  |= |j                  |	= ! d}
|j                  D ]`  }||kD  s	|||
z   kD  s|j                  |   }||j                  ||
z   <   |j                  |= ||
z   |j                  |j                  <   |
dz  }
b |j                          |j                          |j                         j                   }|j                         j"                  }|d|dz    }g }t%        |dz   |j&                  d         D ]*  }||vs|j                  ||   j)                  d             , t        |      dkD  r0t+        j,                  |d      }t+        j,                  ||gd      }t/        j0                  |j&                  d   |      }||j"                  _        |j5                  |       y)au  
        Unload Textual Inversion embeddings from the text encoder of [`StableDiffusionPipeline`]

        Example:
        ```py
        from diffusers import AutoPipelineForText2Image
        import torch

        pipeline = AutoPipelineForText2Image.from_pretrained("stable-diffusion-v1-5/stable-diffusion-v1-5")

        # Example 1
        pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")
        pipeline.load_textual_inversion("sd-concepts-library/moeb-style")

        # Remove all token embeddings
        pipeline.unload_textual_inversion()

        # Example 2
        pipeline.load_textual_inversion("sd-concepts-library/moeb-style")
        pipeline.load_textual_inversion("sd-concepts-library/gta5-artwork")

        # Remove just one token
        pipeline.unload_textual_inversion("<moe-bius>")

        # Example 3: unload from SDXL
        pipeline = AutoPipelineForText2Image.from_pretrained("stabilityai/stable-diffusion-xl-base-1.0")
        embedding_path = hf_hub_download(
            repo_id="linoyts/web_y2k", filename="web_y2k_emb.safetensors", repo_type="model"
        )

        # load embeddings to the text encoders
        state_dict = load_file(embedding_path)

        # load embeddings of text_encoder 1 (CLIP ViT-L/14)
        pipeline.load_textual_inversion(
            state_dict["clip_l"],
            tokens=["<s0>", "<s1>"],
            text_encoder=pipeline.text_encoder,
            tokenizer=pipeline.tokenizer,
        )
        # load embeddings of text_encoder 2 (CLIP ViT-G/14)
        pipeline.load_textual_inversion(
            state_dict["clip_g"],
            tokens=["<s0>", "<s1>"],
            text_encoder=pipeline.text_encoder_2,
            tokenizer=pipeline.tokenizer_2,
        )

        # Unload explicitly from both text encoders and tokenizers
        pipeline.unload_textual_inversion(
            tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder, tokenizer=pipeline.tokenizer
        )
        pipeline.unload_textual_inversion(
            tokens=["<s0>", "<s1>"], text_encoder=pipeline.text_encoder_2, tokenizer=pipeline.tokenizer_2
        )
        ```
        rA   Nr\   r   zNo tokens to remove foundrI   )dim)r   r)   stradded_tokens_decoderri   specialcontentr3   r[   rW   rf   _added_tokens_decoder_added_tokens_encoder_update_trie_update_total_vocab_sizer   embedding_dimr   ru   rt   	unsqueezer+   catr   	Embeddingr   set_input_embeddings)rD   rP   rA   r\   	token_idslast_special_token_idadded_token_idadded_tokenr   token_to_removekey_idr#   text_embedding_dimtemp_text_embedding_weightstext_embedding_weights	to_appendrS   text_embeddings_filtereds                     r<   unload_textual_inversionz4TextualInversionLoaderMixin.unload_textual_inversion  s   @ A{D!A	#Jwt^T'J 	 $&#& /8/M/M/S/S/U ;+"**"**f4!((8,:); 9~" !<==F/8/M/M/S/S/U ;+"**$$^4MM+"5"56,:); *-Y)? 	A%Ho//9//@	A
 !66 	H//H?TW]?]4]!77ARW	//0E0NO33H=AVY_A_	//>!	 	 **, *>>@NN&2&G&G&I&P&P#!<=X?TWX?X!Y	,q02M2S2STU2VW 	NA	!  !<Q!?!I!I!!LM	N y>A		)3I%*YY0F	/RXY%Z"#%<<0F0L0LQ0OQc#d /E '',))*BCrT   )NNN)rY   
__module____qualname____doc__r   r   r   rG   rC   r_   staticmethodrq   ry   r   r   r+   r,   r   rZ   r    rT   r<   r?   r?   n   s`   5d3i+@ Mb 6C <Q <e. &* &*P * *4  265948>',S$s)T#u||BS=TVZ[_`cejeqeq`q[rVs-s't> c49n-.> 12	>
 01> >J 375948	zDsDI~./zD 12zD 01	zDrT   r?   )typingr   r   r   r   r/   r+   huggingface_hub.utilsr   r   models.modeling_utilsr
   utilsr   r   r   r   transformersr   r   accelerate.hooksr   r   r   
get_loggerrY   rj   r2   r.   r=   r?   r   rT   r<   <module>r      s|    / .   6  3 ` ` AVV			H	%* 7  E EPWD WDrT   