





"""simple docstring"""


from dataclasses import dataclass
from typing import Optional, Tuple, Union

import torch
import torch.nn as nn

from ..configuration_utils import ConfigMixin, register_to_config
from ..utils import BaseOutput, apply_forward_hook
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, Encoder, VectorQuantizer



@dataclass
class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase   ):







  '''simple docstring'''


  SCREAMING_SNAKE_CASE__							:torch.FloatTensor





class      __SCREAMING_SNAKE_CASE    (						_UpperCamelCase		,  _UpperCamelCase   ):







  '''simple docstring'''


  @register_to_config
  def __init__(		self   :       Any					,   __a   :       int = 3					,   __a   :       int = 3					,   __a   :       Tuple[str] = ("DownEncoderBlock2D",)					,   __a   :       Tuple[str] = ("UpDecoderBlock2D",)					,   __a   :       Tuple[int] = (64,)					,   __a   :       int = 1					,   __a   :       str = "silu"					,   __a   :       int = 3					,   __a   :       int = 32					,   __a   :       int = 256					,   __a   :       int = 32					,   __a   :       Optional[int] = None					,   __a   :       float = 0.1_82_15					,   __a   :       str = "group"					,   )		->				Optional[int]:
        super().__init__()

        # pass init params to Encoder
        _UpperCamelCase      :	List[str]						=       Encoder(
            in_channels=__a					,   out_channels=__a					,   down_block_types=__a					,   block_out_channels=__a					,   layers_per_block=__a					,   act_fn=__a					,   norm_num_groups=__a					,   double_z=__a					,   )

        _UpperCamelCase      :	Tuple						=       vq_embed_dim if vq_embed_dim is not None else latent_channels

        _UpperCamelCase      :	int						=       nn.Convad(__a					,   __a					,   1	)
        _UpperCamelCase      :	List[str]						=       VectorQuantizer(__a					,   __a					,   beta=0.25					,   remap=__a					,   sane_index_shape=__a	)
        _UpperCamelCase      :	List[str]						=       nn.Convad(__a					,   __a					,   1	)

        # pass init params to Decoder
        _UpperCamelCase      :	Optional[Any]						=       Decoder(
            in_channels=__a					,   out_channels=__a					,   up_block_types=__a					,   block_out_channels=__a					,   layers_per_block=__a					,   act_fn=__a					,   norm_num_groups=__a					,   norm_type=__a					,   )

  @apply_forward_hook
  def    __SCREAMING_SNAKE_CASE				(		self   :       str					,   __a   :       torch.FloatTensor					,   __a   :       bool = True	)		->				VQEncoderOutput:
        _UpperCamelCase      :	Optional[int]						=       self.encoder(__a	)
        _UpperCamelCase      :	Tuple						=       self.quant_conv(__a	)

        if not return_dict:
              return (h,)

        return VQEncoderOutput(latents=__a	)

  @apply_forward_hook
  def    __SCREAMING_SNAKE_CASE				(		self   :       Tuple					,   __a   :       torch.FloatTensor					,   __a   :       bool = False					,   __a   :       bool = True	)		->				Union[DecoderOutput, torch.FloatTensor]:
        # also go through quantization layer
        if not force_not_quantize:
              _UpperCamelCase,  _UpperCamelCase,  _UpperCamelCase      :	Any						=       self.quantize(__a	)
        else:
              _UpperCamelCase      :	str						=       h
        _UpperCamelCase      :	Optional[Any]						=       self.post_quant_conv(__a	)
        _UpperCamelCase      :	int						=       self.decoder(__a					,   quant if self.config.norm_type == "spatial" else None	)

        if not return_dict:
              return (dec,)

        return DecoderOutput(sample=__a	)


  def    __SCREAMING_SNAKE_CASE				(		self   :       int					,   __a   :       torch.FloatTensor					,   __a   :       bool = True	)		->				Union[DecoderOutput, torch.FloatTensor]:
        _UpperCamelCase      :	Tuple						=       sample
        _UpperCamelCase      :	int						=       self.encode(__a	).latents
        _UpperCamelCase      :	int						=       self.decode(__a	).sample

        if not return_dict:
              return (dec,)

        return DecoderOutput(sample=__a	)







"""simple docstring"""


import importlib
import os
import sys


# This is required to make the module import works (when the python process is running from the root of the repo)
sys.path.append(".")




def 					lowercase__    (					lowercase_			)					->		int:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       test_file.split(os.path.sep			)
      if components[0:2] != ["tests", "models"]:
            raise ValueError(
                "`test_file` should start with `tests/models/` (with `/` being the OS specific path separator). Got "
                F'''{test_file} instead.'''			)
      _UpperCamelCase      :	str						=       components[-1]
      if not test_fn.endswith("py"			):
            raise ValueError(F'''`test_file` should be a python file. Got {test_fn} instead.'''			)
      if not test_fn.startswith("test_modeling_"			):
            raise ValueError(
                F'''`test_file` should point to a file name of the form `test_modeling_*.py`. Got {test_fn} instead.'''			)

      _UpperCamelCase      :	Dict						=       components[:-1] + [test_fn.replace(".py"		,""			)]
      _UpperCamelCase      :	List[str]						=       ".".join(lowercase_			)

      return test_module_path




def 					lowercase__    (					lowercase_			)					->		List[Any]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       get_module_path(lowercase_			)
      _UpperCamelCase      :	str						=       importlib.import_module(lowercase_			)

      return test_module




def 					lowercase__    (					lowercase_			)					->		Optional[Any]:




      """simple docstring"""

      _UpperCamelCase      :	Union[str, Any]						=       []
      _UpperCamelCase      :	List[Any]						=       get_test_module(lowercase_			)
      for attr in dir(lowercase_			):
            if attr.endswith("ModelTester"			):
                  tester_classes.append(getattr(lowercase_		,lowercase_			)			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Tuple:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       []
      _UpperCamelCase      :	Any						=       get_test_module(lowercase_			)
      for attr in dir(lowercase_			):
            _UpperCamelCase      :	int						=       getattr(lowercase_		,lowercase_			)
            # (TF/Flax)ModelTesterMixin is also an attribute in specific model test module. Let's exclude them by checking
            # `all_model_classes` is not empty (which also excludes other special classes).
            _UpperCamelCase      :	Optional[Any]						=       getattr(lowercase_		,"all_model_classes"		,[]			)
            if len(lowercase_			) > 0:
                  test_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Any:




      """simple docstring"""

      _UpperCamelCase      :	Dict						=       get_test_classes(lowercase_			)
      _UpperCamelCase      :	int						=       set()
      for test_class in test_classes:
            model_classes.update(test_class.all_model_classes			)

      # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Optional[Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[str]						=       test_class()
      if hasattr(lowercase_		,"setUp"			):
            test.setUp()

      _UpperCamelCase      :	Tuple						=       None
      if hasattr(lowercase_		,"model_tester"			):
            # `(TF/Flax)ModelTesterMixin` has this attribute default to `None`. Let's skip this case.
            if test.model_tester is not None:
                  _UpperCamelCase      :	Tuple						=       test.model_tester.__class__

      return model_tester




def 					lowercase__    (					lowercase_		,lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	str						=       get_test_classes(lowercase_			)

      _UpperCamelCase      :	Dict						=       []
      for test_class in test_classes:
            if model_class in test_class.all_model_classes:
                  target_test_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_		,lowercase_			)					->		Dict:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       get_test_classes_for_model(lowercase_		,lowercase_			)

      _UpperCamelCase      :	List[Any]						=       []
      for test_class in test_classes:
            _UpperCamelCase      :	List[Any]						=       get_model_tester_from_test_class(lowercase_			)
            if tester_class is not None:
                  tester_classes.append(lowercase_			)

    # sort with class names
      return sorted(lowercase_		,key=lambda lowercase_			: x.__name__			)




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	Any						=       get_test_classes(lowercase_			)
      _UpperCamelCase      :	Tuple						=       {test_class: get_model_tester_from_test_class(lowercase_			) for test_class in test_classes}
      return test_tester_mapping




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	List[Any]						=       get_model_classes(lowercase_			)
      _UpperCamelCase      :	Optional[int]						=       {
          model_class: get_test_classes_for_model(lowercase_		,lowercase_			) for model_class in model_classes
      }
      return model_test_mapping




def 					lowercase__    (					lowercase_			)					->		Union[str, Any]:




      """simple docstring"""

      _UpperCamelCase      :	Optional[Any]						=       get_model_classes(lowercase_			)
      _UpperCamelCase      :	Tuple						=       {
          model_class: get_tester_classes_for_model(lowercase_		,lowercase_			) for model_class in model_classes
      }
      return model_to_tester_mapping




def 					lowercase__    (					lowercase_			)					->		Optional[int]:




      """simple docstring"""

      if isinstance(lowercase_		,lowercase_			):
            return o
      elif isinstance(lowercase_		,lowercase_			):
            return o.__name__
      elif isinstance(lowercase_		,(list, tuple)			):
            return [to_json(lowercase_			) for x in o]
      elif isinstance(lowercase_		,lowercase_			):
            return {to_json(lowercase_			): to_json(lowercase_			) for k, v in o.items()}
      else:
            return o
