
    l0jff                     .   d dl Z d dlZd dlZd dlZd dlZd dlmZmZmZm	Z	m
Z
mZm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mZmZmZmZ  e            r&d dlZej        j                                        rd dlZ e            rd dl m!Z!  e            rd dl"m#Z#  e            rd dl$Z$d	e%fd
Z&d Z'de(fdZ)	 d*dededej*        dej*        dej*        dej*        dej*        de+dee
ej*                 e
ej*                 f         fdZ,dedee(ej*        f         fdZ-ej.        fdeej/        j0        e	ej/        j0                 f         fdZ1dee(ej*        f         de(dej/        j0        fdZ2	 d+d e(d!e%d"e+d#e+d$e+f
d%Z3d,d e(fd&Z4d' Z5 G d( d)          Z6dS )-    N)AnyDictIterableListOptionalTupleUnion   )UNet2DConditionModel)SchedulerMixin)convert_state_dict_to_diffusersconvert_state_dict_to_peft	deprecateis_peft_availableis_torch_npu_availableis_torchvision_availableis_transformers_available)set_peft_model_state_dict)
transformsseedc                 0   t          j        |            t          j                             |            t          j        |            t                      r!t          j                            |            dS t          j                            |            dS )z
    Helper function for reproducible behavior to set the seed in `random`, `numpy`, `torch`.

    Args:
        seed (`int`): The seed to set.

    Returns:
        `None`
    N)	randomr   nptorchmanual_seedr   npumanual_seed_allcuda)r   s    [/home/wildlama/miniconda3/envs/lam/lib/python3.11/site-packages/diffusers/training_utils.pyset_seedr    (   s     KINN4	d )	!!$'''''
""4(((((    c                    | j         }|dz  }d|z
  dz  }|                    |j                  |                                         }t	          |j                  t	          |j                  k     r2|d         }t	          |j                  t	          |j                  k     2|                    |j                  }|                    |j                  |                                         }t	          |j                  t	          |j                  k     r2|d         }t	          |j                  t	          |j                  k     2|                    |j                  }||z  dz  }|S )a  
    Computes SNR as per
    https://github.com/TiankaiHang/Min-SNR-Diffusion-Training/blob/521b624bd70c67cee4bdf49225915f5945a872e3/guided_diffusion/gaussian_diffusion.py#L847-L849
    for the given timesteps using the provided noise scheduler.

    Args:
        noise_scheduler (`NoiseScheduler`):
            An object containing the noise schedule parameters, specifically `alphas_cumprod`, which is used to compute
            the SNR values.
        timesteps (`torch.Tensor`):
            A tensor of timesteps for which the SNR is computed.

    Returns:
        `torch.Tensor`: A tensor containing the computed SNR values for each timestep.
          ?      ?device).N   )alphas_cumprodtor&   floatlenshapeexpand)noise_scheduler	timestepsr(   sqrt_alphas_cumprodsqrt_one_minus_alphas_cumprodalphasigmasnrs           r   compute_snrr5   <   s]     %3N(#-%(>%9c$A! .00	8H0II)TZZ\\
!'
(
(3y+?+?
?
?1)< !'
(
(3y+?+?
?
?&&y77E$A$D$DIL\$D$]$]^g$h$n$n$p$p!
+1
2
2S5I5I
I
I(Ei(P% +1
2
2S5I5I
I
I)00AAE 5=Q
CJr!   interpolation_typec                    t                      st          d          | dk    rt          j        j        }n| dk    rt          j        j        }n| dk    rt          j        j        }ns| dk    rt          j        j        }n[| dk    rt          j        j        }nC| dk    rt          j        j	        }n+| dk    rt          j        j
        }nt          d	|  d
          |S )a  
    Maps a string describing an interpolation function to the corresponding torchvision `InterpolationMode` enum. The
    full list of supported enums is documented at
    https://pytorch.org/vision/0.9/transforms.html#torchvision.transforms.functional.InterpolationMode.

    Args:
        interpolation_type (`str`):
            A string describing an interpolation method. Currently, `bilinear`, `bicubic`, `box`, `nearest`,
            `nearest_exact`, `hamming`, and `lanczos` are supported, corresponding to the supported interpolation modes
            in torchvision.

    Returns:
        `torchvision.transforms.InterpolationMode`: an `InterpolationMode` enum used by torchvision's `resize`
        transform.
    zhPlease make sure to install `torchvision` to be able to use the `resolve_interpolation_mode()` function.bilinearbicubicboxnearestnearest_exacthamminglanczoszThe given interpolation mode z is not supported. Currently supported interpolation modes are `bilinear`, `bicubic`, `box`, `nearest`, `nearest_exact`, `hamming`, and `lanczos`.)r   ImportErrorr   InterpolationModeBILINEARBICUBICBOXNEARESTNEAREST_EXACTHAMMINGLANCZOS
ValueError)r6   interpolation_modes     r   resolve_interpolation_moderJ   a   s     $%% 
v
 
 	
 Z'''9B	y	(	('9A	u	$	$'9=	y	(	('9A		.	.'9G	y	(	('9A	y	(	('9An,> n n n
 
 	

 r!   r$   unetr.   r/   noisenoisy_latentstargetencoder_hidden_statesdream_detail_preservationreturnc                 L   |j                             |j                  |dddf         }d|z
  dz  }	|	|z  }
d}t          j                    5   | |||          j        }ddd           n# 1 swxY w Y   d\  }}|j        j        dk    r\|}||z
                                  }|	                    |
           |
                    |	|z            }|
                    |          }n;|j        j        dk    rt          d          t          d|j        j                   ||fS )	a  
    Implements "DREAM (Diffusion Rectification and Estimation-Adaptive Models)" from http://arxiv.org/abs/2312.00210.
    DREAM helps align training with sampling to help training be more efficient and accurate at the cost of an extra
    forward step without gradients.

    Args:
        `unet`: The state unet to use to make a prediction.
        `noise_scheduler`: The noise scheduler used to add noise for the given timestep.
        `timesteps`: The timesteps for the noise_scheduler to user.
        `noise`: A tensor of noise in the shape of noisy_latents.
        `noisy_latents`: Previously noise latents from the training loop.
        `target`: The ground-truth tensor to predict after eps is removed.
        `encoder_hidden_states`: Text embeddings from the text model.
        `dream_detail_preservation`: A float value that indicates detail preservation level.
          See reference.

    Returns:
        `tuple[torch.Tensor, torch.Tensor]`: Adjusted noisy_latents and target.
    Nr$   r#   )NNepsilonv_predictionz/DREAM has not been implemented for v-predictionzUnknown prediction type )r(   r)   r&   r   no_gradsampleconfigprediction_typedetachmul_addNotImplementedErrorrH   )rK   r.   r/   rL   rM   rN   rO   rP   r(   r1   dream_lambdapred_noisy_latents_targetpredicted_noisedelta_noises                   r    compute_dream_and_update_latentsrc      s   : %366y7GHHTXZ^`dIdeN%(>%9c$A! 12KKLD	 L LtM9.CDDKL L L L L L L L L L L L L L L +NG-::.6688&&&&**+H;+VWW**[))			/>	A	A!"STTT\O4J4Z\\]]]7""s   A++A/2A/c                     i }|                                  D ]_\  }}t          |d          rJt          |d          }|8|                                }|                                D ]\  }}||| d| <   `|S )zL
    Returns:
        A state dict containing just the LoRA parameters.
    set_lora_layer
lora_layerNz.lora.)named_moduleshasattrgetattr
state_dictitems)rK   lora_state_dictnamemodulerf   current_lora_layer_sdlora_layer_matrix_name
lora_params           r   unet_lora_state_dictrr      s    
 O**,, Z Zf6+,, 	Z 66J%(2(=(=(?(?%:O:U:U:W:W Z Z6*JOYOt$K$K3I$K$KLLr!   modelc                     t          | t                    s| g} | D ]:}|                                D ]#}|j        r|                    |          |_        $;dS )z
    Casts the training parameters of the model to the specified data type.

    Args:
        model: The PyTorch model whose parameters will be cast.
        dtype: The data type to which the model parameters will be cast.
    N)
isinstancelist
parametersrequires_gradr)   data)rs   dtypemparams       r   cast_training_paramsr}      so     eT""  - -\\^^ 	- 	-E" -"XXe__
	-- -r!   rl   prefixtext_encoderc                     fd|                                  D             }t          t          |                    }t          ||d           dS )aD  
    Sets the `lora_state_dict` into `text_encoder` coming from `transformers`.

    Args:
        lora_state_dict: The state dictionary to be set.
        prefix: String identifier to retrieve the portion of the state dict that belongs to `text_encoder`.
        text_encoder: Where the `lora_state_dict` is to be set.
    c                 p    i | ]2\  }}|                               |                    d            |3S ) )
startswithreplace).0kvr~   s      r   
<dictcomp>z5_set_state_dict_into_text_encoder.<locals>.<dictcomp>   sR       *.!QQ\\Z`MaMa99VR  "A  r!   default)adapter_nameN)rk   r   r   r   )rl   r~   r   text_encoder_state_dicts    `  r   !_set_state_dict_into_text_encoderr      so       2A2G2G2I2I   99XYp9q9qrrl,CR[\\\\\\r!   weighting_scheme
batch_size
logit_mean	logit_std
mode_scalec                 d   | dk    r>t          j        |||fd          }t           j        j                            |          }nk| dk    rNt          j        |fd          }d|z
  |t          j        t          j        |z  dz            dz  dz
  |z   z  z
  }nt          j        |fd          }|S )z
    Compute the density for sampling the timesteps when doing SD3 training.

    Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.

    SD3 paper reference: https://arxiv.org/abs/2403.03206v1.
    logit_normalcpu)meanstdsizer&   mode)r   r&   r
   r'   )	r   normalnn
functionalsigmoidrandcosmathpi)r   r   r   r   r   us         r   %compute_density_for_timestep_samplingr      s     >))LjizmTYZZZH''**	V	#	#JZM%888EJ%)DGaK!O"<"<"AA"E"IJJJZM%888Hr!   c                     | dk    r|dz                                   }n>| dk    r$dd|z  z
  d|dz  z  z   }dt          j        |z  z  }nt          j        |          }|S )z
    Computes loss weighting scheme for SD3 training.

    Courtesy: This was contributed by Rafie Walker in https://github.com/huggingface/diffusers/pull/8528.

    SD3 paper reference: https://arxiv.org/abs/2403.03206v1.
    
sigma_sqrtg       cosmapr
   r'   )r*   r   r   r   	ones_like)r   sigmas	weightingbots       r   compute_loss_weighting_for_sd3r     sr     <''T\((**			X	%	%!f*nq619},3'		OF++	r!   c                     t          j                     t          j                                        r t          j                                         dS t          j        j                                        r t          j                                         dS t                      r t          j
                                         dS dS )zV
    Runs garbage collection. Then clears the cache of the available accelerator.
    N)gccollectr   r   is_availableempty_cachebackendsmpsr   	torch_npur    r!   r   free_memoryr   "  s     JLLLz   $
     			(	(	*	* $			!	! $!!#####$ $r!   c                      e Zd ZdZ	 	 	 	 	 	 	 	 	 d"d	eej        j                 d
edede	de
deee	f         deee	f         de
dee         deeef         fdZed#d$d            Zd Zde	defdZ ej                    d	eej        j                 fd            Zd	eej        j                 ddfdZd%dZd&d%dZdefdZd	eej        j                 ddfdZd	eej        j                 ddfdZd eddfd!ZdS )'EMAModelz6
    Exponential Moving Average of models weights
    H.?        r   Fr$   UUUUUU?Nrw   decay	min_decayupdate_after_stepuse_ema_warmup	inv_gammapowerforeach	model_clsmodel_configc                    t          |t          j        j                  r+d}t	          dd|d           |                                }d}|                    dd          d	}t	          dd|d           |d         }|                    d
d          d}t	          d
d|d           |d
         }t          |          }d |D             | _        |                    dd          1d}t	          dd|d           | 	                    |d                    d| _
        || _        || _        || _        || _        || _        || _        d| _        d| _        || _        |	| _        |
| _        dS )a{  
        Args:
            parameters (Iterable[torch.nn.Parameter]): The parameters to track.
            decay (float): The decay factor for the exponential moving average.
            min_decay (float): The minimum decay factor for the exponential moving average.
            update_after_step (int): The number of steps to wait before starting to update the EMA weights.
            use_ema_warmup (bool): Whether to use EMA warmup.
            inv_gamma (float):
                Inverse multiplicative factor of EMA warmup. Default: 1. Only used if `use_ema_warmup` is True.
            power (float): Exponential factor of EMA warmup. Default: 2/3. Only used if `use_ema_warmup` is True.
            foreach (bool): Use torch._foreach functions for updating shadow parameters. Should be faster.
            device (Optional[Union[str, torch.device]]): The device to store the EMA weights on. If None, the EMA
                        weights will be stored on CPU.

        @crowsonkb's notes on EMA Warmup:
            If gamma=1 and power=1, implements a simple average. gamma=1, power=2/3 are good values for models you plan
            to train for a million or more steps (reaches decay factor 0.999 at 31.6K steps, 0.9999 at 1M steps),
            gamma=1, power=3/4 for models you plan to train for less (reaches decay factor 0.999 at 10K steps, 0.9999
            at 215.4k steps).
        zzPassing a `torch.nn.Module` to `ExponentialMovingAverage` is deprecated. Please pass the parameters of the module instead.z9passing a `torch.nn.Module` to `ExponentialMovingAverage`1.0.0Fstandard_warnT	max_valueNzCThe `max_value` argument is deprecated. Please use `decay` instead.	min_valuezGThe `min_value` argument is deprecated. Please use `min_decay` instead.c                 Z    g | ](}|                                                                 )S r   )clonerY   r   ps     r   
<listcomp>z%EMAModel.__init__.<locals>.<listcomp>t  s,    EEEQaggii..00EEEr!   r&   z=The `device` argument is deprecated. Please use `to` instead.r%   r   )ru   r   r   Moduler   rw   getrv   shadow_paramsr)   temp_stored_paramsr   r   r   r   r   r   optimization_stepcur_decay_valuer   r   r   )selfrw   r   r   r   r   r   r   r   r   r   kwargsdeprecation_messages                r   __init__zEMAModel.__init__6  s   F j%(/22 	"D   K##	    $..00J "N::k4((4"gk7,?uUUUU;'E::k4((4"kk7,?uUUUU{+I*%%
EE*EEE::h%%1"ah)<ERRRRGG6(+G,,,"&
"!2,"
!"#"(r!   rQ   c                     |                     |d          \  }}|                    |          } | |                                ||j        |          }|                    |           |S )NT)return_unused_kwargs)r   r   r   )from_configfrom_pretrainedrw   rW   load_state_dict)clspathr   r   _
ema_kwargsrs   	ema_models           r   r   zEMAModel.from_pretrained  sr    !--d-NN:))$//C((**ieldklll	!!*---r!   c                    | j         t          d          | j        t          d          | j                             | j                  }|                                 }|                    dd             |j        di | |                     |                                           |	                    |           d S )NzJ`save_pretrained` can only be used if `model_cls` was defined at __init__.zM`save_pretrained` can only be used if `model_config` was defined at __init__.r   r   )
r   rH   r   r   rj   popregister_to_configcopy_torw   save_pretrained)r   r   rs   rj   s       r   r   zEMAModel.save_pretrained  s    >!ijjj$lmmm**4+<==__&&
---  ..:...U%%''(((d#####r!   r   c                     t          d|| j        z
  dz
            }|dk    rdS | j        rdd|| j        z  z   | j         z  z
  }nd|z   d|z   z  }t          || j                  }t          || j                  }|S )zN
        Compute the decay factor for the exponential moving average.
        r   r
   r   
   )maxr   r   r   r   minr   r   )r   r   stepr   s       r   	get_decayzEMAModel.get_decay  s     1'$*@@1DEE1993 	71tdn'<#<$*"LLOO 4xBI6Ootz::ot~>>r!   c                    t          |t          j        j                  r)d}t	          dd|d           |                                }t          |          }| xj        dz  c_        |                     | j                  }|| _	        d|z
  }t          j                    }| j        r"t                      rDt          j        j                                        r!t           j                            |d           }|5  d |D             }d	 t)          | j        |          D             }t-          |          t-          |          k     r>t          j        d
 t)          | j        |          D             d |D             d           t          j        |t          j        ||          |           d d d            d S # 1 swxY w Y   d S t)          | j        |          D ]\  }}	t                      rDt          j        j                                        r!t           j                            |	d           }|5  |	j        r|                    |||	z
  z             n|                    |	           d d d            n# 1 swxY w Y   d S )NzPassing a `torch.nn.Module` to `ExponentialMovingAverage.step` is deprecated. Please pass the parameters of the module instead.z>passing a `torch.nn.Module` to `ExponentialMovingAverage.step`r   Fr   r
   )modifier_rankc                      g | ]}|j         	|S r   rx   r   r|   s     r   r   z!EMAModel.step.<locals>.<listcomp>  s     TTT@STuTTTr!   c                 &    g | ]\  }}|j         |S r   r   r   s_paramr|   s      r   r   z!EMAModel.step.<locals>.<listcomp>  s5     ! ! ! .Y^Yl!! ! !r!   c                 &    g | ]\  }}|j         |S r   r   r   s      r   r   z!EMAModel.step.<locals>.<listcomp>  s%    vvv^Webgbuvvvvr!   c                      g | ]}|j         	|S r   r   r   s     r   r   z!EMAModel.step.<locals>.<listcomp>  s     RRR5e>QRRRRr!   T)non_blocking)r2   )ru   r   r   r   r   rw   rv   r   r   r   
contextlibnullcontextr   r   transformersintegrations	deepspeedis_deepspeed_zero3_enabledzeroGatheredParameterszipr   r+   _foreach_copy__foreach_sub__foreach_subrx   sub_copy_)
r   rw   r   r   one_minus_decaycontext_managerparams_grads_params_gradr   r|   s
             r   r   zEMAModel.step  sF   j%(/22 	1D   P##	    $..00J*%%
!# t566$e)$022< 	-(** d|/H/R/m/m/o/o d"+."C"CJ^b"C"c"c   TT*TTT! !25d6H*2U2U! ! ! {##c*oo55(vvs4;Mz7Z7ZvvvRRJRRR%)    #!5#5m[#Q#QYh                    $ #&d&8*"E"E - -,.. c<3L3V3q3q3s3s c&/n&G&G]a&G&b&bO$ - -* -_%%HIIIIe,,,	- - - - - - - - - - - - - - -	- -s%   =B4F>>GG99I>>J	J	c                 R   t          |          }| j        r>t          j        d |D             d t	          | j        |          D                        dS t	          | j        |          D ]<\  }}|j                            |                    |j	                  j                   =dS )aa  
        Copy current averaged parameters into given collection of parameters.

        Args:
            parameters: Iterable of `torch.nn.Parameter`; the parameters to be
                updated with the stored moving averages. If `None`, the parameters with which this
                `ExponentialMovingAverage` was initialized will be used.
        c                     g | ]	}|j         
S r   ry   r   s     r   r   z$EMAModel.copy_to.<locals>.<listcomp>      444444r!   c                 R    g | ]$\  }}|                     |j                  j        %S r   )r)   r&   ry   r   s      r   r   z$EMAModel.copy_to.<locals>.<listcomp>  s-    iii>7EEL)).iiir!   N)
rv   r   r   r  r   r   ry   r  r)   r&   )r   rw   r   r|   s       r   r   zEMAModel.copy_to  s     *%%
< 	@ 44444iiSI[]gEhEhiii    
 #&d&8*"E"E @ @
  EL!9!9!>????@ @r!   c                 2    d | j         D             | _         dS )z
        Move internal buffers of the ExponentialMovingAverage to pinned memory. Useful for non-blocking transfers for
        offloading EMA params to the host.
        c                 6    g | ]}|                                 S r   )
pin_memoryr   s     r   r   z'EMAModel.pin_memory.<locals>.<listcomp>	  s     IIIallnnIIIr!   Nr   r   s    r   r  zEMAModel.pin_memory  s$     JId6HIIIr!   c                 @    fd| j         D             | _         dS )z
        Move internal buffers of the ExponentialMovingAverage to `device`.

        Args:
            device: like `device` argument to `torch.Tensor.to`
        c                     g | ]E}|                                 r|                               n|                              FS ))r&   rz   r   )r&   r   )is_floating_pointr)   )r   r   r&   rz   r   s     r   r   zEMAModel.to.<locals>.<listcomp>  sg     
 
 
  ""$$@ADDe,DGGGV,??
 
 
r!   Nr  )r   r&   rz   r   s    ```r   r)   zEMAModel.to  sE    
 
 
 
 
 
 '	
 
 
r!   c           	      h    | j         | j        | j        | j        | j        | j        | j        | j        dS )z
        Returns the state of the ExponentialMovingAverage as a dict. This method is used by accelerate during
        checkpointing to save the ema state dict.
        r   r   r   r   r   r   r   r   r  r  s    r   rj   zEMAModel.state_dict  s?     Z!%!7!%!7"1Z!/	
 	
 		
r!   c                 (    d |D             | _         dS )z
        Saves the current parameters for restoring later.

        Args:
            parameters: Iterable of `torch.nn.Parameter`. The parameters to be temporarily stored.
        c                 ~    g | ]:}|                                                                                                 ;S r   )rY   r   r   r   s     r   r   z"EMAModel.store.<locals>.<listcomp>4  s8    "X"X"XE5<<>>#5#5#7#7#=#=#?#?"X"X"Xr!   N)r   )r   rw   s     r   storezEMAModel.store-  s!     #Y"XZ"X"X"Xr!   c                     | j         t          d          | j        r/t          j        d |D             d | j         D                        n:t          | j         |          D ]$\  }}|j                            |j                   %d| _         dS )aG  
        Restore the parameters stored with the `store` method. Useful to validate the model with EMA parameters
        without: affecting the original optimization process. Store the parameters before the `copy_to()` method. After
        validation (or model saving), use this to restore the former parameters.

        Args:
            parameters: Iterable of `torch.nn.Parameter`; the parameters to be
                updated with the stored parameters. If `None`, the parameters with which this
                `ExponentialMovingAverage` was initialized will be used.
        NzGThis ExponentialMovingAverage has no `store()`ed weights to `restore()`c                     g | ]	}|j         
S r   r  r   s     r   r   z$EMAModel.restore.<locals>.<listcomp>F  r  r!   c                     g | ]	}|j         
S r   r  )r   c_params     r   r   z$EMAModel.restore.<locals>.<listcomp>F  s    6k6k6kw|6k6k6kr!   )r   RuntimeErrorr   r   r  r   ry   r  )r   rw   r  r|   s       r   restorezEMAModel.restore6  s     "*klll< 	/ 444446k6kSWSj6k6k6k    #&d&=z"J"J / /
  .... #'r!   rj   c                 .   t          j        |          }|                    d| j                  | _        | j        dk     s| j        dk    rt	          d          |                    d| j                  | _        t          | j        t                    st	          d          |                    d| j                  | _        t          | j        t                    st	          d          |                    d	| j
                  | _
        t          | j
        t                    st	          d
          |                    d| j                  | _        t          | j        t                    st	          d          |                    d| j                  | _        t          | j        t          t          f          st	          d          |                    d| j                  | _        t          | j        t          t          f          st	          d          |                    dd          }|]|| _        t          | j        t                     st	          d          t#          d | j        D                       st	          d          dS dS )a  
        Loads the ExponentialMovingAverage state. This method is used by accelerate during checkpointing to save the
        ema state dict.

        Args:
            state_dict (dict): EMA state. Should be an object returned
                from a call to :meth:`state_dict`.
        r   r   r$   zDecay must be between 0 and 1r   zInvalid min_decayr   zInvalid optimization_stepr   zInvalid update_after_stepr   zInvalid use_ema_warmupr   zInvalid inv_gammar   zInvalid powerr   Nzshadow_params must be a listc              3   J   K   | ]}t          |t          j                  V  d S N)ru   r   Tensorr   s     r   	<genexpr>z+EMAModel.load_state_dict.<locals>.<genexpr>|  s.      OOqz!U\22OOOOOOr!   z!shadow_params must all be Tensors)copydeepcopyr   r   rH   r   ru   r*   r   intr   r   boolr   r   r   rv   all)r   rj   r   s      r   r   zEMAModel.load_state_dictO  sM    ]:..
^^GTZ88
:tzC//<===#T^DD$.%00 	20111!+0CTE[!\!\$0#66 	:8999!+0CTE[!\!\$0#66 	:8999(nn-=t?RSS$-t44 	75666#T^DD$.5#,77 	20111^^GTZ88
$*ucl33 	._---"==$!.Dd0$77 A !?@@@OOD<NOOOOO F !DEEE %$F Fr!   )	r   r   r   Fr$   r   FNN)F)rQ   r   )rQ   N)NNF)__name__
__module____qualname____doc__r   r   r   	Parameterr*   r)  r*  r	   r   r   r   strr   classmethodr   r   r   rU   r   r   r  r)   dictrj   r  r!  r   r   r!   r   r   r   1  s         !"$'*#(#''+R) R)UX/0R) R) 	R)
 R) R) $R) UCZ R) R) C=R) 38nR) R) R) R)h     [$ $ $3 5    & U]__7-x(:; 7- 7- 7- _7-r@(58+="> @4 @ @ @ @&J J J J
 
 
 
 

D 
 
 
 
&Y); < Y Y Y Y Y'(58+="> '4 ' ' ' '2.F$ .F4 .F .F .F .F .F .Fr!   r   )r$   )NNNr$  )7r   r'  r   r   r   typingr   r   r   r   r   r   r	   numpyr   r   modelsr   
schedulersr   utilsr   r   r   r   r   r   r   r   r   r   r   peftr   torchvisionr   r   r)  r    r5   r1  rJ   r%  r*   rc   rr   float32r   r   r}   r   r   r   r   r   r   r!   r   <module>r<     s        				   D D D D D D D D D D D D D D D D D D      ( ( ( ( ( ( & & & & & &                    *EEGG  /...... '&&&&&& )3 ) ) ) )(" " "J)3 ) ) ) )h (+3# 3#
3##3# |3# <	3#
 <3# L3# !<3#  %3# 8EL!8EL#99:3# 3# 3# 3#l3 S%,=N8O    & V[Ub - -ehotEHO7L&L M - - - -"]#u|+,]69]IN] ] ] ]( tx '*8=QVkp   , S    $$ $ $LF LF LF LF LF LF LF LF LF LFr!   