




import tempfile
import unittest

from diffusers import (
    DDIMScheduler,
    DDPMScheduler,
    DPMSolverMultistepScheduler,
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    PNDMScheduler,
    logging,
)
from diffusers.configuration_utils import ConfigMixin, register_to_config
from diffusers.utils.testing_utils import CaptureLogger




class 	UpperCamelCase__			(A__  ):

    '''simple docstring'''



    lowerCamelCase_   :			Optional[int]			  =   '''config.json'''







    @register_to_config
    def __init__(					self  ,						UpperCamelCase__=2  ,						UpperCamelCase__=5  ,						UpperCamelCase__=(2, 5)  ,						UpperCamelCase__="for diffusion"  ,						UpperCamelCase__=[1, 3]  ,						)  ->   Optional[int]:
           pass




class 	UpperCamelCase__			(A__  ):

    '''simple docstring'''



    lowerCamelCase_   :			List[Any]			  =   '''config.json'''







    @register_to_config
    def __init__(					self  ,						UpperCamelCase__=2  ,						UpperCamelCase__=5  ,						UpperCamelCase__=(2, 5)  ,						UpperCamelCase__="for diffusion"  ,						UpperCamelCase__=[1, 3]  ,						)  ->   Any:
           pass




class 	UpperCamelCase__			(A__  ):

    '''simple docstring'''



    lowerCamelCase_   :			int			  =   '''config.json'''







    @register_to_config
    def __init__(					self  ,						UpperCamelCase__=2  ,						UpperCamelCase__=5  ,						UpperCamelCase__=(2, 5)  ,						UpperCamelCase__="for diffusion"  ,						UpperCamelCase__=[1, 3]  ,						UpperCamelCase__=[1, 3]  ,						)  ->   int:
           pass




class 	UpperCamelCase__			(A__  ):

    '''simple docstring'''



    lowerCamelCase_   :			Optional[int]			  =   '''config.json'''







    @register_to_config
    def __init__(					self  ,						UpperCamelCase__=2  ,						UpperCamelCase__=5  ,						UpperCamelCase__=(2, 5)  ,						UpperCamelCase__="for diffusion"  ,						UpperCamelCase__=[1, 5]  ,						UpperCamelCase__=[5, 4]  ,						)  ->   Dict:
           pass




class 	UpperCamelCase__			(unittest.TestCase  ):

    '''simple docstring'''



    def 					_lowercase  (					self  )  ->   Dict:






           with self.assertRaises(UpperCamelCase__  ):
                  ConfigMixin.load_config("dummy_path"  )







    def 					_lowercase  (					self  )  ->   Tuple:
           lowerCamelCase     :   Optional[Any]    				=      SampleObject()
           lowerCamelCase     :   Any    				=      obj.config
           assert config["a"] == 2
           assert config["b"] == 5
           assert config["c"] == (2, 5)
           assert config["d"] == "for diffusion"
           assert config["e"] == [1, 3]

           # init ignore private arguments
           lowerCamelCase     :   Any    				=      SampleObject(_name_or_path="lalala"  )
           lowerCamelCase     :   str    				=      obj.config
           assert config["a"] == 2
           assert config["b"] == 5
           assert config["c"] == (2, 5)
           assert config["d"] == "for diffusion"
           assert config["e"] == [1, 3]

           # can override default
           lowerCamelCase     :   Dict    				=      SampleObject(c=6  )
           lowerCamelCase     :   Dict    				=      obj.config
           assert config["a"] == 2
           assert config["b"] == 5
           assert config["c"] == 6
           assert config["d"] == "for diffusion"
           assert config["e"] == [1, 3]

           # can use positional arguments.
           lowerCamelCase     :   int    				=      SampleObject(1  ,						c=6  )
           lowerCamelCase     :   Dict    				=      obj.config
           assert config["a"] == 1
           assert config["b"] == 5
           assert config["c"] == 6
           assert config["d"] == "for diffusion"
           assert config["e"] == [1, 3]







    def 					_lowercase  (					self  )  ->   Dict:
           lowerCamelCase     :   int    				=      SampleObject()
           lowerCamelCase     :   Any    				=      obj.config

           assert config["a"] == 2
           assert config["b"] == 5
           assert config["c"] == (2, 5)
           assert config["d"] == "for diffusion"
           assert config["e"] == [1, 3]

           with tempfile.TemporaryDirectory() as tmpdirname:
                  obj.save_config(UpperCamelCase__  )
                  lowerCamelCase     :   Union[str, Any]    				=      SampleObject.from_config(SampleObject.load_config(UpperCamelCase__  )  )
                  lowerCamelCase     :   Optional[int]    				=      new_obj.config

           # unfreeze configs
           lowerCamelCase     :   List[Any]    				=      dict(UpperCamelCase__  )
           lowerCamelCase     :   Any    				=      dict(UpperCamelCase__  )

           assert config.pop("c"  ) == (2, 5)  # instantiated as tuple
           assert new_config.pop("c"  ) == [2, 5]  # saved & loaded as list because of json
           config.pop("_use_default_values"  )
           assert config == new_config







    def 					_lowercase  (					self  )  ->   Dict:
           lowerCamelCase     :   List[Any]    				=      logging.get_logger("diffusers.configuration_utils"  )
           # 30 for warning
           logger.setLevel(30  )

           with CaptureLogger(UpperCamelCase__  ) as cap_logger:
                  lowerCamelCase     :   Optional[int]    				=      DDIMScheduler.from_pretrained(
                      "hf-internal-testing/tiny-stable-diffusion-torch"  ,						subfolder="scheduler"  )

           assert ddim.__class__ == DDIMScheduler
           # no warning should be thrown
           assert cap_logger.out == ""







    def 					_lowercase  (					self  )  ->   Dict:
           lowerCamelCase     :   Optional[Any]    				=      logging.get_logger("diffusers.configuration_utils"  )
           # 30 for warning
           logger.setLevel(30  )

           with CaptureLogger(UpperCamelCase__  ) as cap_logger:
                  lowerCamelCase     :   Tuple    				=      EulerDiscreteScheduler.from_pretrained(
                      "hf-internal-testing/tiny-stable-diffusion-torch"  ,						subfolder="scheduler"  )

           assert euler.__class__ == EulerDiscreteScheduler
           # no warning should be thrown
           assert cap_logger.out == ""







    def 					_lowercase  (					self  )  ->   Any:
           lowerCamelCase     :   List[Any]    				=      logging.get_logger("diffusers.configuration_utils"  )
           # 30 for warning
           logger.setLevel(30  )

           with CaptureLogger(UpperCamelCase__  ) as cap_logger:
                  lowerCamelCase     :   Any    				=      EulerAncestralDiscreteScheduler.from_pretrained(
                      "hf-internal-testing/tiny-stable-diffusion-torch"  ,						subfolder="scheduler"  )

           assert euler.__class__ == EulerAncestralDiscreteScheduler
           # no warning should be thrown
           assert cap_logger.out == ""







    def 					_lowercase  (					self  )  ->   List[str]:
           lowerCamelCase     :   Any    				=      logging.get_logger("diffusers.configuration_utils"  )
           # 30 for warning
           logger.setLevel(30  )

           with CaptureLogger(UpperCamelCase__  ) as cap_logger:
                  lowerCamelCase     :   str    				=      PNDMScheduler.from_pretrained(
                      "hf-internal-testing/tiny-stable-diffusion-torch"  ,						subfolder="scheduler"  )

           assert pndm.__class__ == PNDMScheduler
           # no warning should be thrown
           assert cap_logger.out == ""







    def 					_lowercase  (					self  )  ->   Tuple:
           lowerCamelCase     :   Union[str, Any]    				=      logging.get_logger("diffusers.configuration_utils"  )
           # 30 for warning
           logger.setLevel(30  )

           with CaptureLogger(UpperCamelCase__  ) as cap_logger:
                  lowerCamelCase     :   Dict    				=      DDPMScheduler.from_pretrained(
                      "hf-internal-testing/tiny-stable-diffusion-torch"  ,						subfolder="scheduler"  ,						prediction_type="sample"  ,						beta_end=8  ,						)

           with CaptureLogger(UpperCamelCase__  ) as cap_logger_a:
                  lowerCamelCase     :   str    				=      DDPMScheduler.from_pretrained("google/ddpm-celebahq-256"  ,						beta_start=88  )

           assert ddpm.__class__ == DDPMScheduler
           assert ddpm.config.prediction_type == "sample"
           assert ddpm.config.beta_end == 8
           assert ddpm_a.config.beta_start == 88

           # no warning should be thrown
           assert cap_logger.out == ""
           assert cap_logger_a.out == ""







    def 					_lowercase  (					self  )  ->   Tuple:
           lowerCamelCase     :   List[str]    				=      logging.get_logger("diffusers.configuration_utils"  )
           # 30 for warning
           logger.setLevel(30  )

           with CaptureLogger(UpperCamelCase__  ) as cap_logger:
                  lowerCamelCase     :   int    				=      DPMSolverMultistepScheduler.from_pretrained(
                      "hf-internal-testing/tiny-stable-diffusion-torch"  ,						subfolder="scheduler"  )

           assert dpm.__class__ == DPMSolverMultistepScheduler
           # no warning should be thrown
           assert cap_logger.out == ""







    def 					_lowercase  (					self  )  ->   List[str]:
           lowerCamelCase     :   List[str]    				=      SampleObject()

           lowerCamelCase     :   str    				=      {k: v for k, v in config.config.items() if not k.startswith("_"  )}

           # make sure that default config has all keys in `_use_default_values`
           assert set(config_dict.keys()  ) == set(config.config._use_default_values  )

           with tempfile.TemporaryDirectory() as tmpdirname:
                  config.save_config(UpperCamelCase__  )

                  # now loading it with SampleObject2 should put f into `_use_default_values`
                  lowerCamelCase     :   Dict    				=      SampleObjecta.from_config(UpperCamelCase__  )

                  assert "f" in config._use_default_values
                  assert config.f == [1, 3]

           # now loading the config, should **NOT** use [1, 3] for `f`, but the default [1, 4] value
           # **BECAUSE** it is part of `config._use_default_values`
           lowerCamelCase     :   Dict    				=      SampleObjecta.from_config(config.config  )
           assert new_config.f == [5, 4]

           config.config._use_default_values.pop()
           lowerCamelCase     :   Tuple    				=      SampleObjecta.from_config(config.config  )
           assert new_config_a.f == [1, 3]

           # Nevertheless "e" should still be correctly loaded to [1, 3] from SampleObject2 instead of defaulting to [1, 5]
           assert new_config_a.e == [1, 3]












import enum
import inspect
from typing import Iterable, List, Optional, Tuple, Union




class 	UpperCamelCase__			(enum.Enum  ):

    '''simple docstring'''



    lowerCamelCase_   :			Tuple			  =   """timm"""
    lowerCamelCase_   :			Union[str, Any]			  =   """transformers"""




def   A   (   _SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE					)			->				Optional[int]:
       if stage_names is None:
              raise ValueError("Stage_names must be set for transformers backbones"					)

       if out_features is not None:
              if not isinstance(_SCREAMING_SNAKE_CASE				,(list,)					):
                     raise ValueError(f'''out_features must be a list {type(_SCREAMING_SNAKE_CASE					)}'''					)
              if any(feat not in stage_names for feat in out_features					):
                     raise ValueError(f'''out_features must be a subset of stage_names: {stage_names} got {out_features}'''					)

       if out_indices is not None:
              if not isinstance(_SCREAMING_SNAKE_CASE				,(list, tuple)					):
                     raise ValueError(f'''out_indices must be a list or tuple, got {type(_SCREAMING_SNAKE_CASE					)}'''					)
              if any(idx >= len(_SCREAMING_SNAKE_CASE					) for idx in out_indices					):
                     raise ValueError("out_indices must be valid indices for stage_names {stage_names}, got {out_indices}"					)

       if out_features is not None and out_indices is not None:
              if len(_SCREAMING_SNAKE_CASE					) != len(_SCREAMING_SNAKE_CASE					):
                     raise ValueError("out_features and out_indices should have the same length if both are set"					)
              if out_features != [stage_names[idx] for idx in out_indices]:
                     raise ValueError("out_features and out_indices should correspond to the same stages if both are set"					)

def   A   (   _SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE				,)			->				Optional[Any]:
       if out_indices is None and out_features is None:
              lowerCamelCase     :   Dict    				=      [len(_SCREAMING_SNAKE_CASE					) - 1]
              lowerCamelCase     :   Tuple    				=      [stage_names[-1]]
       elif out_indices is None and out_features is not None:
              lowerCamelCase     :   List[Any]    				=      [stage_names.index(_SCREAMING_SNAKE_CASE					) for layer in out_features]
       elif out_features is None and out_indices is not None:
              lowerCamelCase     :   Union[str, Any]    				=      [stage_names[idx] for idx in out_indices]
       return out_features, out_indices

def   A   (   _SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE				,_SCREAMING_SNAKE_CASE				,)			->				Tuple[List[str], List[int]]:
       verify_out_features_out_indices(out_features=_SCREAMING_SNAKE_CASE				,out_indices=_SCREAMING_SNAKE_CASE				,stage_names=_SCREAMING_SNAKE_CASE					)
       lowerCamelCase				,   lowerCamelCase     :   str    				=      _align_output_features_output_indices(
           out_features=_SCREAMING_SNAKE_CASE				,out_indices=_SCREAMING_SNAKE_CASE				,stage_names=_SCREAMING_SNAKE_CASE					)
       # Verify that the aligned out_features and out_indices are valid
       verify_out_features_out_indices(out_features=_SCREAMING_SNAKE_CASE				,out_indices=_SCREAMING_SNAKE_CASE				,stage_names=_SCREAMING_SNAKE_CASE					)
       return output_features, output_indices




class 	UpperCamelCase__			:

    '''simple docstring'''



    lowerCamelCase_   :			Optional[BackboneType]			  =   None







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   None:
           if getattr(self  ,						"_backbone"  ,						UpperCamelCase__  ) is None:
                  raise ValueError("self._backbone must be set before calling _init_timm_backbone"  )

           # These will diagree with the defaults for the transformers models e.g. for resnet50
           # the transformer model has out_features = ['stem', 'stage1', 'stage2', 'stage3', 'stage4']
           # the timm model has out_features = ['act', 'layer1', 'layer2', 'layer3', 'layer4']
           lowerCamelCase     :   Any    				=      [stage["module"] for stage in self._backbone.feature_info.info]
           lowerCamelCase     :   Optional[int]    				=      [stage["num_chs"] for stage in self._backbone.feature_info.info]
           lowerCamelCase     :   str    				=      self._backbone.feature_info.out_indices
           lowerCamelCase     :   Any    				=      self._backbone.feature_info.module_name()

           # We verify the out indices and out features are valid
           verify_out_features_out_indices(
               out_features=UpperCamelCase__  ,						out_indices=UpperCamelCase__  ,						stage_names=self.stage_names  )
           lowerCamelCase				,   lowerCamelCase     :   Tuple    				=      out_features, out_indices







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   None:
           lowerCamelCase     :   Optional[int]    				=      getattr(UpperCamelCase__  ,						"stage_names"  )
           lowerCamelCase     :   Optional[int]    				=      getattr(UpperCamelCase__  ,						"out_features"  ,						UpperCamelCase__  )
           lowerCamelCase     :   Union[str, Any]    				=      getattr(UpperCamelCase__  ,						"out_indices"  ,						UpperCamelCase__  )

           lowerCamelCase     :   List[Any]    				=      stage_names
           lowerCamelCase				,   lowerCamelCase     :   Dict    				=      get_aligned_output_features_output_indices(
               out_features=UpperCamelCase__  ,						out_indices=UpperCamelCase__  ,						stage_names=UpperCamelCase__  )
           # Number of channels for each stage. This is set in the transformer backbone model init
           lowerCamelCase     :   Tuple    				=      None







    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   None:
           lowerCamelCase     :   Any    				=      config

           lowerCamelCase     :   Any    				=      getattr(UpperCamelCase__  ,						"use_timm_backbone"  ,						UpperCamelCase__  )
           lowerCamelCase     :   int    				=      BackboneType.TIMM if self.use_timm_backbone else BackboneType.TRANSFORMERS

           if self.backbone_type == BackboneType.TIMM:
                  self._init_timm_backbone(UpperCamelCase__  )
           elif self.backbone_type == BackboneType.TRANSFORMERS:
                  self._init_transformers_backbone(UpperCamelCase__  )
           else:
                  raise ValueError(F'''backbone_type {self.backbone_type} not supported.'''  )







    @property
    def 					_lowercase  (					self  )  ->   Optional[Any]:
           return self._out_features







    @out_features.setter
    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Union[str, Any]:
           lowerCamelCase				,   lowerCamelCase     :   Dict    				=      get_aligned_output_features_output_indices(
               out_features=UpperCamelCase__  ,						out_indices=UpperCamelCase__  ,						stage_names=self.stage_names  )







    @property
    def 					_lowercase  (					self  )  ->   Optional[Any]:
           return self._out_indices







    @out_indices.setter
    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   List[str]:
           lowerCamelCase				,   lowerCamelCase     :   int    				=      get_aligned_output_features_output_indices(
               out_features=UpperCamelCase__  ,						out_indices=UpperCamelCase__  ,						stage_names=self.stage_names  )







    @property
    def 					_lowercase  (					self  )  ->   Tuple:
           # the current backbones will output the number of channels for each stage
           # even if that stage is not in the out_features list.
           return {stage: self.num_features[i] for i, stage in enumerate(self.stage_names  )}







    @property
    def 					_lowercase  (					self  )  ->   List[Any]:
           return [self.out_feature_channels[name] for name in self.out_features]







    def 					_lowercase  (					self  ,						*UpperCamelCase__  ,						**UpperCamelCase__  )  ->   Tuple:
           lowerCamelCase     :   Union[str, Any]    				=      dict(inspect.signature(self.forward  ).parameters  )
           lowerCamelCase     :   Optional[int]    				=      {k: v for k, v in kwargs.items() if k in signature}
           return self(*UpperCamelCase__  ,						**UpperCamelCase__  )







    def 					_lowercase  (					self  ,						UpperCamelCase__  ,						UpperCamelCase__ = None  ,						UpperCamelCase__ = None  ,						UpperCamelCase__ = None  ,						)  ->   int:
           raise NotImplementedError("This method should be implemented by the derived class."  )







    def 					_lowercase  (					self  )  ->   Dict:
           lowerCamelCase     :   List[Any]    				=      super().to_dict()
           lowerCamelCase     :   Optional[int]    				=      output.pop("_out_features"  )
           lowerCamelCase     :   Dict    				=      output.pop("_out_indices"  )
           return output




class 	UpperCamelCase__			:

    '''simple docstring'''



    @property
    def 					_lowercase  (					self  )  ->   int:
           return self._out_features







    @out_features.setter
    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   Optional[Any]:
           lowerCamelCase				,   lowerCamelCase     :   List[Any]    				=      get_aligned_output_features_output_indices(
               out_features=UpperCamelCase__  ,						out_indices=UpperCamelCase__  ,						stage_names=self.stage_names  )







    @property
    def 					_lowercase  (					self  )  ->   Optional[Any]:
           return self._out_indices







    @out_indices.setter
    def 					_lowercase  (					self  ,						UpperCamelCase__  )  ->   int:
           lowerCamelCase				,   lowerCamelCase     :   Optional[Any]    				=      get_aligned_output_features_output_indices(
               out_features=UpperCamelCase__  ,						out_indices=UpperCamelCase__  ,						stage_names=self.stage_names  )







    def 					_lowercase  (					self  )  ->   Any:
           lowerCamelCase     :   str    				=      super().to_dict()
           lowerCamelCase     :   Union[str, Any]    				=      output.pop("_out_features"  )
           lowerCamelCase     :   Optional[int]    				=      output.pop("_out_indices"  )
           return output






