o
    ۷i>                     @   s   d Z ddlZddlZddlZddlmZ ddlmZ ddlm	Z	m
Z
mZ ddlmZ eeZe r6ddlZdd	 Zd
d Zd(dedB fddZ	d)ddZdd Zd*ddZdd Zdd Zd+defddZdeddfd d!Z	d)d"d#Zd$d% Zd&d' Z dS ),z3
PEFT utilities: Utilities related to peft library
    N)version   )logging)is_peft_availableis_peft_versionis_torch_available)empty_device_cachec              
   C   s  ddl m} d}|  D ]}t||rt|d} nq|rTddlm} dd |  D }|D ]#}z
|| |\}}}	W n	 tyC   Y q.w t|drQt	||	|
  q.| S ddlm}
 |  D ]\}}tt| dkrpt| d}t||
rt|tjjrtjj|j|j|jd	ud
|jj}|j|_|jd	ur|j|_d}n3t||
rt|tjjrtj|j|j|j|j|j |j!|j"|jj}|j|_|jd	ur|j|_d}|rt	| || ~t#  q^| S )zd
    Recursively replace all instances of `LoraLayer` with corresponding new layers in `model`.
    r   BaseTunerLayerF
base_layer)_get_submodulesc                 S   s   g | ]
\}}d |vr|qS )lora ).0key_r   r   P/home/ubuntu/vllm_env/lib/python3.10/site-packages/diffusers/utils/peft_utils.py
<listcomp>2   s    z.recurse_remove_peft_layers.<locals>.<listcomp>)	LoraLayerN)biasT)$peft.tuners.tuners_utilsr
   modules
isinstancehasattr
peft.utilsr   named_modulesAttributeErrorsetattrget_base_layerpeft.tuners.lorar   named_childrenlenlistchildrenrecurse_remove_peft_layerstorchnnLinearin_featuresout_featuresr   toweightdeviceConv2din_channelsout_channelskernel_sizestridepaddingdilationgroupsr   )modelr
   has_base_layer_patternmoduler   key_listr   parenttargettarget_namer   namemodule_replaced
new_moduler   r   r   r$   #   sv   


.




r$   c                 C   s>   ddl m} |dkrdS |  D ]}t||r|| qdS )z
    Adjust the weightage given to the LoRA layers of the model.

    Args:
        model (`torch.nn.Module`):
            The model to scale.
        weight (`float`):
            The weight to be given to the LoRA layers.
    r   r	         ?N)r   r
   r   r   scale_layer)r5   r+   r
   r7   r   r   r   scale_lora_layersj   s   


rA   r+   c                 C   sh   ddl m} |du s|dkrdS |  D ]}t||r1|dkr%|| q|jD ]}||d q(qdS )a  
    Removes the previously passed weight given to the LoRA layers of the model.

    Args:
        model (`torch.nn.Module`):
            The model to scale.
        weight (`float`, *optional*):
            The weight to be given to the LoRA layers. If no scale is passed the scale of the lora layer will be
            re-initialized to the correct value. If 0.0 is passed, we will re-initialize the scale with the correct
            value.
    r   r	   Nr?   )r   r
   r   r   unscale_layeractive_adapters	set_scale)r5   r+   r
   r7   adapter_namer   r   r   unscale_lora_layers~   s   

rF   Tc                    s`  i }i }t |  d   tt|  dkr;t|   d d ttfdd| 	 }dd |	 D }|d urt|dkrtt| dkrt|  d d  tt fdd|	 }|rudd |	 D }nd	d |	 D }nt| 
  t d
d | D }tdd |D }	tdd |D }
 ||||	|
d}|S )Nr   r   c                       | d  kS Nr   r   x)rr   r   <lambda>       z!get_peft_kwargs.<locals>.<lambda>c                 S   s    i | ]\}}| d d |qS )z.lora_B.r   splitr   kvr   r   r   
<dictcomp>        z#get_peft_kwargs.<locals>.<dictcomp>c                    rG   rH   r   rI   )
lora_alphar   r   rL      rM   c                 S   s4   i | ]\}}d  |dd d dd|qS ).z.lora_A.r   z.alpha )joinrO   replacerP   r   r   r   rS      s    "c                 S   s4   i | ]\}}d  |dd d dd |qS )rV   z.down.r   N)rX   rO   rP   r   r   r   rS      s   4 c                 S   s   h | ]	}| d d qS )z.lorar   rN   )r   r<   r   r   r   	<setcomp>   s    z"get_peft_kwargs.<locals>.<setcomp>c                 s   s    | ]}d |v V  qdS )lora_magnitude_vectorNr   r   rQ   r   r   r   	<genexpr>   s    z"get_peft_kwargs.<locals>.<genexpr>c                 s   s"    | ]}d |v o| dV  qdS )lora_Bz.biasN)endswithr]   r   r   r   r^      s     )rK   rU   rank_patternalpha_patterntarget_modulesuse_dora	lora_bias)r"   valuesr!   setcollectionsCountermost_commondictfilteritemspopkeysany)	rank_dictnetwork_alpha_dictpeft_state_dictis_unetmodel_state_dictrE   ra   rb   rc   rd   re   lora_config_kwargsr   )rU   rK   r   get_peft_kwargs   s:   
rw   c                 C   s<   ddl m} |  D ]}t||rdt|j   S q
dS )Nr   r	   default_	default_0)r   r
   r   r   r!   rK   )r5   r
   r7   r   r   r   get_adapter_name   s   
rz   c                 C   sH   ddl m} |  D ]}t||r!t|dr|j|d q
| |_q
d S )Nr   r	   enable_adapters)enabled)r   r
   r   r   r   r{   disable_adapters)r5   r|   r
   r7   r   r   r   set_adapter_layers   s   

r~   c                 C   s   ddl m} |  D ]}t||r t|dr|| q
tdq
t| ddrAt| drC| j	|d  t
| jdkrE| `d | _d S d S d S d S )Nr   r	   delete_adapterzdThe version of PEFT you are using is not compatible, please use a version that is greater than 0.6.1_hf_peft_config_loadedFpeft_config)r   r
   r   r   r   r   
ValueErrorgetattrr   rn   r!   r   )r5   rE   r
   r7   r   r   r   delete_adapter_layers   s    

	
r   c           	      C   sv   ddl m} dd }|  D ]*\}}t||r8t|dr"|| n||_t||D ]\}}||||| q*qd S )Nr   r	   c                 S   sj   t | ts| S |  D ]\}}||v r|  S q|d}|d  d|d  d|d  }| |d}|S )NrV   r   r   z.attentions.   r?   )r   rk   rm   rO   get)weight_for_adaptermodule_name
layer_nameweight_partsr   block_weightr   r   r   get_module_weight   s   

 z<set_weights_and_activate_adapters.<locals>.get_module_weightset_adapter)	r   r
   r   r   r   r   active_adapterziprD   )	r5   adapter_namesweightsr
   r   r   r7   rE   r+   r   r   r   !set_weights_and_activate_adapters   s   

r   joint_attention_kwargskwargs_namec                    s    fdd}|S )a(  
    Decorator to automatically handle LoRA layer scaling/unscaling in forward methods.

    This decorator extracts the `lora_scale` from the specified kwargs parameter, applies scaling before the forward
    pass, and ensures unscaling happens after, even if an exception occurs.

    Args:
        kwargs_name (`str`, defaults to `"joint_attention_kwargs"`):
            The name of the keyword argument that contains the LoRA scale. Common values include
            "joint_attention_kwargs", "attention_kwargs", "cross_attention_kwargs", etc.
    c                    s   t   fdd}|S )Nc              	      s   ddl m} d}|}|d ur.| }||< |dd}|s.|dkr.td d |r5t| | z | g|R i |}|W |rKt| | S S |rTt| | w w )Nr   )USE_PEFT_BACKENDr?   scalezPassing `scale` via `z1` when not using the PEFT backend is ineffective.)	rW   r   r   copyrn   loggerwarningrA   rF   )selfargskwargsr   
lora_scaleattention_kwargsresult)
forward_fnr   r   r   wrapper$  s*   


z4apply_lora_scale.<locals>.decorator.<locals>.wrapper)	functoolswraps)r   r   r   )r   r   	decorator#  s   z#apply_lora_scale.<locals>.decoratorr   )r   r   r   r   r   apply_lora_scale  s   !r   min_versionreturnc                 C   s@   t  stdttjdt| k}|std|  dS )z
    Checks if the version of PEFT is compatible.

    Args:
        version (`str`):
            The version of PEFT to check against.
    z@PEFT is not installed. Please install it with `pip install peft`peftz_The version of PEFT you are using is not compatible, please use a version that is greater than N)r   r   r   parse	importlibmetadata)r   is_peft_version_compatibler   r   r   check_peft_versionG  s   r   c           
   
   C   s   ddl m} |d ur|}n
t||| |||d}t| d|v r,|d r,tddr,tdd|v r=|d r=td	d
r=tdz|di |W S  tyV }	 ztd|	d }	~	ww )Nr   )
LoraConfig)rr   rs   rt   ru   rE   rd   <z0.9.0z,DoRA requires PEFT >= 0.9.0. Please upgrade.re   z<=z0.13.2z2lora_bias requires PEFT >= 0.14.0. Please upgrade.z-`LoraConfig` class could not be instantiated.r   )r   r   rw   %_maybe_raise_error_for_ambiguous_keysr   r   	TypeError)

state_dictnetwork_alphasr   rank_pattern_dictrt   ru   rE   r   rv   er   r   r   _create_lora_config[  s0   	


r   c                    sh   | d   }| d }t| D ]!  fdd|D } fdd|D }|r1|r1tddr1tdqd S )	Nra   rc   c                    s   g | ]}| kr|qS r   r   r   modr   r   r   r     s    z9_maybe_raise_error_for_ambiguous_keys.<locals>.<listcomp>c                    s    g | ]} |v r| kr|qS r   r   r   r   r   r   r     rT   r   z0.14.1zzThere are ambiguous keys present in this LoRA. To load it, please update your `peft` installation - `pip install -U peft`.)r   r"   ro   r   r   )configra   rc   exact_matchessubstring_matchesr   r   r   r   }  s   
r   c                    s   d}| d ur@t | dd }|r" fdd|D }|r"dd| d}t | dd }|r@ fd	d|D }|r@|d
d| d7 }|rIt| d S d S )NrW   unexpected_keysc                        g | ]}d |v r |v r|qS lora_r   r]   rE   r   r   r     rT   z2_maybe_warn_for_unhandled_keys.<locals>.<listcomp>zSLoading adapter weights from state_dict led to unexpected keys found in the model: z, z. missing_keysc                    r   r   r   r]   r   r   r   r     rT   zJLoading adapter weights from state_dict led to missing keys in the model: rV   )r   rX   r   r   )incompatible_keysrE   warn_msgr   lora_unexpected_keysr   lora_missing_keysr   r   r   _maybe_warn_for_unhandled_keys  s,   r   )N)TNN)T)r   )!__doc__rh   r   r   	packagingr   rW   r   import_utilsr   r   r   torch_utilsr   
get_logger__name__r   r%   r$   rA   floatrF   rw   rz   r~   r   r   strr   r   r   r   r   r   r   r   r   <module>   s4   
G
2
	 1
"