
    +h8                     >   S r SSKrSSKrSSKJr  SSKJr  \" 5       (       a  SSKr\" \5      r	 " S S\R                  5      rSS	S
SSSSSSSSS.rSSSSSSSSSSSSS.rSSSSSSSSSSS.
r0 SS _SS!_SS"_SS#_SS$_SS%_SS&_SS'_S(S)_S*S+_S,S-_S.S/_S0S1_S2S3_S4S5_S6S7_rS S!S"S#S$S%S&S'S8S9S:S;S<.rS=S>S?.r\R$                  \\R&                  \0r\R$                  \\R*                  \0r\R*                  \0rS@SA0rSB rSKSC jrSKSD jrSE rSF rSKSG jrSKSH jrSI\ 4SJ jr!g)LzI
State dict utilities: utility methods for converting state dicts easily
    N   )is_torch_available)
get_loggerc                   (    \ rS rSrSrSrSrSrSrSr	g)	StateDictType    z.
The mode to use when converting state dicts.
diffusers_oldkohya_sspeft	diffusers N)
__name__
__module____qualname____firstlineno____doc__DIFFUSERS_OLDKOHYA_SSPEFT	DIFFUSERS__static_attributes__r       Z/home/james-whalen/.local/lib/python3.13/site-packages/diffusers/utils/state_dict_utils.pyr   r       s     $MHDIr   r   z.to_out.0.lora_Bz.to_out.0.lora_Az.to_q.lora_Az.to_q.lora_Bz.to_k.lora_Az.to_k.lora_Bz.to_v.lora_Az.to_v.lora_Bz.lora_B.lora_Az.to_out.0.lora_magnitude_vector).to_out_lora.up.to_out_lora.down.to_q_lora.down.to_q_lora.up.to_k_lora.down.to_k_lora.up.to_v_lora.down.to_v_lora.upz.lora.upz
.lora.down.to_out.lora_magnitude_vectorz.q_proj.lora_Bz.q_proj.lora_Az.k_proj.lora_Bz.k_proj.lora_Az.v_proj.lora_Bz.v_proj.lora_Az.out_proj.lora_Bz.out_proj.lora_Aztext_projection.lora_A.weightztext_projection.lora_B.weight).q_proj.lora_linear_layer.up.q_proj.lora_linear_layer.down.k_proj.lora_linear_layer.up.k_proj.lora_linear_layer.down.v_proj.lora_linear_layer.up.v_proj.lora_linear_layer.down.out_proj.lora_linear_layer.up .out_proj.lora_linear_layer.down.lora_linear_layer.up.lora_linear_layer.downz text_projection.lora.down.weightztext_projection.lora.up.weight)
r   r   r    r   r"   r!   r   r   r,   r-   r$   r%   r&   r'   r(   r)   r*   r+   zto_k.lora_Azto_k.lora.downzto_k.lora_Bzto_k.lora.upzto_q.lora_Azto_q.lora.downzto_q.lora_Bzto_q.lora.upzto_v.lora_Azto_v.lora.downzto_v.lora_Bzto_v.lora.upzto_out.0.lora_Azto_out.0.lora.downzto_out.0.lora_Bzto_out.0.lora.upz.k_proj.lora_magnitude_vectorz.v_proj.lora_magnitude_vectorz.q_proj.lora_magnitude_vectorz.out_proj.lora_magnitude_vector)r   r   r    r   r"   r!   r   r   z.to_k.lora_magnitude_vectorz.to_v.lora_magnitude_vectorz.to_q.lora_magnitude_vectorr#   	lora_downlora_up)lora_Alora_Bz.processor..c                 "   0 nU R                  5        Hx  u  p4[        R                  5        H$  nXS;   d  M
  [        U   nUR                  XV5      nM&     UR                  5        H  nXS;   d  M
  X   nUR                  XV5      n  O   XBU'   Mz     U$ )a  
Simply iterates over the state dict and replaces the patterns in `mapping` with the corresponding values.

Args:
    state_dict (`dict[str, torch.Tensor]`):
        The state dict to convert.
    mapping (`dict[str, str]`):
        The mapping to use for conversion, the mapping should be a dictionary with the following structure:
            - key: the pattern to replace
            - value: the pattern to replace with

Returns:
    converted_state_dict (`dict`)
        The converted state dict.
)itemsKEYS_TO_ALWAYS_REPLACEkeysreplace)
state_dictmappingconverted_state_dictkvpatternnew_patterns          r   convert_state_dictr?      s        "-224G|4W=IIg3 5
 ||~G|%.IIg3	 &
 #$Q #  r   c                 l   Ucw  [        S U R                  5        5       5      (       a  [        R                  nOA[        S U R                  5        5       5      (       a  [        R                  nO[        S5      eU[        R                  5       ;  a  [        SU S35      e[        U   n[        X5      $ )a  
Converts a state dict to the PEFT format The state dict can be from previous diffusers format (`OLD_DIFFUSERS`), or
new diffusers format (`DIFFUSERS`). The method only supports the conversion from diffusers old/new to PEFT for now.

Args:
    state_dict (`dict[str, torch.Tensor]`):
        The state dict to convert.
    original_type (`StateDictType`, *optional*):
        The original type of the state dict, if not provided, the method will try to infer it automatically.
c              3   ,   #    U  H
  nS U;   v   M     g7fto_out_loraNr   .0r;   s     r   	<genexpr>-convert_state_dict_to_peft.<locals>.<genexpr>        =+<a}!+<   c              3   ,   #    U  H
  nS U;   v   M     g7flora_linear_layerNr   rD   s     r   rF   rG           E3Da$)3DrI   -Could not automatically infer state dict typeOriginal type  is not supported)anyr6   r   r   r   
ValueErrorPEFT_STATE_DICT_MAPPINGSr?   )r8   original_typekwargsr9   s       r   convert_state_dict_to_peftrV      s     =:??+<===)77ME:??3DEEE)33MLMM499;;>-8IJKK&}5Gj22r   c                   ^ UR                  SS5      mTb  ST-   mOSmUc  [        S U R                  5        5       5      (       a  [        R                  nOk[        U4S jU R                  5        5       5      (       a  [        R
                  nO2[        S U R                  5        5       5      (       a  U $ [        S5      eU[        R                  5       ;  a  [        S	U S
35      e[        U   n[        X5      $ )a^  
Converts a state dict to new diffusers format. The state dict can be from previous diffusers format
(`OLD_DIFFUSERS`), or PEFT format (`PEFT`) or new diffusers format (`DIFFUSERS`). In the last case the method will
return the state dict as is.

The method only supports the conversion from diffusers old, PEFT to diffusers new for now.

Args:
    state_dict (`dict[str, torch.Tensor]`):
        The state dict to convert.
    original_type (`StateDictType`, *optional*):
        The original type of the state dict, if not provided, the method will try to infer it automatically.
    kwargs (`dict`, *args*):
        Additional arguments to pass to the method.

        - **adapter_name**: For example, in case of PEFT, some keys will be prepended
            with the adapter name, therefore needs a special handling. By default PEFT also takes care of that in
            `get_peft_model_state_dict` method:
            https://github.com/huggingface/peft/blob/ba0477f2985b1ba311b83459d29895c809404e99/src/peft/utils/save_and_load.py#L92
            but we add it here in case we don't want to rely on that method.
adapter_nameNr2    c              3   ,   #    U  H
  nS U;   v   M     g7frB   r   rD   s     r   rF   2convert_state_dict_to_diffusers.<locals>.<genexpr>   rH   rI   c              3   6   >#    U  H  nS T S3U;   v   M     g7fr   z.weightNr   rE   r;   peft_adapter_names     r   rF   r[      s#     VDUq7,-W5:DU   c              3   ,   #    U  H
  nS U;   v   M     g7frK   r   rD   s     r   rF   r[      rM   rI   rN   rO   rP   )	poprQ   r6   r   r   r   rR   DIFFUSERS_STATE_DICT_MAPPINGSr?   )r8   rT   rU   r9   r_   s       @r   convert_state_dict_to_diffusersrd      s    , 

>48$"33=:??+<===)77MVJOODUVVV)..ME:??3DEEELMM9>>@@>-8IJKK+M:Gj22r   c                 $    [         n[        X5      $ )zY
Converts a state dict from UNet format to diffusers format - i.e. by removing some keys
)UNET_TO_DIFFUSERSr?   )r8   r9   s     r   convert_unet_state_dict_to_peftrg      s      Gj22r   c                      [        U 5      n[	        S UR                  5        5       5      (       d  [        S5      eU$ ! [         a%  n[        U5      S:X  a  [        U 5      n SnAN[e SnAff = f)z
Attempts to first `convert_state_dict_to_peft`, and if it doesn't detect `lora_linear_layer` for a valid
`DIFFUSERS` LoRA for example, attempts to exclusively convert the Unet `convert_unet_state_dict_to_peft`
rN   Nc              3   D   #    U  H  nS U;   =(       d    SU;   v   M     g7f)r0   r1   Nr   )rE   keys     r   rF   1convert_all_state_dict_to_peft.<locals>.<genexpr>  s"     N=Mcx31(c/1=Ms    z#Your LoRA was not converted to PEFT)rV   	Exceptionstrrg   rQ   r6   rR   )r8   	peft_dictes      r   convert_all_state_dict_to_peftrp     si    
.z:	 NY^^=MNNN>??  q6DD7
CI	s   ? 
A.	A)(A))A.c                   ^	  SSK nUR	                  SS5      m	T	b  ST	-   m	OSm	Uc8  [        U	4S jU R                  5        5       5      (       a  [        R                  nU[        R                  5       ;  a  [        SU S	35      e[        U [        [        R                     5      n0 nUR                  5        H  u  pgS
U;   a  UR                  S
S5      nOJSU;   a  UR                  SS5      nO1SU;   a  UR                  SS5      nOSU;   a  UR                  SS5      nUR                  SSUR                  S5      S-
  5      nUR                  T	S5      nXuU'   SU;   d  M  UR                  S5      S    S3nUR                   " [#        U5      5      XX'   M     U$ ! [         a    [        R                  S5        e f = f)a  
Converts a `PEFT` state dict to `Kohya` format that can be used in AUTOMATIC1111, ComfyUI, SD.Next, InvokeAI, etc.
The method only supports the conversion from PEFT to Kohya for now.

Args:
    state_dict (`dict[str, torch.Tensor]`):
        The state dict to convert.
    original_type (`StateDictType`, *optional*):
        The original type of the state dict, if not provided, the method will try to infer it automatically.
    kwargs (`dict`, *args*):
        Additional arguments to pass to the method.

        - **adapter_name**: For example, in case of PEFT, some keys will be prepended
            with the adapter name, therefore needs a special handling. By default PEFT also takes care of that in
            `get_peft_model_state_dict` method:
            https://github.com/huggingface/peft/blob/ba0477f2985b1ba311b83459d29895c809404e99/src/peft/utils/save_and_load.py#L92
            but we add it here in case we don't want to rely on that method.
r   NzDConverting PEFT state dicts to Kohya requires torch to be installed.rX   r2   rY   c              3   6   >#    U  H  nS T S3U;   v   M     g7fr]   r   r^   s     r   rF   .convert_state_dict_to_kohya.<locals>.<genexpr>9  s#     TBSQ*+73q8BSr`   rO   rP   ztext_encoder_2.z	lora_te2.ztext_encoder.z	lora_te1.unet	lora_unetlora_magnitude_vector
dora_scale_   r.   z.alpha)torchImportErrorloggererrorrb   rQ   r6   r   r   KOHYA_STATE_DICT_MAPPINGSrR   r?   r4   r7   countsplittensorlen)
r8   rT   rU   rz   kohya_ss_partial_state_dictkohya_ss_state_dict	kohya_keyweight	alpha_keyr_   s
            @r   convert_state_dict_to_kohyar     s   &
 

>48$"33T*//BSTTT)..M5::<<>-8IJKK #5ZAZ[h[m[mAn"o 9>>@		)!))*;[II	)!))/;GIy !))&+>I$	1!))*A<PI%%c3	0Dq0HI	%%&7<	)/I&)#$??3/236:I-2\\#f+-F* A" O  [\s   F !F?c                   ^ Ub[  [        U[        5      (       a  U/nU R                  5        V^Vs0 s H%  u  mn[        U4S jU 5       5      (       d  M"  TU_M'     n nn[	        S U R                  5        5       5      $ s  snnf )Nc              3   ,   >#    U  H	  oT;   v   M     g 7fNr   )rE   fr;   s     r   rF   &state_dict_all_zero.<locals>.<genexpr>\  s     @\Q[AaQ[s   c              3   p   #    U  H,  n[         R                  " US :H  5      R                  5       v   M.     g7f)r   N)rz   allitem)rE   params     r   rF   r   ^  s+     M9Luyy!$))++9Ls   46)
isinstancerm   r4   rQ   r   values)r8   
filter_strr;   r<   s     ` r   state_dict_all_zeror   X  st    j#&&$J'1'7'7'9]'9tq!S@\Q[@\=\dad'9
]M9J9J9LMMM ^s   !B B 
model_filec                 F   SS K nSSKJn  UR                  R	                  U SSS9 nUR                  5       =(       d    0 nS S S 5        WR                  SS 5        U(       a0  UR                  U5      nU(       a  [        R                  " U5      $ S $ g ! , (       d  f       NX= f)Nr   ry   )LORA_ADAPTER_METADATA_KEYptcpu)	frameworkdeviceformat)
safetensors.torchloaders.lora_baser   rz   	safe_openmetadatarb   getjsonloads)r   safetensorsr   r   r   raws         r   _load_sft_state_dict_metadatar   a  s    =				$	$Z4	$	NRS::<%2 
O LL4 ll45"%tzz#/4/ 
O	Ns   B
B r   )"r   enumr   import_utilsr   loggingr   rz   r   r|   Enumr   rf   DIFFUSERS_TO_PEFTDIFFUSERS_OLD_TO_PEFTPEFT_TO_DIFFUSERSDIFFUSERS_OLD_TO_DIFFUSERSPEFT_TO_KOHYA_SSr   r   rS   r   rc   r~   r5   r?   rV   rd   rg   rp   r   r   rm   r   r   r   r   <module>r      sl     ,   
H	DII  *+%#%#%#%F   %5&6$4&6$4&6&8(:&((G&E   &'%'%')+&( 46 4 6	
 4 6 8 : # > # > # > +  )! ( 4737377;#B#B#B%F     !6.  !;)! 
 +//1AB  3 
 B36,3^3&<~Nc r   