






import glob
import os
from typing import Dict, List, Union

import torch

from diffusers.utils import is_safetensors_available


if is_safetensors_available():
							import safetensors.torch

from huggingface_hub import snapshot_download

from diffusers import DiffusionPipeline, __version__
from diffusers.schedulers.scheduling_utils import SCHEDULER_CONFIG_NAME
from diffusers.utils import CONFIG_NAME, DIFFUSERS_CACHE, ONNX_WEIGHTS_NAME, WEIGHTS_NAME




class 							__A	(     lowercase_					):





				"""simple docstring"""







				def __init__(					self       ):




									"""simple docstring"""

									self.register_to_config()
									super().__init__()


				def  __lowercase				(					self				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									if dicta == dicta:
														return True
									else:
														__UpperCamelCase						,							__UpperCamelCase :   Optional[Any]									=self._remove_meta_keys(__UpperCamelCase       )
														__UpperCamelCase						,							__UpperCamelCase :   int									=self._remove_meta_keys(__UpperCamelCase       )
														if configa == configa:
																			print(f'Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.'       )
																			return True
									return False


				def  __lowercase				(					self				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   Dict									=[]
									__UpperCamelCase :   List[Any]									=config_dict.copy()
									for key in config_dict.keys():
														if key.startswith('_'       ):
																			temp_dict.pop(__UpperCamelCase       )
																			meta_keys.append(__UpperCamelCase       )
									return (temp_dict, meta_keys)


				@torch.no_grad()
				def  __lowercase				(					self				,    lowerCamelCase__				,    **lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   str									=kwargs.pop('cache_dir'				,    __UpperCamelCase       )
									__UpperCamelCase :   Union[str, Any]									=kwargs.pop('resume_download'				,    __UpperCamelCase       )
									__UpperCamelCase :   Tuple									=kwargs.pop('force_download'				,    __UpperCamelCase       )
									__UpperCamelCase :   Tuple									=kwargs.pop('proxies'				,    __UpperCamelCase       )
									__UpperCamelCase :   List[str]									=kwargs.pop('local_files_only'				,    __UpperCamelCase       )
									__UpperCamelCase :   Union[str, Any]									=kwargs.pop('use_auth_token'				,    __UpperCamelCase       )
									__UpperCamelCase :   List[Any]									=kwargs.pop('revision'				,    __UpperCamelCase       )
									__UpperCamelCase :   Union[str, Any]									=kwargs.pop('torch_dtype'				,    __UpperCamelCase       )
									__UpperCamelCase :   Optional[int]									=kwargs.pop('device_map'				,    __UpperCamelCase       )

									__UpperCamelCase :   Tuple									=kwargs.pop('alpha'				,    0.5       )
									__UpperCamelCase :   str									=kwargs.pop('interp'				,    __UpperCamelCase       )

									print('Received list'				,    __UpperCamelCase       )
									print(f'Combining with alpha={alpha}, interpolation mode={interp}'       )

									__UpperCamelCase :   int									=len(__UpperCamelCase       )
									# Ignore result from model_index_json comparision of the two checkpoints
									__UpperCamelCase :   List[str]									=kwargs.pop('force'				,    __UpperCamelCase       )

									# If less than 2 checkpoints, nothing to merge. If more than 3, not supported for now.
									if checkpoint_count > 3 or checkpoint_count < 2:
														raise ValueError(
														    'Received incorrect number of checkpoints to merge. Ensure that either 2 or 3 checkpoints are being'
														    ' passed.'       )

									print('Received the right number of checkpoints'       )
									# chkpt0, chkpt1 = pretrained_model_name_or_path_list[0:2]
									# chkpt2 = pretrained_model_name_or_path_list[2] if checkpoint_count == 3 else None

									# Validate that the checkpoints can be merged
									# Step 1: Load the model config and compare the checkpoints. We'll compare the model_index.json first while ignoring the keys starting with '_'
									__UpperCamelCase :   int									=[]
									for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
														__UpperCamelCase :   Union[str, Any]									=DiffusionPipeline.load_config(
														    __UpperCamelCase				,    cache_dir=__UpperCamelCase				,    resume_download=__UpperCamelCase				,    force_download=__UpperCamelCase				,    proxies=__UpperCamelCase				,    local_files_only=__UpperCamelCase				,    use_auth_token=__UpperCamelCase				,    revision=__UpperCamelCase				,    )
														config_dicts.append(__UpperCamelCase       )

									__UpperCamelCase :   Tuple									=True
									for idx in range(1				,    len(__UpperCamelCase       )       ):
														comparison_result &= self._compare_model_configs(config_dicts[idx - 1]				,    config_dicts[idx]       )
														if not force and comparison_result is False:
																			raise ValueError('Incompatible checkpoints. Please check model_index.json for the models.'       )
																			print(config_dicts[0]				,    config_dicts[1]       )
									print('Compatible model_index.json files found'       )
									# Step 2: Basic Validation has succeeded. Let's download the models and save them into our local files.
									__UpperCamelCase :   Optional[Any]									=[]
									for pretrained_model_name_or_path, config_dict in zip(__UpperCamelCase				,    __UpperCamelCase       ):
														__UpperCamelCase :   int									=[k for k in config_dict.keys() if not k.startswith('_'       )]
														__UpperCamelCase :   List[str]									=[os.path.join(__UpperCamelCase				,    '*'       ) for k in folder_names]
														allow_patterns += [
														    WEIGHTS_NAME,
														    SCHEDULER_CONFIG_NAME,
														    CONFIG_NAME,
														    ONNX_WEIGHTS_NAME,
														    DiffusionPipeline.config_name,
														]
														__UpperCamelCase :   Any									=config_dict.get('_class_name'       )
														__UpperCamelCase :   int									={'diffusers': __version__, 'pipeline_class': requested_pipeline_class}

														__UpperCamelCase :   Optional[int]									=(
														    pretrained_model_name_or_path
														    if os.path.isdir(__UpperCamelCase       )
														    else snapshot_download(
														        __UpperCamelCase				,    cache_dir=__UpperCamelCase				,    resume_download=__UpperCamelCase				,    proxies=__UpperCamelCase				,    local_files_only=__UpperCamelCase				,    use_auth_token=__UpperCamelCase				,    revision=__UpperCamelCase				,    allow_patterns=__UpperCamelCase				,    user_agent=__UpperCamelCase				,    )
														)
														print('Cached Folder'				,    __UpperCamelCase       )
														cached_folders.append(__UpperCamelCase       )

									# Step 3:-
									# Load the first checkpoint as a diffusion pipeline and modify its module state_dict in place
									__UpperCamelCase :   Optional[int]									=DiffusionPipeline.from_pretrained(
									    cached_folders[0]				,    torch_dtype=__UpperCamelCase				,    device_map=__UpperCamelCase       )
									final_pipe.to(self.device       )

									__UpperCamelCase :   List[str]									=None
									if len(__UpperCamelCase       ) > 2:
														__UpperCamelCase :   Any									=os.path.join(cached_folders[2]       )

									if interp == "sigmoid":
														__UpperCamelCase :   Tuple									=CheckpointMergerPipeline.sigmoid
									elif interp == "inv_sigmoid":
														__UpperCamelCase :   Optional[int]									=CheckpointMergerPipeline.inv_sigmoid
									elif interp == "add_diff":
														__UpperCamelCase :   List[str]									=CheckpointMergerPipeline.add_difference
									else:
														__UpperCamelCase :   Union[str, Any]									=CheckpointMergerPipeline.weighted_sum

									# Find each module's state dict.
									for attr in final_pipe.config.keys():
														if not attr.startswith('_'       ):
																			__UpperCamelCase :   int									=os.path.join(cached_folders[1]				,    __UpperCamelCase       )
																			if os.path.exists(__UpperCamelCase       ):
																								__UpperCamelCase :   List[Any]									=[
																								    *glob.glob(os.path.join(__UpperCamelCase				,    '*.safetensors'       )       ),
																								    *glob.glob(os.path.join(__UpperCamelCase				,    '*.bin'       )       ),
																								]
																								__UpperCamelCase :   int									=files[0] if len(__UpperCamelCase       ) > 0 else None
																			if len(__UpperCamelCase       ) < 3:
																								__UpperCamelCase :   Dict									=None
																			else:
																								__UpperCamelCase :   List[str]									=os.path.join(cached_folders[2]				,    __UpperCamelCase       )
																								if os.path.exists(__UpperCamelCase       ):
																													__UpperCamelCase :   Tuple									=[
																													    *glob.glob(os.path.join(__UpperCamelCase				,    '*.safetensors'       )       ),
																													    *glob.glob(os.path.join(__UpperCamelCase				,    '*.bin'       )       ),
																													]
																													__UpperCamelCase :   Optional[Any]									=files[0] if len(__UpperCamelCase       ) > 0 else None
                # For an attr if both checkpoint_path_1 and 2 are None, ignore.
                # If atleast one is present, deal with it according to interp method, of course only if the state_dict keys match.
																			if checkpoint_path_a is None and checkpoint_path_a is None:
																								print(f'Skipping {attr}: not present in 2nd or 3d model'       )
																								continue
																			try:
																								__UpperCamelCase :   List[Any]									=getattr(__UpperCamelCase				,    __UpperCamelCase       )
																								if isinstance(__UpperCamelCase				,    __UpperCamelCase       ):  # ignore requires_safety_checker boolean
																													continue
																								__UpperCamelCase :   Optional[int]									=getattr(__UpperCamelCase				,    'state_dict'       )
																								__UpperCamelCase :   Tuple									=theta_a()

																								__UpperCamelCase :   Dict									=getattr(__UpperCamelCase				,    'load_state_dict'       )
																								__UpperCamelCase :   Optional[int]									=(
																								    safetensors.torch.load_file(__UpperCamelCase       )
																								    if (is_safetensors_available() and checkpoint_path_a.endswith('.safetensors'       ))
																								    else torch.load(__UpperCamelCase				,    map_location='cpu'       )
																								)
																								__UpperCamelCase :   Tuple									=None
																								if checkpoint_path_a:
																													__UpperCamelCase :   Any									=(
																													    safetensors.torch.load_file(__UpperCamelCase       )
																													    if (is_safetensors_available() and checkpoint_path_a.endswith('.safetensors'       ))
																													    else torch.load(__UpperCamelCase				,    map_location='cpu'       )
																													)

																								if not theta_a.keys() == theta_a.keys():
																													print(f'Skipping {attr}: key mismatch'       )
																													continue
																								if theta_a and not theta_a.keys() == theta_a.keys():
																													print(f'Skipping {attr}:y mismatch'       )
																			except Exception as e:
																								print(f'Skipping {attr} do to an unexpected error: {str(__UpperCamelCase       )}'       )
																								continue
																			print(f'MERGING {attr}'       )

																			for key in theta_a.keys():
																								if theta_a:
																													__UpperCamelCase :   Any									=theta_func(theta_a[key]				,    theta_a[key]				,    theta_a[key]				,    __UpperCamelCase       )
																								else:
																													__UpperCamelCase :   str									=theta_func(theta_a[key]				,    theta_a[key]				,    __UpperCamelCase				,    __UpperCamelCase       )

																			del theta_a
																			del theta_a
																			update_theta_a(__UpperCamelCase       )

																			del theta_a
									return final_pipe


				@staticmethod
				def  __lowercase				(					lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									return ((1 - alpha) * thetaa) + (alpha * thetaa)


				@staticmethod
				def  __lowercase				(					lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									__UpperCamelCase :   int									=alpha * alpha * (3 - (2 * alpha))
									return thetaa + ((thetaa - thetaa) * alpha)


				@staticmethod
				def  __lowercase				(					lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									import math

									__UpperCamelCase :   int									=0.5 - math.sin(math.asin(1.0 - 2.0 * alpha       ) / 3.0       )
									return thetaa + ((thetaa - thetaa) * alpha)







				@staticmethod
				def  __lowercase				(					lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__				,    lowerCamelCase__       ):




									"""simple docstring"""

									return thetaa + (thetaa - thetaa) * (1.0 - alpha)








"""simple docstring"""
from functools import lru_cache






@lru_cache
def    A__							(     UpperCamelCase			):
							if not isinstance(UpperCamelCase   ,    UpperCamelCase			):
														raise TypeError("k must be an integer."			)
							if k < 0:
														raise ValueError("k integer must be greater or equal to zero."			)
							if k == 0:
														return 0
							elif k == 1:
														return 1
							else:
														return fibonacci(k - 1			) + fibonacci(k - 2			)






def    A__							(     UpperCamelCase   ,    UpperCamelCase			):
							A						=    len(UpperCamelCase			)
							# Find m such that F_m >= n where F_i is the i_th fibonacci number.
							A						=    0
							while True:
														if fibonacci(UpperCamelCase			) >= len_list:
																					A						=    i
																					break
														i += 1
							A						=    0
							while fibb_k > 0:
														A						=    min(
														    offset + fibonacci(fibb_k - 1			)   ,    len_list - 1			)  # Prevent out of range
														A						=    arr[index_k]
														if item_k_1 == val:
																					return index_k
														elif val < item_k_1:
																					fibb_k -= 1
														elif val > item_k_1:
																					offset += fibonacci(fibb_k - 1			)
																					fibb_k -= 2
							else:
														return -1


if __name__ == "__main__":
		import doctest

		doctest.testmod()


