
    +h-i                        S SK JrJrJrJr  S SKrS SKrS SKJr  S SKJ	r	  SSK
Jr  SSKJrJrJrJr  \" 5       (       a  S SKJrJr  \" 5       (       a
  S S	KJrJrJr  \R0                  " \5      rS
rSr\S 5       r " S S5      rg)    )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                 R   UR                  SS 5      nUR                  SS5      nUR                  SS 5      nUR                  SS 5      nUR                  SS 5      nUR                  SS 5      nUR                  SS 5      nUR                  S	S 5      n	UR                  S
S 5      n
SnU
c  Sn
SnSSS.n/ nU  H  n[        U[        [        R                  45      (       d  S nU
(       a  U	b  U	bT  U	R                  S5      (       a>   [        UU	=(       d    [        UUUUUUUUS9
n[        R                  R                  USS9nUc*  [        UU	=(       d    [        UUUUUUUUS9
n[        U5      nOUnUR                  W5        M     U$ ! [         a  nU(       d  UeS n S nANaS nAff = f)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/james-whalen/.local/lib/python3.13/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NJ  K$7'K,@,@,P,P&!05%0%L4L"+'5 ')9&!)"+#-"J "-!2!2!<!<ZPU!<!VJ !,1!,!C0C'#1#%5"%')
 -Z8
6J:&] *H` 3 ! &'!%J	&s   =F
F&F!!F&c                   Z   \ rS rSrSrS\\\\   4   SS4S jrS\SS4S jr	S r
\S	 5       r\S
 5       r\   SS\\\\   \\\R"                  4   \\\\R"                  4      4   S\\\\\   4      S\S   S\S   4S jj5       r   SS\\\\\   4      S\S   S\S   4S jjrSrg)TextualInversionLoaderMixinn   zQ
Load Textual Inversion tokens and embeddings to the tokenizer and text encoder.
prompt	tokenizerr   c                     [        U[        5      (       d  U/nOUnU Vs/ s H  o@R                  XB5      PM     nn[        U[        5      (       d  US   $ U$ s  snf )aa  
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)selfrA   rB   promptsps        r<   maybe_convert_prompt0TextualInversionLoaderMixin.maybe_convert_prompts   s\     &$''hGGELMW--a;WM&$''1: Ns   Ac                    UR                  U5      n[        U5      nU He  nXRR                  ;   d  M  UnSnU SU 3UR                  ;   a'  USU SU 3-  nUS-  nU SU 3UR                  ;   a  M'  UR                  XV5      nMg     U$ )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)rE   rA   rB   tokensunique_tokensr#   replacementis           r<   rD   1TextualInversionLoaderMixin._maybe_convert_prompt   s      ##F+F"E666#qn	(F(FFQugQqc?2KFA qn	(F(FF  ; #     c                    Uc9  [        U R                  R                   SU R                  R                   S35      eUc9  [        U R                  R                   SU R                  R                   S35      e[	        U5      S:  a<  [	        U5      [	        U5      :w  a$  [        S[	        U5       S[	        U5       S35      eU Vs/ s H	  oUc  M  UPM     nn[	        [        U5      5      [	        U5      :  a  [        SU 35      eg s  snf )	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 `rK   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lenrO   )rE   rB   text_encoderr4   rR   tvalid_tokenss          r<   _check_text_inv_inputs2TextualInversionLoaderMixin._check_text_inv_inputs   s?   >>**+ ,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= > 
 $*;6a6;s< !C$55Z[aZbcdd 6 <s   D
D
c                 &   / n/ n[        X5       H  u  pV[        U[        R                  5      (       a  Uc  [	        S5      eUnUnOW[        U5      S:X  a%  [        [        UR                  5       5      5      u  pxO#SU;   a  US   nUS   S   nO[	        SU S35      eUb"  Xv:w  a  [        R                  SU S	U S
35        OUnXbR                  5       ;   a  [	        SU SU S35      eUR                  U5        UR                  U5        M     X44$ )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=...`.rK   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,   rZ   r^   nextiteritemsloggerinfo	get_vocabr3   )	rR   r7   rB   
all_tokensall_embeddingsr:   r#   loaded_token	embeddings	            r<   _retrieve_tokens_and_embeddings;TextualInversionLoaderMixin._retrieve_tokens_and_embeddings   sS   
!$[!9J*ell33=$ I   %&	ZA%*.tJ4D4D4F/G*H'i"j0)&1&'89#>	 <ZL I" "   \%:0>bchbiijkl$++-- UG#tuzt{  |o  p  e$!!),C ":F ))rW   c           	         / n/ n[        X5       GH'  u  pVU S3UR                  5       ;   a^  U/nSnU SU 3UR                  ;   a2  UR                  U SU 35        US-  nU SU 3UR                  ;   a  M2  [	        SU SU S35      e[        UR                  5      S:  =(       a    UR                  S   S:  n	U	(       aJ  X6/[        SUR                  S   5       Vs/ s H	  o SU 3PM     sn-   -  nXE V
s/ s H  oPM     sn
-  nM  X6/-  nU[        UR                  5      S:  a  US   /OU/-  nGM*     X44$ s  snf s  sn
f )N_1rK   rL   zMulti-vector Token zU already in tokenizer vocabulary. Please choose a different token name or remove the ri   r   )rj   rp   rP   r3   rZ   r^   shaperange)rR   
embeddingsrB   rq   rr   rt   r#   multi_vector_tokensrU   is_multi_vectorr;   s              r<   _extend_tokens_and_embeddings9TextualInversionLoaderMixin._extend_tokens_and_embeddings   s   
 #J 7I|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gq)//Z[J\A](^A]A7!A3A](^^^
i"8i1i"88g%
C	4H14L9Q<.S\R]]% !8( )) )_"8s    D?
;ENr8   r#   r_   r   c                 :  ^ U=(       d    [        U SS5      nU=(       d    [        U SS5      n[        U[        5      (       d  U/OUn[        U[        5      (       d  U/OUnUS   c  U[        U5      -  nU R	                  X4Xg5        [        U40 UD6n[        U5      S:  a{  [        U5      S:X  al  [        US   [        R                  5      (       aJ  [        US   5      n[        U5      [        U5      :w  a$  [        S[        U5       S[        U5       S35      eU R                  XxU5      u  pyU R                  XyU5      u  pyUR                  5       R                  R                  S	   m[        U4S
 jU	 5       5      (       a  [        S5      eSn
SnU R                  Gc  U R                   R#                  5        H  u  p[        U[$        R&                  5      (       d  M&  [)        US5      (       d  M9  [        [        US5      [*        5      n
[        [        US5      [,        5      =(       dD    [)        UR.                  S5      =(       a'    [        UR.                  R0                  S   [,        5      n[2        R5                  S5        U(       d	  U
(       d  M  [7        XS9  M     UR8                  nUR:                  nUR=                  [        U5      [        U5      -   5        UR                  5       R                  n[?        Xy5       HP  u  nnURA                  U5        URC                  U5      nUURD                  U'   [2        R5                  SU S35        MR     URG                  XS9  U
(       a  U RI                  US9  gU(       a  U RK                  US9  gg)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")
```

rB   Nr_   r   rK   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   H   >#    U  H  nTUR                   S    :g  v   M     g7f)r   N)ry   ).0embexpected_emb_dims     r<   	<genexpr>ETextualInversionLoaderMixin.load_textual_inversion.<locals>.<genexpr>  s     GJS399R=0Js   "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 rh   )dtyper'   r&   )&getattrr)   listr^   rb   r=   r+   r,   rZ   ru   r~   get_input_embeddingsweightry   anyhf_device_map
componentsrm   r   Modulehasattrr   r   r   r   rn   ro   r   r'   r   resize_token_embeddingsrj   
add_tokensconvert_tokens_to_idsdatatoenable_model_cpu_offloadenable_sequential_cpu_offload)rE   r8   r#   rB   r_   r5   r4   rR   r7   r{   is_model_cpu_offloadis_sequential_cpu_offloadrL   	componentr'   r   input_embeddingsrt   token_idr   s                      @r<   r]   2TextualInversionLoaderMixin.load_textual_inversion  sn   R A{D!A	#Jwt^T'J
 ;TBB ++. 	'
 !+5$ 7 7%U!9c"@AAF 	##I=[d 99Wb[ab v;?s;/14+a.%,,7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G_   %$)!% $ 5 5 7i33y*55/9')Z:XZd/e,&wy*'EGWX Z&y'9'97C  Z *9+=+=+C+CA+FHX Y 2
  o 58L8L3Ia !8  $$"" 	,,S^c&k-IJ'<<>EE !$F 7E9  ' 66u=H.7!!(+KKA%JK !8 	%7  )))8&..f.= 'rW   rR   c                    U=(       d    [        U SS5      nU=(       d    [        U SS5      n/ nSnU(       a  [        U[        5      (       a  U/nUR                  R	                  5        H=  u  pgUR
                  (       d%  UR                  U;   a  UR                  U5        M9  M;  UnM?     [        U5      S:X  a  [        S5      eOf/ nUR                  R	                  5        HF  u  pgUR
                  (       d.  UR                  U5        UR                  UR                  5        MD  UnMH     [        XA5       H  u  pUR                  U	 UR                  U		 M!     Sn
UR                   H`  nX:  d  M
  XU
-   :  d  M  UR                  U   nXR                  XZ-   '   UR                  U	 XZ-   UR                  UR                  '   U
S-  n
Mb     UR                  5         UR                  5         UR                  5       R                   nUR                  5       R"                  nUSUS-    n/ n[%        US-   UR&                  S   5       H.  nUU;  d  M  UR                  UU   R)                  S5      5        M0     [        U5      S:  a+  [*        R,                  " USS9n[*        R,                  " X/SS9n[.        R0                  " UR&                  S   U5      nUUR"                  l        UR5                  U5        g)a  
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
)
```
rB   Nr_   r   zNo tokens to remove foundrK   )dim)r   r)   stradded_tokens_decoderrm   specialcontentr3   r^   rZ   rj   _added_tokens_decoder_added_tokens_encoder_update_trie_update_total_vocab_sizer   embedding_dimr   rz   ry   	unsqueezer+   catr   	Embeddingr   set_input_embeddings)rE   rR   rB   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_appendrU   text_embeddings_filtereds                     r<   unload_textual_inversion4TextualInversionLoaderMixin.unload_textual_inversion  s   @ A{D!A	#Jwt^T'J 	 $&#&& /8/M/M/S/S/U+"**"**f4!((8 5 -;) 0V 9~" !<== # F/8/M/M/S/S/U+"**$$^4MM+"5"56,:) 0V *-Y)?%H//9//@ *@
 !66H/HW]?]4]!77ARW//0E0NO33H=AVA_	//>! 7 	 **, *>>@NN&2&G&G&I&P&P#!<=X?TWX?X!Y	,q02M2S2STU2VWA	!  !<Q!?!I!I!!LM X y>A		)3I%*YY0F/RXY%Z"#%<<0F0L0LQ0OQc#d /E '',))*BCrW    )NNN)r\   
__module____qualname____firstlineno____doc__r   r   r   rH   rD   rb   staticmethodru   r~   r   r   r+   r,   r   r]   r   __static_attributes__r   rW   r<   r?   r?   n   sg   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 zDrW   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_loggerr\   rn   r2   r.   r=   r?   r   rW   r<   <module>r      s    / .   6  3 ` ` AVV			H	%* 7  E EPWD WDrW   