

"""simple docstring"""

import random
import unittest

import numpy as np

from transformers.testing_utils import require_torch, require_vision
from transformers.utils import is_torch_available, is_vision_available

from ...test_image_processing_common import ImageProcessingSavingTestMixin, prepare_image_inputs


if is_torch_available():
							import torch

if is_vision_available():
							import PIL

							from transformers import FlavaImageProcessor
							from transformers.image_utils import PILImageResampling
							from transformers.models.flava.image_processing_flava import (
							    FLAVA_CODEBOOK_MEAN,
							    FLAVA_CODEBOOK_STD,
							    FLAVA_IMAGE_MEAN,
							    FLAVA_IMAGE_STD,
							)
else:
							a__ :	str						= None


class 			_snake_case     (						unittest.TestCase       ):







						def __init__(self     ,							UpperCAmelCase_     ,							UpperCAmelCase_=7     ,							UpperCAmelCase_=3     ,							UpperCAmelCase_=3_0     ,							UpperCAmelCase_=4_0_0     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=1 / 2_5_5     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=FLAVA_IMAGE_MEAN     ,							UpperCAmelCase_=FLAVA_IMAGE_STD     ,							UpperCAmelCase_=1_4     ,							UpperCAmelCase_=7_5     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=1_6     ,							UpperCAmelCase_=0.3     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=None     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=True     ,							UpperCAmelCase_=FLAVA_CODEBOOK_MEAN     ,							UpperCAmelCase_=FLAVA_CODEBOOK_STD     ,							)			->						Union[str, Any]:
											__lowercase												=			size if size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
											__lowercase												=			crop_size if crop_size is not None else {'''height''': 2_2_4, '''width''': 2_2_4}
											__lowercase												=			codebook_size if codebook_size is not None else {'''height''': 1_1_2, '''width''': 1_1_2}
											__lowercase												=			codebook_crop_size if codebook_crop_size is not None else {'''height''': 1_1_2, '''width''': 1_1_2}

											__lowercase												=			parent
											__lowercase												=			batch_size
											__lowercase												=			num_channels
											__lowercase												=			do_resize
											__lowercase												=			do_rescale
											__lowercase												=			rescale_factor
											__lowercase												=			min_resolution
											__lowercase												=			max_resolution
											__lowercase												=			size
											__lowercase												=			resample if resample is not None else PILImageResampling.BICUBIC
											__lowercase												=			do_normalize
											__lowercase												=			image_mean
											__lowercase												=			image_std
											__lowercase												=			do_center_crop
											__lowercase												=			crop_size

											__lowercase												=			input_size_patches
											__lowercase												=			total_mask_patches
											__lowercase												=			mask_group_max_patches
											__lowercase												=			mask_group_min_patches
											__lowercase												=			mask_group_min_aspect_ratio
											__lowercase												=			mask_group_max_aspect_ratio

											__lowercase												=			codebook_do_resize
											__lowercase												=			codebook_size
											__lowercase												=			codebook_resample if codebook_resample is not None else PILImageResampling.LANCZOS
											__lowercase												=			codebook_do_center_crop
											__lowercase												=			codebook_crop_size
											__lowercase												=			codebook_do_map_pixels
											__lowercase												=			codebook_do_normalize
											__lowercase												=			codebook_image_mean
											__lowercase												=			codebook_image_std







						def        _UpperCamelCase    (self							)			->						str:
											return {
											    "image_mean": self.image_mean,
											    "image_std": self.image_std,
											    "do_normalize": self.do_normalize,
											    "do_resize": self.do_resize,
											    "size": self.size,
											    "resample": self.resample,
											    "do_rescale": self.do_rescale,
											    "rescale_factor": self.rescale_factor,
											    "do_center_crop": self.do_center_crop,
											    "crop_size": self.crop_size,
											    "input_size_patches": self.input_size_patches,
											    "total_mask_patches": self.total_mask_patches,
											    "mask_group_max_patches": self.mask_group_max_patches,
											    "mask_group_min_patches": self.mask_group_min_patches,
											    "mask_group_min_aspect_ratio": self.mask_group_min_aspect_ratio,
											    "mask_group_max_aspect_ratio": self.mask_group_min_aspect_ratio,
											    "codebook_do_resize": self.codebook_do_resize,
											    "codebook_size": self.codebook_size,
											    "codebook_resample": self.codebook_resample,
											    "codebook_do_center_crop": self.codebook_do_center_crop,
											    "codebook_crop_size": self.codebook_crop_size,
											    "codebook_do_map_pixels": self.codebook_do_map_pixels,
											    "codebook_do_normalize": self.codebook_do_normalize,
											    "codebook_image_mean": self.codebook_image_mean,
											    "codebook_image_std": self.codebook_image_std,
											}







						def        _UpperCamelCase    (self							)			->						Optional[Any]:
											return (self.size["height"], self.size["width"])







						def        _UpperCamelCase    (self							)			->						str:
											return (
											    (self.input_size_patches, self.input_size_patches)
											    if not isinstance(self.input_size_patches     ,							UpperCAmelCase_							)
											    else self.input_size_patches
											)







						def        _UpperCamelCase    (self							)			->						Dict:
											return (self.codebook_size["height"], self.codebook_size["width"])



@require_torch
@require_vision
class 			_snake_case     (						UpperCamelCase						,			unittest.TestCase       ):
						__snake_case 			=     FlavaImageProcessor if is_vision_available() else None
						__snake_case 			=     None







						def        _UpperCamelCase    (self							)			->						Dict:
											__lowercase												=			FlavaImageProcessingTester(self							)







						@property
						def        _UpperCamelCase    (self							)			->						Any:
											return self.image_processor_tester.prepare_image_processor_dict()







						def        _UpperCamelCase    (self							)			->						Optional[int]:
											__lowercase												=			self.image_processing_class(**self.image_processor_dict							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''image_mean'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''image_std'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''do_normalize'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''do_resize'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''resample'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''crop_size'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''do_center_crop'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''do_rescale'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''rescale_factor'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''masking_generator'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_do_resize'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_size'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_resample'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_do_center_crop'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_crop_size'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_do_map_pixels'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_do_normalize'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_image_mean'''							)							)
											self.assertTrue(hasattr(UpperCAmelCase_     ,							'''codebook_image_std'''							)							)







						def        _UpperCamelCase    (self							)			->						List[str]:
											__lowercase												=			self.image_processing_class.from_dict(self.image_processor_dict							)
											self.assertEqual(image_processor.size     ,							{'''height''': 2_2_4, '''width''': 2_2_4}							)
											self.assertEqual(image_processor.crop_size     ,							{'''height''': 2_2_4, '''width''': 2_2_4}							)
											self.assertEqual(image_processor.codebook_size     ,							{'''height''': 1_1_2, '''width''': 1_1_2}							)
											self.assertEqual(image_processor.codebook_crop_size     ,							{'''height''': 1_1_2, '''width''': 1_1_2}							)

											__lowercase												=			self.image_processing_class.from_dict(
											    self.image_processor_dict     ,							size=4_2     ,							crop_size=8_4     ,							codebook_size=3_3     ,							codebook_crop_size=6_6							)
											self.assertEqual(image_processor.size     ,							{'''height''': 4_2, '''width''': 4_2}							)
											self.assertEqual(image_processor.crop_size     ,							{'''height''': 8_4, '''width''': 8_4}							)
											self.assertEqual(image_processor.codebook_size     ,							{'''height''': 3_3, '''width''': 3_3}							)
											self.assertEqual(image_processor.codebook_crop_size     ,							{'''height''': 6_6, '''width''': 6_6}							)







						def        _UpperCamelCase    (self							)			->						List[str]:
											pass







						def        _UpperCamelCase    (self							)			->						str:
											# Initialize image_processing
											__lowercase												=			self.image_processing_class(**self.image_processor_dict							)
											# create random PIL images
											__lowercase												=			prepare_image_inputs(self.image_processor_tester     ,							equal_resolution=UpperCAmelCase_							)
											for image in image_inputs:
																self.assertIsInstance(UpperCAmelCase_     ,							PIL.Image.Image							)

											# Test not batched input
											__lowercase												=			image_processing(image_inputs[0]     ,							return_tensors='''pt'''							)

											# Test no bool masked pos
											self.assertFalse('''bool_masked_pos''' in encoded_images							)

											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_image_size()

											self.assertEqual(
											    encoded_images.pixel_values.shape     ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,							)

											# Test batched
											__lowercase												=			image_processing(UpperCAmelCase_     ,							return_tensors='''pt'''							)
											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_image_size()

											# Test no bool masked pos
											self.assertFalse('''bool_masked_pos''' in encoded_images							)

											self.assertEqual(
											    encoded_images.pixel_values.shape     ,							(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )     ,							)







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)			->						Tuple:
											# Initialize image_processing
											__lowercase												=			self.image_processing_class(**self.image_processor_dict							)
											# create random tensors
											__lowercase												=			prepare_image_inputs(self.image_processor_tester     ,							equal_resolution=UpperCAmelCase_     ,							**UpperCAmelCase_							)
											for image in image_inputs:
																self.assertIsInstance(UpperCAmelCase_     ,							UpperCAmelCase_							)

											# Test not batched input
											__lowercase												=			image_processing(image_inputs[0]     ,							return_tensors='''pt'''							)

											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_image_size()
											self.assertEqual(
											    encoded_images.pixel_values.shape     ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,							)

											__lowercase												=			image_processing(UpperCAmelCase_     ,							return_image_mask=UpperCAmelCase_     ,							return_tensors='''pt'''							)

											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_image_size()
											self.assertEqual(
											    encoded_images.pixel_values.shape     ,							(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )     ,							)

											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_mask_size()
											self.assertEqual(
											    encoded_images.bool_masked_pos.shape     ,							(
											        self.image_processor_tester.batch_size,
											        expected_height,
											        expected_width,
											    )     ,							)

											# Test batched
											__lowercase												=			image_processing(UpperCAmelCase_     ,							return_tensors='''pt'''							).pixel_values

											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_image_size()
											self.assertEqual(
											    encoded_images.shape     ,							(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )     ,							)

											# Test masking
											__lowercase												=			image_processing(UpperCAmelCase_     ,							return_image_mask=UpperCAmelCase_     ,							return_tensors='''pt'''							)

											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_image_size()
											self.assertEqual(
											    encoded_images.pixel_values.shape     ,							(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )     ,							)

											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_mask_size()
											self.assertEqual(
											    encoded_images.bool_masked_pos.shape     ,							(
											        self.image_processor_tester.batch_size,
											        expected_height,
											        expected_width,
											    )     ,							)







						def        _UpperCamelCase    (self							)			->						str:
											self._test_call_framework(np.ndarray     ,							prepare_kwargs={'''numpify''': True}							)







						def        _UpperCamelCase    (self							)			->						Tuple:
											self._test_call_framework(torch.Tensor     ,							prepare_kwargs={'''torchify''': True}							)







						def        _UpperCamelCase    (self							)			->						Optional[Any]:
											# Initialize image_processing
											random.seed(1_2_3_4							)
											__lowercase												=			self.image_processing_class(**self.image_processor_dict							)
											__lowercase												=			prepare_image_inputs(self.image_processor_tester     ,							equal_resolution=UpperCAmelCase_     ,							torchify=UpperCAmelCase_							)

											# Test not batched input
											__lowercase												=			image_processing(image_inputs[0]     ,							return_image_mask=UpperCAmelCase_     ,							return_tensors='''pt'''							)
											self.assertEqual(encoded_images.bool_masked_pos.sum().item()     ,							7_5							)







						def        _UpperCamelCase    (self							)			->						Dict:
											# Initialize image_processing
											__lowercase												=			self.image_processing_class(**self.image_processor_dict							)
											# create random PIL images
											__lowercase												=			prepare_image_inputs(self.image_processor_tester     ,							equal_resolution=UpperCAmelCase_							)
											for image in image_inputs:
																self.assertIsInstance(UpperCAmelCase_     ,							PIL.Image.Image							)

											# Test not batched input
											__lowercase												=			image_processing(image_inputs[0]     ,							return_codebook_pixels=UpperCAmelCase_     ,							return_tensors='''pt'''							)
											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_codebook_image_size()
											self.assertEqual(
											    encoded_images.codebook_pixel_values.shape     ,							(1, self.image_processor_tester.num_channels, expected_height, expected_width)     ,							)

											# Test batched
											__lowercase												=			image_processing(UpperCAmelCase_     ,							return_codebook_pixels=UpperCAmelCase_     ,							return_tensors='''pt'''							)
											__lowercase						, __lowercase												=			self.image_processor_tester.get_expected_codebook_image_size()
											self.assertEqual(
											    encoded_images.codebook_pixel_values.shape     ,							(
											        self.image_processor_tester.batch_size,
											        self.image_processor_tester.num_channels,
											        expected_height,
											        expected_width,
											    )     ,							)





"""simple docstring"""

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 			_snake_case     (						UpperCamelCase       ):







						def __init__(self							)			->						Optional[Any]:
											self.register_to_config()
											super().__init__()







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)			->						List[Any]:
											if dicta == dicta:
																return True
											else:
																__lowercase						, __lowercase												=			self._remove_meta_keys(UpperCAmelCase_							)
																__lowercase						, __lowercase												=			self._remove_meta_keys(UpperCAmelCase_							)
																if configa == configa:
																					print(f'''Warning !: Mismatch in keys {meta_keysa} and {meta_keysa}.'''							)
																					return True
											return False







						def        _UpperCamelCase    (self     ,							UpperCAmelCase_							)			->						str:
											__lowercase												=			[]
											__lowercase												=			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        _UpperCamelCase    (self     ,							UpperCAmelCase_     ,							**UpperCAmelCase_							)			->						Optional[Any]:
											__lowercase												=			kwargs.pop('''cache_dir'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''resume_download'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''force_download'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''proxies'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''local_files_only'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''use_auth_token'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''revision'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''torch_dtype'''     ,							UpperCAmelCase_							)
											__lowercase												=			kwargs.pop('''device_map'''     ,							UpperCAmelCase_							)

											__lowercase												=			kwargs.pop('''alpha'''     ,							0.5							)
											__lowercase												=			kwargs.pop('''interp'''     ,							UpperCAmelCase_							)

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

											__lowercase												=			len(UpperCAmelCase_							)
											# Ignore result from model_index_json comparision of the two checkpoints
											__lowercase												=			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 '_'
											__lowercase												=			[]
											for pretrained_model_name_or_path in pretrained_model_name_or_path_list:
																__lowercase												=			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_							)

											__lowercase												=			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.
											__lowercase												=			[]
											for pretrained_model_name_or_path, config_dict in zip(UpperCAmelCase_     ,							UpperCAmelCase_							):
																__lowercase												=			[k for k in config_dict.keys() if not k.startswith('''_'''							)]
																__lowercase												=			[os.path.join(UpperCAmelCase_     ,							'''*'''							) for k in folder_names]
																allow_patterns += [
																    WEIGHTS_NAME,
																    SCHEDULER_CONFIG_NAME,
																    CONFIG_NAME,
																    ONNX_WEIGHTS_NAME,
																    DiffusionPipeline.config_name,
																]
																__lowercase												=			config_dict.get('''_class_name'''							)
																__lowercase												=			{'''diffusers''': __version__, '''pipeline_class''': requested_pipeline_class}

																__lowercase												=			(
																    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
											__lowercase												=			DiffusionPipeline.from_pretrained(
											    cached_folders[0]     ,							torch_dtype=UpperCAmelCase_     ,							device_map=UpperCAmelCase_							)
											final_pipe.to(self.device							)

											__lowercase												=			None
											if len(UpperCAmelCase_							) > 2:
																__lowercase												=			os.path.join(cached_folders[2]							)

											if interp == "sigmoid":
																__lowercase												=			CheckpointMergerPipeline.sigmoid
											elif interp == "inv_sigmoid":
																__lowercase												=			CheckpointMergerPipeline.inv_sigmoid
											elif interp == "add_diff":
																__lowercase												=			CheckpointMergerPipeline.add_difference
											else:
																__lowercase												=			CheckpointMergerPipeline.weighted_sum

											# Find each module's state dict.
											for attr in final_pipe.config.keys():
																if not attr.startswith('''_'''							):
																					__lowercase												=			os.path.join(cached_folders[1]     ,							UpperCAmelCase_							)
																					if os.path.exists(UpperCAmelCase_							):
																										__lowercase												=			[
																										    *glob.glob(os.path.join(UpperCAmelCase_     ,							'''*.safetensors'''							)							),
																										    *glob.glob(os.path.join(UpperCAmelCase_     ,							'''*.bin'''							)							),
																										]
																										__lowercase												=			files[0] if len(UpperCAmelCase_							) > 0 else None
																					if len(UpperCAmelCase_							) < 3:
																										__lowercase												=			None
																					else:
																										__lowercase												=			os.path.join(cached_folders[2]     ,							UpperCAmelCase_							)
																										if os.path.exists(UpperCAmelCase_							):
																															__lowercase												=			[
																															    *glob.glob(os.path.join(UpperCAmelCase_     ,							'''*.safetensors'''							)							),
																															    *glob.glob(os.path.join(UpperCAmelCase_     ,							'''*.bin'''							)							),
																															]
																															__lowercase												=			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:
																										__lowercase												=			getattr(UpperCAmelCase_     ,							UpperCAmelCase_							)
																										if isinstance(UpperCAmelCase_     ,							UpperCAmelCase_							):  # ignore requires_safety_checker boolean
																															continue
																										__lowercase												=			getattr(UpperCAmelCase_     ,							'''state_dict'''							)
																										__lowercase												=			theta_a()

																										__lowercase												=			getattr(UpperCAmelCase_     ,							'''load_state_dict'''							)
																										__lowercase												=			(
																										    safetensors.torch.load_file(UpperCAmelCase_							)
																										    if (is_safetensors_available() and checkpoint_path_a.endswith('''.safetensors'''							))
																										    else torch.load(UpperCAmelCase_     ,							map_location='''cpu'''							)
																										)
																										__lowercase												=			None
																										if checkpoint_path_a:
																															__lowercase												=			(
																															    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:
																															__lowercase												=			theta_func(theta_a[key]     ,							theta_a[key]     ,							theta_a[key]     ,							UpperCAmelCase_							)
																										else:
																															__lowercase												=			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        _UpperCamelCase    (UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)			->						List[Any]:
											return ((1 - alpha) * thetaa) + (alpha * thetaa)







						@staticmethod
						def        _UpperCamelCase    (UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)			->						List[Any]:
											__lowercase												=			alpha * alpha * (3 - (2 * alpha))
											return thetaa + ((thetaa - thetaa) * alpha)







						@staticmethod
						def        _UpperCamelCase    (UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)			->						List[Any]:
											import math

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







						@staticmethod
						def        _UpperCamelCase    (UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_     ,							UpperCAmelCase_							)			->						List[str]:
											return thetaa + (thetaa - thetaa) * (1.0 - alpha)


