
    
3j}F                        S SK Jr  S SKrS SKJrJr  S SKrS SKJr  S SK	J
r
  SSKJr  SSKJrJrJr  \(       a  SS	KJr  S
r\" \5      r " S S\\5      r " S S\5      rSS jrg)    )annotationsN)TYPE_CHECKINGAny)validate_hf_hub_args)Self   )ConfigMixin)
BaseOutputPushToHubMixin
get_logger
BlockStatezguider_config.jsonc                    ^  \ rS rSrSr\rSrSrSSS jjr	S r
S rS rSS	 jrSS
 jrSU 4S jjrSS jrSS jrS S jr      S!S jrS"S jrS#S jr\S$S j5       r\S$S j5       r\S%S j5       r\        S&S j5       r\          S'S j5       r\\   S(     S)S jj5       5       rS*S+S jjrSr U =r!$ ),BaseGuidance&   zGBase class providing the skeleton for implementing guidance techniques.N__guidance_identifier__c                   [         R                  S5        Xl        X l        S U l        S U l        S U l        SU l        S U l        X0l	        SUs=::  a  S:  d  O  [        SU S35      eXs=::  a  S::  d  O  [        SU SU S35      eU R                  b  [        U R                  [        5      (       d  [        S	5      eg )
NzGuiders are currently an experimental feature under active development. The API is subject to breaking changes in future releases.r                 ?z4Expected `start` to be between 0.0 and 1.0, but got .zExpected `stop` to be between z and 1.0, but got z\`_input_predictions` must be a list of required prediction names for the guidance technique.)loggerwarning_start_stop_step_num_inference_steps	_timestep_count_prepared_input_fields_enabled
ValueError_input_predictions
isinstancelist)selfstartstopenableds       X/home/wildlama/miniconda3/lib/python3.13/site-packages/diffusers/guiders/guider_utils.py__init__BaseGuidance.__init__-   s     Q	
 

)-!+/ ?Cu"s"STYSZZ[\]]$$=eWDVW[V\\]^__""**T=T=TVZ2[2[n  3\    c                P    U R                   R                  " U R                  40 UD6$ )ax  
Creates a copy of this guider instance, optionally with modified configuration parameters.

Args:
    **kwargs: Configuration parameters to override in the new instance. If no kwargs are provided,
        returns an exact copy with the same configuration.

Returns:
    A new guider instance with the same (or updated) configuration.

Example:
    ```python
    # Create a CFG guider
    guider = ClassifierFreeGuidance(guidance_scale=3.5)

    # Create an exact copy
    same_guider = guider.new()

    # Create a copy with different start step, keeping other config the same
    new_guider = guider.new(guidance_scale=5)
    ```
)	__class__from_configconfig)r%   kwargss     r)   newBaseGuidance.newE   s"    . ~~))$++@@@r,   c                    SU l         g )NFr    r%   s    r)   disableBaseGuidance.disable^   s	    r,   c                    SU l         g )NTr5   r6   s    r)   enableBaseGuidance.enablea   s	    r,   c                6    Xl         X l        X0l        SU l        g )Nr   )r   r   r   r   )r%   stepnum_inference_stepstimesteps       r)   	set_stateBaseGuidance.set_stated   s    
$7!! r,   c                    U R                   U R                  U R                  U R                  U R                  U R
                  S.nU$ )a  
Returns the current state of the guidance technique as a dictionary. The state variables will be included in
the __repr__ method. Returns:
    `dict[str, Any]`: A dictionary containing the current state variables including:
        - step: Current inference step
        - num_inference_steps: Total number of inference steps
        - timestep: Current timestep tensor
        - count_prepared: Number of times prepare_models has been called
        - enabled: Whether the guidance is enabled
        - num_conditions: Number of conditions
)r=   r>   r?   count_preparedr(   num_conditions)r   r   r   r   r    rD   )r%   states     r)   	get_stateBaseGuidance.get_statej   sB     JJ#'#<#<"22}}"11
 r,   c           	       > [         T
U ]  5       nU R                  5       n/ nUR                  5        Ho  u  pE[	        U5      nSU;   aB  UR                  S5      nUS   S-   SR                  USS  Vs/ s H  nSU-   PM
     sn5      -   nUR                  SU SU 35        Mq     SR                  U5      n	U SU	 3$ s  snf )	za
Returns a string representation of the guidance object including both config and current state.

r      Nz    z  z: z
State:
)super__repr__rF   itemsstrsplitjoinappend)r%   str_reprrE   state_lineskvv_strv_linesline	state_strr.   s             r)   rL   BaseGuidance.__repr__   s    
 7#%   KKMDAFEu}++d+
T)DIIQXYZY[Q\6]Q\v}Q\6],^^A3b01 " IIk*	:i[11 7^s   2B=c                .    U =R                   S-  sl         g)z
Prepares the models for the guidance technique on a given batch of data. This method should be overridden in
subclasses to implement specific model preparation logic.
rJ   N)r   r%   denoisers     r)   prepare_modelsBaseGuidance.prepare_models   s    
 	!r,   c                    g)a
  
Cleans up the models for the guidance technique after a given batch of data. This method should be overridden
in subclasses to implement specific model cleanup logic. It is useful for removing any hooks or other stateful
modifications made during `prepare_models`.
N r\   s     r)   cleanup_modelsBaseGuidance.cleanup_models   s     	r,   c                    [        S5      e)Nz?BaseGuidance::prepare_inputs must be implemented in subclasses.NotImplementedError)r%   datas     r)   prepare_inputsBaseGuidance.prepare_inputs   s    !"cddr,   c                    [        S5      e)NzPBaseGuidance::prepare_inputs_from_block_state must be implemented in subclasses.re   )r%   rg   input_fieldss      r)   prepare_inputs_from_block_state,BaseGuidance.prepare_inputs_from_block_state   s     ""tuur,   c                P   [        S U 5       5      (       d  [        S5      e[        U5      U R                  :w  a%  [        SU R                   S[        U5       S35      eU Vs0 s H#  n[	        X R
                  5      UR                  _M%     nnU R                  " S0 UD6$ s  snf )Nc              3  :   #    U  H  n[        US 5      v   M     g7f)
noise_predN)hasattr).0ds     r)   	<genexpr>(BaseGuidance.__call__.<locals>.<genexpr>   s     :T71l++Ts   z1Expected all data to have `noise_pred` attribute.z	Expected z data items, but got z. Please check the input data.ra   )allr!   lenrD   getattr_identifier_keyrp   forward)r%   rg   rs   forward_inputss       r)   __call__BaseGuidance.__call__   s    :T:::PQQt9+++D//00Ec$i[Pno  SWWRVQ'!%9%9:ALLHRVW||-n-- Xs   %*B#c                    [        S5      e)Nz8BaseGuidance::forward must be implemented in subclasses.re   )r%   argsr1   s      r)   rz   BaseGuidance.forward   s    !"\]]r,   c                    [        S5      e)Nz?BaseGuidance::is_conditional must be implemented in subclasses.re   r6   s    r)   is_conditionalBaseGuidance.is_conditional       !"cddr,   c                $    U R                   (       + $ )N)r   r6   s    r)   is_unconditionalBaseGuidance.is_unconditional   s    &&&&r,   c                    [        S5      e)Nz?BaseGuidance::num_conditions must be implemented in subclasses.re   r6   s    r)   rD   BaseGuidance.num_conditions   r   r,   c                t   SSK Jn  0 nUR                  5        H]  u  pg [        U[        R
                  5      (       a  XuU'   M+  [        U[        5      (       a  Xr   XV'   MH  [        S[        U5       35      e   X5U R                  '   U" S0 UD6$ ! [         a    [        R                  SU S35         M  f = f)7  
Prepares a batch of data for the guidance technique. This method is used in the `prepare_inputs` method of the
`BaseGuidance` class. It prepares the batch based on the provided tuple index.

Args:
    input_fields (`dict[str, str | tuple[str, str]]`):
        A dictionary where the keys are the names of the fields that will be used to store the data once it is
        prepared with `prepare_inputs`. The values can be either a string or a tuple of length 2, which is used
        to look up the required data provided for preparation. If a string is provided, it will be used as the
        conditional data (or unconditional if used with a guidance method that requires it). If a tuple of
        length 2 is provided, the first element must be the conditional data identifier and the second element
        must be the unconditional data identifier or None.
    data (`BlockState`):
        The input data to be prepared.
    tuple_index (`int`):
        The index to use when accessing input fields that are tuples.

Returns:
    `BlockState`: The prepared batch of data.
r   r   zInvalid value type: "`data` does not have attribute(s) , skipping.ra   )"modular_pipelines.modular_pipeliner   rM   r#   torchTensortupler!   typer   debugry   )clsrg   tuple_index
identifierr   
data_batchkeyvalues           r)   _prepare_batchBaseGuidance._prepare_batch   s    6 	D
**,JCVeU\\22&+sOu--&+&8JO$';DK=%IJJ ' +53&&''J''  VA%TUVs   #BB!B#B76B7c                \   SSK Jn  0 nUR                  5        HQ  u  px [        U[        5      (       a  [        X(5      Xg'   M*  [        U[        5      (       a  [        X(U   5      Xg'   MQ  MS     XFU R                  '   U" S0 UD6$ ! [         a    [        R                  SU S35         M  f = f)r   r   r   r   r   ra   )r   r   rM   r#   rN   rx   r   AttributeErrorr   r   ry   )	r   rk   rg   r   r   r   r   r   r   s	            r)   _prepare_batch_from_block_state,BaseGuidance._prepare_batch_from_block_state   s    8 	D
&,,.JC	VeS))&-d&:JOu--&-d+4F&GJO  / +53&&''J'' " VA%TUVs   "B%B#B+*B+c                `    U R                   " SUUSSS.UD6u  pTnU R                  " U4SU0UD6$ )a	  
Instantiate a guider from a pre-defined JSON configuration file in a local directory or Hub repository.

Parameters:
    pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
        Can be either:

            - A string, the *model id* (for example `google/ddpm-celebahq-256`) of a pretrained model hosted on
              the Hub.
            - A path to a *directory* (for example `./my_model_directory`) containing the guider configuration
              saved with [`~BaseGuidance.save_pretrained`].
    subfolder (`str`, *optional*):
        The subfolder location of a model file within a larger model repository on the Hub or locally.
    return_unused_kwargs (`bool`, *optional*, defaults to `False`):
        Whether kwargs that are not consumed by the Python class should be returned or not.
    cache_dir (`str | os.PathLike`, *optional*):
        Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
        is not used.
    force_download (`bool`, *optional*, defaults to `False`):
        Whether or not to force the (re-)download of the model weights and configuration files, overriding the
        cached versions if they exist.

    proxies (`dict[str, str]`, *optional*):
        A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
        'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
    output_loading_info(`bool`, *optional*, defaults to `False`):
        Whether or not to also return a dictionary containing missing keys, unexpected keys and error messages.
    local_files_only(`bool`, *optional*, defaults to `False`):
        Whether to only load local model weights and configuration files or not. If set to `True`, the model
        won't be downloaded from the Hub.
    token (`str` or *bool*, *optional*):
        The token to use as HTTP bearer authorization for remote files. If `True`, the token generated from
        `diffusers-cli login` (stored in `~/.huggingface`) is used.
    revision (`str`, *optional*, defaults to `"main"`):
        The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
        allowed by Git.

> [!TIP] > To use private or [gated models](https://huggingface.co/docs/hub/models-gated#gated-models), log-in
with `hf > auth login`. You can also activate the special >
["offline-mode"](https://huggingface.co/diffusers/installation.html#offline-mode) to use this method in a >
firewalled environment.

T)pretrained_model_name_or_path	subfolderreturn_unused_kwargsreturn_commit_hashr   ra   )load_configr/   )r   r   r   r   r1   r0   commit_hashs          r)   from_pretrainedBaseGuidance.from_pretrained!  sP    h '*oo '
*G!%#	'

 '
# v[<P[TZ[[r,   c                ,    U R                   " SXS.UD6  g)a  
Save a guider configuration object to a directory so that it can be reloaded using the
[`~BaseGuidance.from_pretrained`] class method.

Args:
    save_directory (`str` or `os.PathLike`):
        Directory where the configuration JSON file will be saved (will be created if it does not exist).
    push_to_hub (`bool`, *optional*, defaults to `False`):
        Whether or not to push your model to the Hugging Face Hub after saving it. You can specify the
        repository you want to push to with `repo_id` (will default to the name of `save_directory` in your
        namespace).
    kwargs (`dict[str, Any]`, *optional*):
        Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
)save_directorypush_to_hubNra   )save_config)r%   r   r   r1   s       r)   save_pretrainedBaseGuidance.save_pretrained^  s     	ZZSYZr,   )r   r    r   r   r   r   r   r   )r   r   T)r&   floatr'   r   r(   bool)r=   intr>   r   r?   ztorch.LongTensorreturnNone)r   zdict[str, Any])r   rN   )r]   ztorch.nn.Moduler   r   )rg   'BlockState'r   list['BlockState'])rg   r   rk    dict[str, str | tuple[str, str]]r   r   )rg   r   r   r   )r   r   )r   r   )r   r   )rg   z,dict[str, tuple[torch.Tensor, torch.Tensor]]r   r   r   rN   r   r   )
rk   r   rg   r   r   r   r   rN   r   r   )NNF)r   zstr | os.PathLike | Noner   z
str | Noner   r   )F)r   zstr | os.PathLiker   r   )"__name__
__module____qualname____firstlineno____doc__GUIDER_CONFIG_NAMEconfig_namer"   ry   r*   r2   r7   r:   r@   rF   rL   r^   rb   rh   rl   r|   rz   propertyr   r   rD   classmethodr   r   r   r   r   __static_attributes____classcell__)r.   s   @r)   r   r   &   s   R$K/O0A2!,22"ev v0Pv	v
.^ e e ' ' e e ((:(( (( 	((
 
(( ((T *(6*( *( 	*(
 *( 
*( *(X  CG $"	9\'?9\ 9\ 
9\  9\v[ [r,   r   c                  4    \ rS rSr% S\S'   S\S'   S\S'   Srg)	GuiderOutputip  ztorch.Tensorpredztorch.Tensor | None	pred_condpred_uncondra   N)r   r   r   r   __annotations__r   ra   r,   r)   r   r   p  s    
""$$r,   r   c                    UR                  [        [        SUR                  5      5      SS9nU R                  [        [        SU R                  5      5      SS9nXU-  -  nX%-  SU-
  U -  -   n U $ )a  
Rescales `noise_cfg` tensor based on `guidance_rescale` to improve image quality and fix overexposure. Based on
Section 3.4 from [Common Diffusion Noise Schedules and Sample Steps are
Flawed](https://huggingface.co/papers/2305.08891).

Args:
    noise_cfg (`torch.Tensor`):
        The predicted noise tensor for the guided diffusion process.
    noise_pred_text (`torch.Tensor`):
        The predicted noise tensor for the text-guided diffusion process.
    guidance_rescale (`float`, *optional*, defaults to 0.0):
        A rescale factor applied to the noise predictions.
Returns:
    noise_cfg (`torch.Tensor`): The rescaled noise prediction tensor.
rJ   T)dimkeepdim)stdr$   rangendim)	noise_cfgnoise_pred_textguidance_rescalestd_textstd_cfgnoise_pred_rescaleds         r)   rescale_noise_cfgr   v  s{      ""tE!_5I5I,J'KUY"ZHmmU1inn%= >mMG#''9: 6!>N:NR[9[[Ir,   )r   )
__future__r   ostypingr   r   r   huggingface_hub.utilsr   typing_extensionsr   configuration_utilsr	   utilsr
   r   r   r   r   r   r   r   r   r   r   ra   r,   r)   <module>r      sb    # 	 %  6 " - : : ? *  
H	G[; G[T
%: %r,   