o
    ٷi7                     @   s$  d dl Z d dlZd dlmZmZmZ ddlmZmZm	Z	m
Z
 ddlmZmZ d dlmZ eeZdd	ed
edefddZdded
edefddZddeeB d
edefddZdeeB deeee
 f fddZdeeB dee eB fddZ	ddeeB dedeeeee
 ef ef fddZdS )    N)TupleOptionalUnion   )DBCacheConfigTaylorSeerCalibratorConfigDBPruneConfigCalibratorConfig   )ParallelismConfigParallelismBackend)init_loggerFcache_kwargsresetreturnc              
   C   s|  zt | }i }|ddrB|s't|d|dd|dd|dddnt j|d|dd|dd|ddd|d	< d
|vr_|sKt nt  |d< |d jdi | |W S t|d
d}|dkr|spt nt  |d< |d jdi | |W S |dkr|st nt  |d< |d jdi | |W S t	d| d t
y } z	t	dt| d}~ww )a  
    Load cache options from a dictionary. We keep this function for backward compatibility.
    Args:
        cache_kwargs (`dict`):
            A dictionary containing the cache configuration.
        reset (`bool`, *optional*, defaults to `False`):
            Whether to reset the configuration to default values to None before applying the loaded settings.
            This is useful when you want to ensure that only the settings specified in the dictionary
            are applied, without retaining any previous configurations (e.g., when using ParaModifier to modify
            existing configurations).
    Returns:
        `dict`: A dictionary containing the loaded cache options.
    enable_taylorseerFenable_encoder_taylorseertaylorseer_cache_typeresidualtaylorseer_orderr   )enable_calibratorenable_encoder_calibratorcalibrator_cache_typer   calibrator_config
cache_typecache_configNDBCacheDBPrunezUnsupported cache_type: .z#Error parsing cache configuration.  )copydeepcopygetr   r   r   updatestrr   
ValueError	Exception)r   r   kwargscache_context_kwargsr   er   r   K/home/ubuntu/.local/lib/python3.10/site-packages/cache_dit/caching/utils.pyload_cache_options_from_dict   sN   







r+   yaml_file_pathc              
   C   s   z t | d}t|}W d    n1 sw   Y  t||W S  ty.   td|   tjyD } z
tdt| d }~ww )NrConfiguration file not found: YAML file parsing error: )openyaml	safe_loadr+   FileNotFoundError	YAMLErrorr$   )r,   r   fr'   r)   r   r   r*   load_cache_options_from_yamlP   s   r6   path_or_dictc                 C   s:   t d t| trt| |S t| trt| |S td)a  
    Load cache options from a YAML file or a dictionary.
    Args:
        path_or_dict (`str` or `dict`):
            The file path to the YAML configuration file or a dictionary containing the configuration.
        reset (`bool`, *optional*, defaults to `False`):
            Whether to reset the configuration to default values to None before applying the loaded settings.
            This is useful when you want to ensure that only the settings specified in the file or dictionary
            are applied, without retaining any previous configurations (e.g., when using ParaModifier to modify
            existing configurations).
    Returns:
        `dict`: A dictionary containing the loaded cache options.
    zg`load_options` is deprecated and will be removed in future versions. Please use `load_configs` instead.EInput must be a file path (str) or a configuration dictionary (dict).)loggerwarning
isinstancer$   r6   dictr+   r%   )r7   r   r   r   r*   load_options[   s   



r=   c              
   K   s  t | trFzt| d}t|}W d   n1 sw   Y  W n3 ty/   td|   tjyE } z
tdt| d}~ww t | trQt	| }nt
dd|vrd|v r_dS t||d	d
}|dd}|dd}|du r|t
d||fS |d }d|v r|d }	t |	trd|v sJ dddlm}
 |d }|
||	d|d< t||d	d
}|dd}|dd}|du rt
d||fS )an  
    New APU that only load cache configuration from a YAML file or a dictionary. Assumes
    that the yaml contains a 'cache_config' section, and returns only that section.
    Raise ValueError if not found.
    Args:
        path_or_dict (`str` or `dict`):
            The file path to the YAML configuration file or a dictionary containing the configuration.
        reset (`bool`, *optional*, defaults to `False`):
            Whether to reset the configuration to default values to None before applying the loaded settings.
            This is useful when you want to ensure that only the settings specified in the file or dictionary
            are applied, without retaining any previous configurations (e.g., when using ParaModifier to modify
            existing configurations).
    Returns:
        `dict`: A dictionary containing the loaded cache configuration.
    r-   Nr.   r/   r8   r   parallelism_config)NNr   Fr   z(Failed to load 'cache_config'. Got None.steps_computation_masknum_inference_stepszUTo parse steps_mask from str, 'num_inference_steps' must be provided in cache_config.r   )
steps_mask)total_stepsmask_policy)r;   r$   r0   r1   r2   r3   r4   r<   r    r!   r%   r+   r"   cache_interfacerA   )r7   r'   r5   r   r)   r(   r   r   cache_config_kwargsr?   rA   r@   r   r   r*   load_cache_configv   s\   




rF   c           	   
   K   st  t | trFzt| d}t|}W d   n1 sw   Y  W n3 ty/   td|   tjyE } z
tdt| d}~ww t | trQt	| }nt
d|ddr_d|v S d|vredS |d }d	|v rx|d	 }t||d	< d
ttB dB dtt fdd}|ddrd|v r||d |d< d|v r||d |d< d|v r||d |d< tdi |}|S )a  
    Load parallelism configuration from a YAML file or a dictionary. Assumes that the yaml
    contains a 'parallelism_config' section, and returns only that section. Raise ValueError
    if not found.
    Args:
        path_or_dict (`str` or `dict`):
            The file path to the YAML configuration file or a dictionary containing the configuration.
    Returns:
        `ParallelismConfig`: An instance of ParallelismConfig containing the loaded parallelism configuration.
    r-   Nr.   r/   r8   
check_onlyFr>   backendsizer   c                 S   s   | d u rd S t | tr| S t | tr>|  dkr>dd lm} d} | r(| } | dkr3t	d | S t
d|  d | S td|  d)	Nautor   r   zvAuto parallel size selected as 1. Make sure to run with torch.distributed to utilize multiple devices for parallelism.zAuto selected parallel size to r   zInvalid parallel size value: z. Must be int or 'auto'.)r;   intr$   lowertorch.distributeddistributedis_initializedget_world_sizer9   r:   infor%   )rI   distr   r   r*   _maybe_auto_parallel_size   s"   
z:load_parallelism_config.<locals>._maybe_auto_parallel_sizeauto_parallel_sizeTulysses_size	ring_sizetp_sizer   )r;   r$   r0   r1   r2   r3   r4   r<   r    r!   r%   r"   r   from_strrK   r   r   )	r7   r'   r5   parallel_kwargsr)   parallelism_config_kwargsbackend_strrS   r>   r   r   r*   load_parallelism_config   sN   

r\   Treturn_dictc                 K   sL   t | fi |\}}t| fi |}t|trd}|r!|||dS |||fS )a  
    Load both cache and parallelism configurations from a YAML file or a dictionary. For example,
    the YAML file can be structured as follows:
    ```yaml
    cache_config:
      max_warmup_steps: 8
      warmup_interval: 2
      max_cached_steps: -1
      max_continuous_cached_steps: 2
      Fn_compute_blocks: 1
      Bn_compute_blocks: 0
      residual_diff_threshold: 0.12
      enable_taylorseer: true
      taylorseer_order: 1
    parallelism_config:
      ulysses_size: 4
      parallel_kwargs:
        attention_backend: native
        experimental_ulysses_anything: true
        experimental_ulysses_float8: true
        extra_parallel_modules: ["text_encoder", "vae"]
    ```
    Args:
        path_or_dict (`str` or `dict`):
            The file path to the YAML configuration file or a dictionary containing the configuration.
    Returns:
        `Tuple[DBCacheConfig, Optional[CalibratorConfig], ParallelismConfig]`: A tuple containing the loaded
        cache configuration, optional calibrator configuration, and parallelism configuration. If `return_dict`
        is set to `True`, returns a dictionary with keys "cache_config", "calibrator_config", and "parallelism_config".
    N)r   r   r>   )rF   r\   r;   bool)r7   r]   r'   r   r   r>   r   r   r*   load_configs  s   #

r_   )F)T)r1   r    typingr   r   r   cache_contextsr   r   r   r	   parallelismr   r   cache_dit.loggerr   __name__r9   r<   r^   r+   r$   r6   r=   rF   r\   r_   r   r   r   r*   <module>   s8    @
H

P