






'''simple docstring'''

from dataclasses import dataclass
from typing import Dict, 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 .attention_processor import AttentionProcessor, AttnProcessor
from .modeling_utils import ModelMixin
from .vae import Decoder, DecoderOutput, DiagonalGaussianDistribution, Encoder




@dataclass
class     A    (      UpperCamelCase_						):






 """simple docstring"""





 __a			:						Union[str, Any]      =						42






class     A    (      UpperCamelCase_,   UpperCamelCase_						):






 """simple docstring"""





 __a			:						List[Any]      =						True
 @register_to_config
 def __init__(							self			,     __lowerCAmelCase = 3			,     __lowerCAmelCase = 3			,     __lowerCAmelCase = ("DownEncoderBlock2D",)			,     __lowerCAmelCase = ("UpDecoderBlock2D",)			,     __lowerCAmelCase = (64,)			,     __lowerCAmelCase = 1			,     __lowerCAmelCase = "silu"			,     __lowerCAmelCase = 4			,     __lowerCAmelCase = 32			,     __lowerCAmelCase = 32			,     __lowerCAmelCase = 0.1_82_15			,     ):
       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			,     )

       # pass init params to Decoder
       UpperCamelCase_				:   Union[str, Any]					    =							Decoder(
           in_channels=__A			,     out_channels=__A			,     up_block_types=__A			,     block_out_channels=__A			,     layers_per_block=__A			,     norm_num_groups=__A			,     act_fn=__A			,     )

       UpperCamelCase_				:   List[Any]					    =							nn.Convad(2 * latent_channels			,     2 * latent_channels			,     1 )
       UpperCamelCase_				:   Any					    =							nn.Convad(__A			,     __A			,     1 )

       UpperCamelCase_				:   str					    =							False
       UpperCamelCase_				:   Dict					    =							False

       # only relevant if vae tiling is enabled
       UpperCamelCase_				:   List[str]					    =							self.config.sample_size
       UpperCamelCase_				:   List[Any]					    =							(
           self.config.sample_size[0]
           if isinstance(self.config.sample_size			,     (list, tuple) )
           else self.config.sample_size
       )
       UpperCamelCase_				:   Tuple					    =							int(sample_size / (2 ** (len(self.config.block_out_channels ) - 1)) )
       UpperCamelCase_				:   List[str]					    =							0.25
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase=False ):
       if isinstance(__A			,     (Encoder, Decoder) ):
             UpperCamelCase_				:   List[Any]					    =							value
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase = True ):
       UpperCamelCase_				:   int					    =							use_tiling
 def   _UpperCAmelCase       (							self ):
       self.enable_tiling(__A )
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   str					    =							True
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[int]					    =							False
 @property
 # Copied from diffusers.models.unet_2d_condition.UNet2DConditionModel.attn_processors
 def   _UpperCAmelCase       (							self ):
       UpperCamelCase_				:   Optional[Any]					    =							{}

       def fn_recursive_add_processors(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
             if hasattr(__A			,     """set_processor""" ):
                   UpperCamelCase_				:   List[Any]					    =							module.processor

             for sub_name, child in module.named_children():
                   fn_recursive_add_processors(F"{name}.{sub_name}"			,     __A			,     __A )

             return processors

       for name, module in self.named_children():
             fn_recursive_add_processors(__A			,     __A			,     __A )

       return processors
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase ):
       UpperCamelCase_				:   str					    =							len(self.attn_processors.keys() )

       if isinstance(__A			,     __A ) and len(__A ) != count:
             raise ValueError(
                 F"A dict of processors was passed, but the number of processors {len(__A )} does not match the"
                 F" number of attention layers: {count}. Please make sure to pass {count} processor classes." )

       def fn_recursive_attn_processor(__lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
             if hasattr(__A			,     """set_processor""" ):
                   if not isinstance(__A			,     __A ):
                         module.set_processor(__A )
                   else:
                         module.set_processor(processor.pop(F"{name}.processor" ) )

             for sub_name, child in module.named_children():
                   fn_recursive_attn_processor(F"{name}.{sub_name}"			,     __A			,     __A )

       for name, module in self.named_children():
             fn_recursive_attn_processor(__A			,     __A			,     __A )
 def   _UpperCAmelCase       (							self ):
       self.set_attn_processor(AttnProcessor() )
 @apply_forward_hook
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = True ):
       if self.use_tiling and (x.shape[-1] > self.tile_sample_min_size or x.shape[-2] > self.tile_sample_min_size):
             return self.tiled_encode(__A			,     return_dict=__A )

       if self.use_slicing and x.shape[0] > 1:
             UpperCamelCase_				:   int					    =							[self.encoder(__A ) for x_slice in x.split(1 )]
             UpperCamelCase_				:   str					    =							torch.cat(__A )
       else:
             UpperCamelCase_				:   Dict					    =							self.encoder(__A )

       UpperCamelCase_				:   Optional[int]					    =							self.quant_conv(__A )
       UpperCamelCase_				:   int					    =							DiagonalGaussianDistribution(__A )

       if not return_dict:
             return (posterior,)

       return AutoencoderKLOutput(latent_dist=__A )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = True ):
       if self.use_tiling and (z.shape[-1] > self.tile_latent_min_size or z.shape[-2] > self.tile_latent_min_size):
             return self.tiled_decode(__A			,     return_dict=__A )

       UpperCamelCase_				:   Optional[int]					    =							self.post_quant_conv(__A )
       UpperCamelCase_				:   List[str]					    =							self.decoder(__A )

       if not return_dict:
             return (dec,)

       return DecoderOutput(sample=__A )
 @apply_forward_hook
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = True ):
       if self.use_slicing and z.shape[0] > 1:
             UpperCamelCase_				:   int					    =							[self._decode(__A ).sample for z_slice in z.split(1 )]
             UpperCamelCase_				:   Union[str, Any]					    =							torch.cat(__A )
       else:
             UpperCamelCase_				:   Optional[Any]					    =							self._decode(__A ).sample

       if not return_dict:
             return (decoded,)

       return DecoderOutput(sample=__A )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   List[str]					    =							min(a.shape[2]			,     b.shape[2]			,     __A )
       for y in range(__A ):
             UpperCamelCase_				:   Optional[Any]					    =							a[:, :, -blend_extent + y, :] * (1 - y / blend_extent) + b[:, :, y, :] * (y / blend_extent)
       return b
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase			,     __lowerCAmelCase ):
       UpperCamelCase_				:   Optional[Any]					    =							min(a.shape[3]			,     b.shape[3]			,     __A )
       for x in range(__A ):
             UpperCamelCase_				:   Tuple					    =							a[:, :, :, -blend_extent + x] * (1 - x / blend_extent) + b[:, :, :, x] * (x / blend_extent)
       return b
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = True ):
       UpperCamelCase_				:   List[Any]					    =							int(self.tile_sample_min_size * (1 - self.tile_overlap_factor) )
       UpperCamelCase_				:   Union[str, Any]					    =							int(self.tile_latent_min_size * self.tile_overlap_factor )
       UpperCamelCase_				:   Union[str, Any]					    =							self.tile_latent_min_size - blend_extent

       # Split the image into 512x512 tiles and encode them separately.
       UpperCamelCase_				:   Tuple					    =							[]
       for i in range(0			,     x.shape[2]			,     __A ):
             UpperCamelCase_				:   int					    =							[]
             for j in range(0			,     x.shape[3]			,     __A ):
                   UpperCamelCase_				:   str					    =							x[:, :, i : i + self.tile_sample_min_size, j : j + self.tile_sample_min_size]
                   UpperCamelCase_				:   Optional[Any]					    =							self.encoder(__A )
                   UpperCamelCase_				:   Union[str, Any]					    =							self.quant_conv(__A )
                   row.append(__A )
             rows.append(__A )
       UpperCamelCase_				:   Any					    =							[]
       for i, row in enumerate(__A ):
             UpperCamelCase_				:   Optional[int]					    =							[]
             for j, tile in enumerate(__A ):
                   # blend the above tile and the left tile
                   # to the current tile and add the current tile to the result row
                   if i > 0:
                         UpperCamelCase_				:   str					    =							self.blend_v(rows[i - 1][j]			,     __A			,     __A )
                   if j > 0:
                         UpperCamelCase_				:   List[Any]					    =							self.blend_h(row[j - 1]			,     __A			,     __A )
                   result_row.append(tile[:, :, :row_limit, :row_limit] )
             result_rows.append(torch.cat(__A			,     dim=3 ) )

       UpperCamelCase_				:   Any					    =							torch.cat(__A			,     dim=2 )
       UpperCamelCase_				:   Optional[Any]					    =							DiagonalGaussianDistribution(__A )

       if not return_dict:
             return (posterior,)

       return AutoencoderKLOutput(latent_dist=__A )
 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = True ):
       UpperCamelCase_				:   Any					    =							int(self.tile_latent_min_size * (1 - self.tile_overlap_factor) )
       UpperCamelCase_				:   Union[str, Any]					    =							int(self.tile_sample_min_size * self.tile_overlap_factor )
       UpperCamelCase_				:   int					    =							self.tile_sample_min_size - blend_extent

       # Split z into overlapping 64x64 tiles and decode them separately.
       # The tiles have an overlap to avoid seams between tiles.
       UpperCamelCase_				:   Union[str, Any]					    =							[]
       for i in range(0			,     z.shape[2]			,     __A ):
             UpperCamelCase_				:   Dict					    =							[]
             for j in range(0			,     z.shape[3]			,     __A ):
                   UpperCamelCase_				:   Optional[int]					    =							z[:, :, i : i + self.tile_latent_min_size, j : j + self.tile_latent_min_size]
                   UpperCamelCase_				:   Optional[Any]					    =							self.post_quant_conv(__A )
                   UpperCamelCase_				:   Optional[int]					    =							self.decoder(__A )
                   row.append(__A )
             rows.append(__A )
       UpperCamelCase_				:   Tuple					    =							[]
       for i, row in enumerate(__A ):
             UpperCamelCase_				:   Optional[int]					    =							[]
             for j, tile in enumerate(__A ):
                   # blend the above tile and the left tile
                   # to the current tile and add the current tile to the result row
                   if i > 0:
                         UpperCamelCase_				:   Any					    =							self.blend_v(rows[i - 1][j]			,     __A			,     __A )
                   if j > 0:
                         UpperCamelCase_				:   Dict					    =							self.blend_h(row[j - 1]			,     __A			,     __A )
                   result_row.append(tile[:, :, :row_limit, :row_limit] )
             result_rows.append(torch.cat(__A			,     dim=3 ) )

       UpperCamelCase_				:   Any					    =							torch.cat(__A			,     dim=2 )
       if not return_dict:
             return (dec,)

       return DecoderOutput(sample=__A )





 def   _UpperCAmelCase       (							self			,     __lowerCAmelCase			,     __lowerCAmelCase = False			,     __lowerCAmelCase = True			,     __lowerCAmelCase = None			,     ):
       UpperCamelCase_				:   List[Any]					    =							sample
       UpperCamelCase_				:   int					    =							self.encode(__A ).latent_dist
       if sample_posterior:
             UpperCamelCase_				:   Union[str, Any]					    =							posterior.sample(generator=__A )
       else:
             UpperCamelCase_				:   int					    =							posterior.mode()
       UpperCamelCase_				:   int					    =							self.decode(__A ).sample

       if not return_dict:
             return (dec,)

       return DecoderOutput(sample=__A )














'''simple docstring'''

# Lint as: python3
import itertools
import os
import re


UpperCamelCase							=re.compile(R"([A-Z]+)([A-Z][a-z])")
UpperCamelCase							=re.compile(R"([a-z\d])([A-Z])")

UpperCamelCase							=re.compile(R"(?<!_)_(?!_)")
UpperCamelCase							=re.compile(R"(_{2,})")

UpperCamelCase							=R"^\w+(\.\w+)*$"

UpperCamelCase							=R"<>:/\|?*"



def 							snake_case					(     a_							: str	)       ->				int:





      """simple docstring"""

      UpperCamelCase_				:   str					    =							_uppercase_uppercase_re.sub(r"""\1_\2"""    ,   a_	)
      UpperCamelCase_				:   List[Any]					    =							_lowercase_uppercase_re.sub(r"""\1_\2"""    ,   a_	)
      return name.lower()



def 							snake_case					(     a_							: Any	)       ->				Optional[Any]:





      """simple docstring"""

      UpperCamelCase_				:   Optional[Any]					    =							_single_underscore_re.split(a_	)
      UpperCamelCase_				:   Tuple					    =							[_multiple_underscores_re.split(a_	) for n in name]
      return "".join(n.capitalize() for n in itertools.chain.from_iterable(a_	) if n != """"""	)



def 							snake_case					(     a_							: Optional[int]	)       ->				str:





      """simple docstring"""

      if os.path.basename(a_	) != name:
            raise ValueError(f"Should be a dataset name, not a path: {name}"	)
      return camelcase_to_snakecase(a_	)



def 							snake_case					(     a_							: List[Any]    ,   a_							: Optional[int]	)       ->				Optional[Any]:





      """simple docstring"""

      if os.path.basename(a_	) != name:
            raise ValueError(f"Should be a dataset name, not a path: {name}"	)
      if not re.match(_split_re    ,   a_	):
            raise ValueError(f"Split name should match '{_split_re}'' but got '{split}'."	)
      return f"{filename_prefix_for_name(a_	)}-{split}"



def 							snake_case					(     a_							: Optional[Any]    ,   a_							: int    ,   a_							: List[Any]    ,   a_							: Union[str, Any]=None	)       ->				Dict:





      """simple docstring"""

      UpperCamelCase_				:   Optional[int]					    =							filename_prefix_for_split(a_    ,   a_	)
      if filetype_suffix:
            prefix += f".{filetype_suffix}"
      UpperCamelCase_				:   str					    =							os.path.join(a_    ,   a_	)
      return f"{filepath}*"



def 							snake_case					(     a_							: Tuple    ,   a_							: Any    ,   a_							: Optional[int]    ,   a_							: Union[str, Any]=None    ,   a_							: Optional[Any]=None	)       ->				List[Any]:





      """simple docstring"""

      UpperCamelCase_				:   Dict					    =							filename_prefix_for_split(a_    ,   a_	)
      UpperCamelCase_				:   Dict					    =							os.path.join(a_    ,   a_	)

      if shard_lengths:
            UpperCamelCase_				:   Optional[int]					    =							len(a_	)
            UpperCamelCase_				:   Tuple					    =							[f"{prefix}-{shard_id:05d}-of-{num_shards:05d}" for shard_id in range(a_	)]
            if filetype_suffix:
                  UpperCamelCase_				:   Tuple					    =							[filename + f".{filetype_suffix}" for filename in filenames]
            return filenames
      else:
            UpperCamelCase_				:   Dict					    =							prefix
            if filetype_suffix:
                  filename += f".{filetype_suffix}"
            return [filename]






