
    (ti}F                        d dl mZ d dlZd dlmZmZ d dlZd dlmZ d dl	m
Z
 ddlmZ ddlmZmZmZ erdd	lmZ d
Z ee      Z G d dee      Z G d de      ZddZy)    )annotationsN)TYPE_CHECKINGAny)validate_hf_hub_args)Self   )ConfigMixin)
BaseOutputPushToHubMixin
get_logger
BlockStatezguider_config.jsonc                  N    e Zd ZdZeZdZdZdddZd Z	d Z
d ZddZdd	Zd fd
ZddZddZddZ	 	 	 	 	 	 ddZd dZd!dZed"d       Zed"d       Zed#d       Ze	 	 	 	 	 	 	 	 d$d       Ze	 	 	 	 	 	 	 	 	 	 d%d       Zee	 	 	 d&	 	 	 	 	 d'd              Zd(d)dZ xZS )*BaseGuidancezGBase class providing the skeleton for implementing guidance techniques.N__guidance_identifier__c                v   t         j                  d       || _        || _        d | _        d | _        d | _        d| _        d | _        || _	        d|cxk  rdk  sn t        d| d      ||cxk  rdk  sn t        d| d| d      | j                  t        | j                  t              st        d	      y )
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       m/Volumes/fast/ai/experiments/MLX_z-image/.venv/lib/python3.12/site-packages/diffusers/guiders/guider_utils.py__init__zBaseGuidance.__init__-   s     Q	
 

)-!+/ ?Cu"s"STYSZZ[\]]$$=eWDVW[V\\]^__""**T=T=TVZ2[n  3\    c                P     | j                   j                  | j                  fi |S )a  
        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(   newzBaseGuidance.newE   s$    . *t~~))$++@@@r*   c                    d| _         y )NFr   r$   s    r(   disablezBaseGuidance.disable^   s	    r*   c                    d| _         y )NTr2   r3   s    r(   enablezBaseGuidance.enablea   s	    r*   c                <    || _         || _        || _        d| _        y )Nr   )r   r   r   r   )r$   stepnum_inference_stepstimesteps       r(   	set_statezBaseGuidance.set_stated   s     
$7!! r*   c                    | j                   | j                  | j                  | j                  | j                  | j
                  d}|S )an  
        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
        )r8   r9   r:   count_preparedr'   num_conditions)r   r   r   r   r   r>   )r$   states     r(   	get_statezBaseGuidance.get_statej   sB     JJ#'#<#<"22}}"11
 r*   c           	     x   t         
|          }| j                         }g }|j                         D ]j  \  }}t	        |      }d|v r?|j                  d      }|d   dz   dj                  |dd D cg c]  }d|z   	 c}      z   }|j                  d| d|        l dj                  |      }	| d|	 S c c}w )	zq
        Returns a string representation of the guidance object including both config and current state.
        
r      Nz    z  z: z
State:
)super__repr__r@   itemsstrsplitjoinappend)r$   str_reprr?   state_lineskvv_strv_linesline	state_strr,   s             r(   rE   zBaseGuidance.__repr__   s    
 7#%   KKMDAqFEu}++d+
T)DIIQXYZY[Q\6]Q\v}Q\6],^^A3b01 " IIk*	:i[11 7^s   1B7c                .    | xj                   dz  c_         y)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.
        rC   N)r   r$   denoisers     r(   prepare_modelszBaseGuidance.prepare_models   s    
 	!r*   c                     y)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 rT   s     r(   cleanup_modelszBaseGuidance.cleanup_models   s     	r*   c                    t        d      )Nz?BaseGuidance::prepare_inputs must be implemented in subclasses.NotImplementedError)r$   datas     r(   prepare_inputszBaseGuidance.prepare_inputs   s    !"cddr*   c                    t        d      )NzPBaseGuidance::prepare_inputs_from_block_state must be implemented in subclasses.r[   )r$   r]   input_fieldss      r(   prepare_inputs_from_block_statez,BaseGuidance.prepare_inputs_from_block_state   s     ""tuur*   c                @   t        d |D              st        d      t        |      | j                  k7  r%t        d| j                   dt        |       d      |D ci c]#  }t	        || j
                        |j                  % }} | j                  di |S c c}w )Nc              3  4   K   | ]  }t        |d         yw)
noise_predN)hasattr).0ds     r(   	<genexpr>z(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.rX   )allr    lenr>   getattr_identifier_keyrd   forward)r$   r]   rg   forward_inputss       r(   __call__zBaseGuidance.__call__   s    :T::PQQt9+++D//00Ec$i[Pno  SWWRVQ'!T%9%9:ALLHRVWt||-n-- Xs   (Bc                    t        d      )Nz8BaseGuidance::forward must be implemented in subclasses.r[   )r$   argsr/   s      r(   rm   zBaseGuidance.forward   s    !"\]]r*   c                    t        d      )Nz?BaseGuidance::is_conditional must be implemented in subclasses.r[   r3   s    r(   is_conditionalzBaseGuidance.is_conditional       !"cddr*   c                    | j                    S )N)rs   r3   s    r(   is_unconditionalzBaseGuidance.is_unconditional   s    &&&&r*   c                    t        d      )Nz?BaseGuidance::num_conditions must be implemented in subclasses.r[   r3   s    r(   r>   zBaseGuidance.num_conditions   rt   r*   c                b   ddl m} i }|j                         D ]V  \  }}	 t        |t        j
                        r|||<   n0t        |t              r	||   ||<   nt        dt        |             X ||| j                  <    |di |S # t        $ r t        j                  d| d       Y w xY w)  
        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.rX   )"modular_pipelines.modular_pipeliner   rF   r"   torchTensortupler    typer   debugrl   )clsr]   tuple_index
identifierr   
data_batchkeyvalues           r(   _prepare_batchzBaseGuidance._prepare_batch   s    6 	D
**,JCVeU\\2&+JsOu-&+K&8JsO$';DK=%IJJ ' +5
3&&''J''  VA%TUVs   AB		"B.-B.c                J   ddl m} i }|j                         D ]J  \  }}	 t        |t              rt        ||      ||<   n$t        |t              rt        |||         ||<   n	 L ||| j                  <    |di |S # t        $ r t        j                  d| d       Y w xY w)ry   r   r   rz   r{   rX   )r|   r   rF   r"   rG   rk   r   AttributeErrorr   r   rl   )	r   r`   r]   r   r   r   r   r   r   s	            r(   _prepare_batch_from_block_statez,BaseGuidance._prepare_batch_from_block_state   s    8 	D
&,,.JC	VeS)&-dE&:JsOu-&-dE+4F&GJsO  / +5
3&&''J'' " VA%TUVs   AA=="B"!B"c                b     | j                   d||ddd|\  }}} | j                  |fd|i|S )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   rX   )load_configr-   )r   r   r   r   r/   r.   commit_hashs          r(   from_pretrainedzBaseGuidance.from_pretrained!  sV    h '6coo '
*G!%#	'

 '
# sv[<P[TZ[[r*   c                .     | j                   d||d| y)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_hubNrX   )save_config)r$   r   r   r/   s       r(   save_pretrainedzBaseGuidance.save_pretrained^  s     	ZKZSYZr*   )r   r   T)r%   floatr&   r   r'   bool)r8   intr9   r   r:   ztorch.LongTensorreturnNone)r   zdict[str, Any])r   rG   )rU   ztorch.nn.Moduler   r   )r]   'BlockState'r   list['BlockState'])r]   r   r`    dict[str, str | tuple[str, str]]r   r   )r]   r   r   r   )r   r   )r   r   )r   r   )r]   z,dict[str, tuple[torch.Tensor, torch.Tensor]]r   r   r   rG   r   r   )
r`   r   r]   r   r   r   r   rG   r   r   )NNF)r   zstr | os.PathLike | Noner   z
str | Noner   r   )F)r   zstr | os.PathLiker   r   ) __name__
__module____qualname____doc__GUIDER_CONFIG_NAMEconfig_namer!   rl   r)   r0   r4   r6   r;   r@   rE   rV   rY   r^   ra   ro   rm   propertyrs   rv   r>   classmethodr   r   r   r   r   __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                  ,    e Zd ZU ded<   ded<   ded<   y)GuiderOutputztorch.Tensorpredztorch.Tensor | None	pred_condpred_uncondN)r   r   r   __annotations__rX   r*   r(   r   r   p  s    
""$$r*   r   c                    |j                  t        t        d|j                              d      }| j                  t        t        d| j                              d      }| ||z  z  }||z  d|z
  | z  z   } | S )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.
    rC   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#x''9: #6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   rX   r*   r(   <module>r      sb    # 	 %  6 " - : : ? *  
H	G[; G[T
%: %r*   