o
    ¶ÏiTW  ã                   @  s    d Z ddlmZ ddlZddlZddlZddlmZ ddl	Z	ddl
Z
dddddd	d
œZddd„Zi fdd„Zi fdd„Zddd„Zddd„Ze
jdfdd„ZdS ) aÎ  
    This file is part of ComfyUI.
    Copyright (C) 2024 Comfy

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
é    )ÚannotationsNÚmlp_fc1Úmlp_fc2Úself_attn_k_projÚself_attn_q_projÚself_attn_v_projÚself_attn_out_proj)zmlp.fc1zmlp.fc2zself_attn.k_projzself_attn.q_projzself_attn.v_projzself_attn.out_projTc              	   C  s.  i }t ƒ }|D ]õ}d |¡}d }||  ¡ v r!| |  ¡ }| |¡ d |¡}d }	||  ¡ v r7| | }	| |¡ tjD ]}
|
 || ||	|¡}|d urV|||| < | |j	¡ q:q:d |¡}d |¡}|  
|d ¡}|  
|d ¡}|d ur›| |¡ d|ff||| < |d ur›| |¡ d|ff|d || d tdƒ … ¡< d |¡}|  
|d ¡}|d ur¸d|ff||| < | |¡ d	 |¡}|  
|d ¡}|d urßd|ff|d || d tdƒ … ¡< | |¡ d
 |¡}|  
|d ¡}|d urüd|ff||| < | |¡ q|r|  ¡ D ]}||vrt d |¡¡ q|S )Nz{}.alphaz{}.dora_scalez	{}.w_normz	{}.b_normÚdiffz{}.biasú.weightz{}.diffz	{}.diff_bz{}.set_weightÚsetzlora key not loaded: {})r   ÚformatÚkeysÚitemÚaddÚweight_adapterÚadaptersÚloadÚupdateÚloaded_keysÚgetÚlenÚloggingÚwarning)ÚloraÚto_loadÚlog_missingÚ
patch_dictr   ÚxÚ
alpha_nameÚalphaÚdora_scale_nameÚ
dora_scaleÚadapter_clsÚadapterÚw_norm_nameÚb_norm_nameÚw_normÚb_normÚ	diff_nameÚdiff_weightÚdiff_bias_nameÚ	diff_biasÚset_weight_nameÚ
set_weight© r.   ú(/mnt/c/Users/fbmor/ComfyUI/comfy/lora.pyÚ	load_lora%   sh   




ý



&


&


€
€r0   c              
   C  sî  |   ¡  ¡ }|D ]3}| d¡r;||d |d tdƒ … ¡< | d¡}|dkr;| d¡s;||d ||d tdƒ … ¡< qd}d}d}td	ƒD ]¨}tD ]£}	d
 ||	¡}||v rx| |t|	 ¡}
|||
< d |t|	 ¡}
|||
< d ||	¡}
|||
< d ||	¡}||v r¦| |t|	 ¡}
|||
< d |t|	 ¡}
|||
< d}d ||	¡}
|||
< d ||	¡}||v ríd}|rËd |t|	 ¡}
|||
< d ||	¡}
|||
< qJd |t|	 ¡}
|||
< d ||	¡}
|||
< d |t|	 ¡}
|||
< qJqF|D ]i}| d¡rZ| d¡r<|tdƒtdƒ … }d}|r|d7 }|r/|d7 }|dkr/||d || 	dd¡¡< |d7 }||d || 	dd¡¡< qñ| d¡rZ|tdƒtdƒ … }d | 	dd¡¡}
|||
< qñd}||v rj||d< ||d< d}||v ru||d< |S )Nr
   ztext_encoders.{}z.transformer.r   Úclip_é   z'lora_te_text_model_encoder_layers_{}_{}Fé    z9clip_h.transformer.text_model.encoder.layers.{}.{}.weightz(lora_te1_text_model_encoder_layers_{}_{}z,text_encoder.text_model.encoder.layers.{}.{}z9clip_l.transformer.text_model.encoder.layers.{}.{}.weightTz9clip_g.transformer.text_model.encoder.layers.{}.{}.weightz(lora_te2_text_model_encoder_layers_{}_{}z.text_encoder_2.text_model.encoder.layers.{}.{}z-lora_prior_te_text_model_encoder_layers_{}_{}zt5xxl.transformer.é   zlora_te{}_{}Ú.Ú_zhydit_clip.transformer.bert.zlora_te1_{}z)clip_g.transformer.text_projection.weightÚlora_prior_te_text_projectionÚlora_te2_text_projectionz)clip_l.transformer.text_projection.weightÚlora_te1_text_projection)
Ú
state_dictr   Úendswithr   r   ÚfindÚ
startswithÚrangeÚLORA_CLIP_MAPÚreplace)ÚmodelÚkey_mapÚsdkÚkÚtpÚtext_model_lora_keyÚclip_l_presentÚclip_g_presentÚbÚcÚlora_keyÚl_keyÚt5_indexr.   r.   r/   Úmodel_lora_keys_clipa   s   

 €
€Þ$
€

rN   c              	   C  sÞ  |   ¡ }| ¡ }|D ]8}| d¡rB| d¡r;|tdƒtdƒ …  dd¡}||d |¡< ||d |d tdƒ … ¡< q
||d |¡< q
tj 	| j
j¡}|D ]R}| d¡rŸd || ¡}|d tdƒ …  dd¡}||d |¡< ||d |¡< d	d
g}|D ]"}	d |	|d tdƒ …  dd¡¡}
|
 d¡rš|
d d… }
|||
< q|qMt| tjjƒrÌ|D ]"}| d¡rË| d¡rË|tdƒtdƒ …  dd¡}||d |¡< q©t| tjjƒr5tjj| j
jdd}|D ]T}| d¡r4|| }d |d tdƒ … ¡}|||< d |d tdƒ … ¡}|||< d |d tdƒ …  dd¡¡}|||< d |d tdƒ …  dd¡¡}|||< qàt| tjjƒrgtjj| j
jdd}|D ]}| d¡re|| }d |d tdƒ … ¡}|||< qIt| tjjƒr¹tjj| j
jdd}|D ]=}| d¡r·|| }d |d tdƒ … ¡}|||< d |d tdƒ … ¡}|||< d |d tdƒ … ¡}|||< q{t| tjjƒrå|D ]!}| d¡rã| d¡rã|tdƒtdƒ … }||d |¡< qÃt| tjjƒrotjj| j
jdd}|D ]J}| d¡rB|| }||d |d tdƒ … ¡< ||d |d tdƒ …  dd¡¡< ||d |d tdƒ …  dd¡¡< |||d tdƒ … < qù|D ](}| j
j dd¡}| d¡rmd|v rm|dd|d ff|d | dd¡¡< qFt| tjjƒr›|D ]!}| d¡r™| d¡r™|tdƒtdƒ … }||d |¡< qyt| tjjƒrî|D ]H}| d¡rì| d¡rì|}| dd¡ dd¡ d d!¡}| d"d#¡ d$d%¡}| d&d'¡}|tdƒtdƒ … }||d |¡< ||d |¡< q¥t| tjjƒr%|D ],}| d¡r#| d¡r#|tdƒtdƒ … }||d | dd¡¡< ||d |¡< qøt| tjjƒrQ|D ]!}| d¡rO| d¡rO|tdƒtdƒ … }||d |¡< q/t| tjjƒr}|D ]!}| d¡r{| d¡r{|tdƒtdƒ … }||d |¡< q[t| tjjƒr»|D ]3}| d¡r¹| d¡r¹|tdƒtdƒ … }||d |¡< ||d |¡< ||d | dd¡¡< q‡t| tjjƒrtjj | j
jdd}|D ]3}| d¡r|| }|d tdƒ … }||d |¡< ||d |¡< ||d | dd¡¡< |||< qÏt| tjj!ƒr6|D ](}| d¡r4| d¡r4|tdƒtdƒ … }||d |¡< ||d |¡< qt| tjj"ƒrm|D ],}| d(¡rk| d¡rk|td(ƒtdƒ … }||d |¡< ||d | dd¡¡< q@|S ))Nzdiffusion_model.r
   r5   r6   zlora_unet_{}z{}zdiffusion_model.{}z
lycoris_{}Ú zunet.z{}{}z.to_z.processor.to_z	.to_out.0éþÿÿÿzlora_prior_unet_{})Úoutput_prefixztransformer.{}zbase_model.model.{}zlora_transformer_{}zunet.base_model.model.{}Úhidden_sizer   z	.linear1.é   z.linear1.weightz.linear1_qkvz	_mod.lin.z_mod.linear.z
_attn.qkv.z
_attn_qkv.z_attn.proj.z_attn_proj.zmlp.0.zmlp.fc1.zmlp.2.zmlp.fc2.z.modulation.lin.z.modulation.linear.zdiffusion_model.decoder.)#r:   r   r=   r;   r   r@   r   ÚcomfyÚutilsÚunet_to_diffusersÚmodel_configÚunet_configÚ
isinstanceÚ
model_baseÚStableCascade_CÚSD3Úmmdit_to_diffusersÚAuraFlowÚauraflow_to_diffusersÚPixArtÚpixart_to_diffusersÚ
HunyuanDiTÚFluxÚflux_to_diffusersr   Ú
GenmoMochiÚHunyuanVideoÚHiDreamÚACEStepÚOmnigen2Ú	QwenImageÚLumina2Úz_image_to_diffusersÚ
Kandinsky5Ú	ACEStep15)rA   rB   ÚsdrC   rD   Úkey_loraÚdiffusers_keysÚunet_keyÚdiffusers_lora_prefixÚpÚdiffusers_lora_keyÚtorR   r.   r.   r/   Úmodel_lora_keys_unet²   s:  

€
"

€

€  €€€€$$€$€€€€€€€€€€rw   Útensorútorch.TensorÚ	new_shapeú	list[int]Úreturnc                   sŽ   t ‡ ‡fdd„ttˆ ƒƒD ƒƒrtdƒ‚tˆ ƒtˆjƒkr!tdƒ‚tjˆ ˆjˆjd}t	dd„ ˆjD ƒƒ}t	dd„ ˆjD ƒƒ}ˆ| ||< |S )	aº  
    Pad a tensor to a new shape with zeros.

    Args:
        tensor (torch.Tensor): The original tensor to be padded.
        new_shape (List[int]): The desired shape of the padded tensor.

    Returns:
        torch.Tensor: A new tensor padded with zeros to the specified shape.

    Note:
        If the new shape is smaller than the original tensor in any dimension,
        the original tensor will be truncated in that dimension.
    c                   s   g | ]}ˆ | ˆj | k ‘qS r.   )Úshape)Ú.0Úi©rz   rx   r.   r/   Ú
<listcomp>k  s    z'pad_tensor_to_shape.<locals>.<listcomp>zGThe new shape must be larger than the original tensor in all dimensionszLThe new shape must have the same number of dimensions as the original tensor)ÚdtypeÚdevicec                 s  ó    | ]}t d |ƒV  qdS ©r   N©Úslice©r~   Údimr.   r.   r/   Ú	<genexpr>u  ó   € z&pad_tensor_to_shape.<locals>.<genexpr>c                 s  r„   r…   r†   rˆ   r.   r.   r/   rŠ   v  r‹   )
Úanyr>   r   Ú
ValueErrorr}   ÚtorchÚzerosr‚   rƒ   Útuple)rx   rz   Úpadded_tensorÚorig_slicesÚ
new_slicesr.   r€   r/   Úpad_tensor_to_shape\  s    r”   c                 C  s¤   |j }| D ]J}|d }|d }|d ust|tƒrqt|tjƒr+| |¡}|d ur*|}qt|ƒdkrO|d |d }	}
|	dkrOt|
ƒdkrO|
d d rO|
d j }q|S )Nr2   rS   r4   r   r	   Ú
pad_weight)r}   rY   Úlistr   ÚWeightAdapterBaseÚcalculate_shaper   )ÚpatchesÚweightÚkeyÚoriginal_weightsÚcurrent_shapert   ÚvÚoffsetÚadapter_shapeÚ
patch_typeÚ
patch_datar.   r.   r/   r˜   }  s"   
 
€r˜   c                 C  sœ  | D ]H}|d }|d }|d }|d }	|d }
|
d u r!dd„ }
d }|	d ur6|}|  |	d |	d |	d ¡}|dkr>||9 }t|tƒret|dd … |d d tjj|d d |j|d	d
d	d||df}t|tj	ƒr| |||||	|
||¡}|d u r†t
 d |j|¡¡ n|}|d urŽ|}qt|ƒdkr˜d}nt|ƒdkr¦|d }|d }|dkrü|d }t|ƒdko¹|d d }|rÔ|j|jkrÔt
 d ||j|j¡¡ t||jƒ}|dkrû|j|jkrët
 d ||j|j¡¡ nY||
|tj ||j|j¡ ƒ7 }nH|dkr	| |d ¡ n;|dkr;|d }tj ||j|¡tj || d d |j|¡ }||
|tj ||j|j¡ ƒ7 }n	t
 d ||¡¡ |d urK|}q|S )Nr   r2   r4   rS   é   c                 S  s   | S ©Nr.   )Úar.   r.   r/   Ú<lambda>ž  s    z"calculate_weight.<locals>.<lambda>g      ð?T)Úcopy)Úinplace)Úintermediate_dtypezCalculate Weight Failed: {} {}r	   r•   z"Pad weight {} from {} to shape: {}g        z4WARNING SHAPE MISMATCH {} WEIGHT NOT MERGED {} != {}r   Úmodel_as_lorazpatch type not recognized {} {})ÚnarrowrY   r–   Úcalculate_weightrT   Úmodel_managementÚcast_to_devicerƒ   r   r—   r   r   r   Únamer   r}   Úinfor”   r‚   Úcopy_)r™   rš   r›   r©   rœ   rt   Ústrengthrž   Ústrength_modelrŸ   ÚfunctionÚ
old_weightÚoutputr¡   r	   Údo_pad_weightÚtarget_weightr)   r.   r.   r/   r¬   –  sj   

D €

ÿ"
€r¬   )T)rx   ry   rz   r{   r|   ry   r¤   )Ú__doc__Ú
__future__r   Úcomfy.utilsrT   Úcomfy.model_managementÚcomfy.model_baseÚcomfy.weight_adapterr   r   rŽ   r?   r0   rN   rw   r”   r˜   Úfloat32r¬   r.   r.   r.   r/   Ú<module>   s,    ú

<Q 
+
!