
    1;ji5                        d Z ddlZddlmZ  ee          Z G d dej                  Zddd	d
ddddddddZdddddddddddddZ	ddddddddddd
Z
i dddd dd!dd"dd#dd$dd%dd&d'd(d)d*d+d,d-d.d/d0d1d2d3d4d5d6Zdd d!d"d#d$d%d&d7d8d9d:d;Zd<d=d>Zej        e
ej        e	iZej        eej        eiZej        eiZd?d@iZdA ZdGdBZdGdCZdD ZdE ZdGdFZdS )HzI
State dict utilities: utility methods for converting state dicts easily
    N   )
get_loggerc                   "    e Zd ZdZdZdZdZdZdS )StateDictTypez6
    The mode to use when converting state dicts.
    diffusers_oldkohya_sspeft	diffusersN)__name__
__module____qualname____doc__DIFFUSERS_OLDKOHYA_SSPEFT	DIFFUSERS     Z/root/voice-cloning/.venv/lib/python3.11/site-packages/diffusers/utils/state_dict_utils.pyr   r      s.          $MHDIIIr   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                 D   i }|                                  D ]\  }}t                                          D ])}||v r#t          |         }|                    ||          }*|                                D ]&}||v r ||         }|                    ||          } n'|||<   |S )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        "" $ $1-2244 	4 	4G!||4W=IIg{33||~~ 	 	G!||%g.IIg{33  #$Qr   c                    |t          d |                                 D                       rt          j        }nGt          d |                                 D                       rt          j        }nt          d          |t                                          vrt          d| d          t          |         }t          | |          S )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.
    Nc              3      K   | ]}d |v V  	dS to_out_loraNr   .0r7   s     r   	<genexpr>z-convert_state_dict_to_peft.<locals>.<genexpr>   '      ==a}!======r   c              3      K   | ]}d |v V  	dS lora_linear_layerNr   r@   s     r   rB   z-convert_state_dict_to_peft.<locals>.<genexpr>   (      EEa$)EEEEEEr   -Could not automatically infer state dict typeOriginal type  is not supported)anyr2   r   r   r   
ValueErrorPEFT_STATE_DICT_MAPPINGSr;   )r4   original_typekwargsr5   s       r   convert_state_dict_to_peftrP      s     ==:??+<+<===== 	N)7MMEE:??3D3DEEEEE 	N)3MMLMMM499;;;;J-JJJKKK&}5Gj'222r   c                 :   |                     dd          dz   nd|t          d |                                 D                       rt          j        }nvt          fd|                                 D                       rt          j        }n<t          d |                                 D                       r| S t          d          |t                                          vrt          d	| d
          t          |         }t          | |          S )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 pre-pended
                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_nameNr.    c              3      K   | ]}d |v V  	dS r>   r   r@   s     r   rB   z2convert_state_dict_to_diffusers.<locals>.<genexpr>   rC   r   c              3   (   K   | ]}d  d|v V  dS r   z.weightNr   rA   r7   peft_adapter_names     r   rB   z2convert_state_dict_to_diffusers.<locals>.<genexpr>   s5      VVq5,555:VVVVVVr   c              3      K   | ]}d |v V  	dS rE   r   r@   s     r   rB   z2convert_state_dict_to_diffusers.<locals>.<genexpr>   rG   r   rH   rI   rJ   )	poprK   r2   r   r   r   rL   DIFFUSERS_STATE_DICT_MAPPINGSr;   )r4   rN   rO   r5   rX   s       @r   convert_state_dict_to_diffusersr\      s3   , 

>488$"33==:??+<+<===== 	N)7MMVVVVJOODUDUVVVVV 	N).MMEE:??3D3DEEEEE 	NLMMM9>>@@@@J-JJJKKK+M:Gj'222r   c                 0    t           }t          | |          S )za
    Converts a state dict from UNet format to diffusers format - i.e. by removing some keys
    )UNET_TO_DIFFUSERSr;   )r4   r5   s     r   convert_unet_state_dict_to_peftr_      s      Gj'222r   c                    	 t          |           }n;# t          $ r.}t          |          dk    rt          |           }n Y d}~nd}~ww xY wt	          d |                                D                       st          d          |S )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`
    rH   Nc              3   &   K   | ]}d |v pd|v V  dS )r,   r-   Nr   )rA   keys     r   rB   z1convert_all_state_dict_to_peft.<locals>.<genexpr>  s/      NNcx31(c/NNNNNNr   z#Your LoRA was not converted to PEFT)rP   	Exceptionstrr_   rK   r2   rL   )r4   	peft_dictes      r   convert_all_state_dict_to_peftrg      s    
.z::		   q66DDD7
CCII IIII NNY^^=M=MNNNNN @>???s    
A
$AA
c                   	 	 ddl }n)# t          $ r t                              d            w xY w|                    dd          		d	z   	nd	|9t          	fd|                                 D                       rt          j        }|t                                          vrt          d| d	          t          | t          t          j                           }i }|                                D ] \  }}d
|v r|                    d
d          }nPd|v r|                    dd          }n5d|v r|                    dd          }nd|v r|                    dd          }|                    dd|                    d          dz
            }|                    	d          }|||<   d|v rC|                    d          d          d}|                    t#          |                    ||<   |S )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 pre-pended
                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.rR   r.   rS   c              3   (   K   | ]}d  d|v V  dS rV   r   rW   s     r   rB   z.convert_state_dict_to_kohya.<locals>.<genexpr>3  s5      TTQ3*333q8TTTTTTr   rI   rJ   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errorrZ   rK   r2   r   r   KOHYA_STATE_DICT_MAPPINGSrL   r;   r0   r3   countsplittensorlen)
r4   rN   rO   rp   kohya_ss_partial_state_dictkohya_ss_state_dict	kohya_keyweight	alpha_keyrX   s
            @r   convert_state_dict_to_kohyar~     sI   &   [\\\ 

>488$"33TTTT*//BSBSTTTTT 	/).M5::<<<<J-JJJKKK #5ZAZ[h[mAn"o"o 9>>@@ G G	6	))!))*;[IIII	))!))/;GGIIy  !))&+>>II$	11!))*A<PPI%%c3	0D0Dq0HII	%%&7<<	)/I&)##$??3//2:::I-2\\#f++-F-F	*s    &.)N)r   enumloggingr   r   rr   Enumr   r^   DIFFUSERS_TO_PEFTDIFFUSERS_OLD_TO_PEFTPEFT_TO_DIFFUSERSDIFFUSERS_OLD_TO_DIFFUSERSPEFT_TO_KOHYA_SSr   r   rM   r   r[   rt   r1   r;   rP   r\   r_   rg   r~   r   r   r   <module>r      s           
H		    DI    *+%#%#%#%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3 3 3 36,3 ,3 ,3 ,3^3 3 3  &< < < < < <r   