from typing import Optional, Tuple, Union

import tensorflow as tf

from ...activations_tf import ACTaFN
from ...file_utils import add_code_sample_docstrings, add_start_docstrings, add_start_docstrings_to_model_forward
from ...modeling_tf_outputs import (
    TFBaseModelOutputWithNoAttention,
    TFBaseModelOutputWithPoolingAndNoAttention,
    TFSequenceClassifierOutput,
)
from ...modeling_tf_utils import TFPreTrainedModel, TFSequenceClassificationLoss, keras_serializable, unpack_inputs
from ...tf_utils import shape_list
from ...utils import logging
from .configuration_regnet import RegNetConfig


__lowercase							 =					logging.get_logger(__name__)

# General docstring
__lowercase							 =					'''RegNetConfig'''

# Base docstring
__lowercase							 =					'''facebook/regnet-y-040'''
__lowercase							 =					[1, 1088, 7, 7]

# Image classification docstring
__lowercase							 =					'''facebook/regnet-y-040'''
__lowercase							 =					'''tabby, tabby cat'''

__lowercase							 =					[
    '''facebook/regnet-y-040''',
    # See all regnet models at https://huggingface.co/models?filter=regnet
]


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase = 3 , __lowercase = 1 , __lowercase = 1 , __lowercase = "relu" , **__lowercase , )       ->	Dict:
        super().__init__(**__lowercase)
        # The padding and conv has been verified in
        # https://colab.research.google.com/gist/sayakpaul/854bc10eeaf21c9ee2119e0b9f3841a7/scratchpad.ipynb
        __UpperCamelCase     :Optional[int]			  =		tf.keras.layers.ZeroPaddingaD(padding=kernel_size // 2)
        __UpperCamelCase     :Any			  =		tf.keras.layers.ConvaD(
            filters=__lowercase , kernel_size=__lowercase , strides=__lowercase , padding='''VALID''' , groups=__lowercase , use_bias=__lowercase , name='''convolution''' , )
        __UpperCamelCase     :Tuple			  =		tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name='''normalization''')
        __UpperCamelCase     :List[str]			  =		ACTaFN[activation] if activation is not None else tf.identity







    def 			UpperCamelCase__   (	self , __lowercase)       ->	List[Any]:
        __UpperCamelCase     :Optional[int]			  =		self.convolution(self.padding(__lowercase))
        __UpperCamelCase     :Optional[int]			  =		self.normalization(__lowercase)
        __UpperCamelCase     :Tuple			  =		self.activation(__lowercase)
        return hidden_state


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , **__lowercase)       ->	int:
        super().__init__(**__lowercase)
        __UpperCamelCase     :Tuple			  =		config.num_channels
        __UpperCamelCase     :Optional[int]			  =		TFRegNetConvLayer(
            out_channels=config.embedding_size , kernel_size=3 , stride=2 , activation=config.hidden_act , name='''embedder''' , )







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Dict:
        __UpperCamelCase     :Dict			  =		shape_list(__lowercase)[1]
        if tf.executing_eagerly() and num_channels != self.num_channels:
            raise ValueError(
                '''Make sure that the channel dimension of the pixel values match with the one set in the configuration.''')

        # When running on CPU, `tf.keras.layers.Conv2D` doesn't support `NCHW` format.
        # So change the input format from `NCHW` to `NHWC`.
        # shape = (batch_size, in_height, in_width, in_channels=num_channels)
        __UpperCamelCase     :Dict			  =		tf.transpose(__lowercase , perm=(0, 2, 3, 1))
        __UpperCamelCase     :Optional[int]			  =		self.embedder(__lowercase)
        return hidden_state


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase = 2 , **__lowercase)       ->	Optional[Any]:
        super().__init__(**__lowercase)
        __UpperCamelCase     :Union[str, Any]			  =		tf.keras.layers.ConvaD(
            filters=__lowercase , kernel_size=1 , strides=__lowercase , use_bias=__lowercase , name='''convolution''')
        __UpperCamelCase     :int			  =		tf.keras.layers.BatchNormalization(epsilon=1E-5 , momentum=0.9 , name='''normalization''')







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = False)       ->	tf.Tensor:
        return self.normalization(self.convolution(__lowercase) , training=__lowercase)


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase , **__lowercase)       ->	Union[str, Any]:
        super().__init__(**__lowercase)
        __UpperCamelCase     :int			  =		tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase , name='''pooler''')
        __UpperCamelCase     :List[Any]			  =		[
            tf.keras.layers.ConvaD(filters=__lowercase , kernel_size=1 , activation='''relu''' , name='''attention.0'''),
            tf.keras.layers.ConvaD(filters=__lowercase , kernel_size=1 , activation='''sigmoid''' , name='''attention.2'''),
        ]







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Any:
        # [batch_size, h, w, num_channels] -> [batch_size, 1, 1, num_channels]
        __UpperCamelCase     :List[str]			  =		self.pooler(__lowercase)
        for layer_module in self.attention:
            __UpperCamelCase     :List[str]			  =		layer_module(__lowercase)
        __UpperCamelCase     :int			  =		hidden_state * pooled
        return hidden_state


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase , __lowercase , __lowercase = 1 , **__lowercase)       ->	Tuple:
        super().__init__(**__lowercase)
        __UpperCamelCase     :str			  =		in_channels != out_channels or stride != 1
        __UpperCamelCase     :Any			  =		max(1 , out_channels // config.groups_width)
        __UpperCamelCase     :Optional[Any]			  =		(
            TFRegNetShortCut(__lowercase , stride=__lowercase , name='''shortcut''')
            if should_apply_shortcut
            else tf.keras.layers.Activation('''linear''' , name='''shortcut''')
        )
        # `self.layers` instead of `self.layer` because that is a reserved argument.
        __UpperCamelCase     :Optional[int]			  =		[
            TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=config.hidden_act , name='''layer.0'''),
            TFRegNetConvLayer(
                __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act , name='''layer.1'''),
            TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=__lowercase , name='''layer.2'''),
        ]
        __UpperCamelCase     :Dict			  =		ACTaFN[config.hidden_act]







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Any:
        __UpperCamelCase     :Optional[int]			  =		hidden_state
        for layer_module in self.layers:
            __UpperCamelCase     :Any			  =		layer_module(__lowercase)
        __UpperCamelCase     :Tuple			  =		self.shortcut(__lowercase)
        hidden_state += residual
        __UpperCamelCase     :Optional[Any]			  =		self.activation(__lowercase)
        return hidden_state


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase , __lowercase , __lowercase = 1 , **__lowercase)       ->	Union[str, Any]:
        super().__init__(**__lowercase)
        __UpperCamelCase     :int			  =		in_channels != out_channels or stride != 1
        __UpperCamelCase     :Optional[int]			  =		max(1 , out_channels // config.groups_width)
        __UpperCamelCase     :Dict			  =		(
            TFRegNetShortCut(__lowercase , stride=__lowercase , name='''shortcut''')
            if should_apply_shortcut
            else tf.keras.layers.Activation('''linear''' , name='''shortcut''')
        )
        __UpperCamelCase     :Dict			  =		[
            TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=config.hidden_act , name='''layer.0'''),
            TFRegNetConvLayer(
                __lowercase , stride=__lowercase , groups=__lowercase , activation=config.hidden_act , name='''layer.1'''),
            TFRegNetSELayer(__lowercase , reduced_channels=int(round(in_channels / 4)) , name='''layer.2'''),
            TFRegNetConvLayer(__lowercase , kernel_size=1 , activation=__lowercase , name='''layer.3'''),
        ]
        __UpperCamelCase     :Dict			  =		ACTaFN[config.hidden_act]







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Optional[int]:
        __UpperCamelCase     :str			  =		hidden_state
        for layer_module in self.layers:
            __UpperCamelCase     :Optional[Any]			  =		layer_module(__lowercase)
        __UpperCamelCase     :List[Any]			  =		self.shortcut(__lowercase)
        hidden_state += residual
        __UpperCamelCase     :List[str]			  =		self.activation(__lowercase)
        return hidden_state


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , __lowercase , __lowercase , __lowercase = 2 , __lowercase = 2 , **__lowercase)       ->	int:
        super().__init__(**__lowercase)

        __UpperCamelCase     :List[Any]			  =		TFRegNetXLayer if config.layer_type == '''x''' else TFRegNetYLayer
        __UpperCamelCase     :List[str]			  =		[
            # downsampling is done in the first layer with stride of 2
            layer(__lowercase , __lowercase , __lowercase , stride=__lowercase , name='''layers.0'''),
            *[layer(__lowercase , __lowercase , __lowercase , name=f"""layers.{i+1}""") for i in range(depth - 1)],
        ]







    def 			UpperCamelCase__   (	self , __lowercase)       ->	Optional[Any]:
        for layer_module in self.layers:
            __UpperCamelCase     :Tuple			  =		layer_module(__lowercase)
        return hidden_state


class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    def __init__(	self , __lowercase , **__lowercase)       ->	str:
        super().__init__(**__lowercase)
        __UpperCamelCase     :Any			  =		[]
        # based on `downsample_in_first_stage`, the first layer of the first stage may or may not downsample the input
        self.stages.append(
            TFRegNetStage(
                __lowercase , config.embedding_size , config.hidden_sizes[0] , stride=2 if config.downsample_in_first_stage else 1 , depth=config.depths[0] , name='''stages.0''' , ))
        __UpperCamelCase     :str			  =		zip(config.hidden_sizes , config.hidden_sizes[1:])
        for i, ((in_channels, out_channels), depth) in enumerate(zip(__lowercase , config.depths[1:])):
            self.stages.append(TFRegNetStage(__lowercase , __lowercase , __lowercase , depth=__lowercase , name=f"""stages.{i+1}"""))







    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = False , __lowercase = True)       ->	TFBaseModelOutputWithNoAttention:
        __UpperCamelCase     :Optional[Any]			  =		() if output_hidden_states else None

        for stage_module in self.stages:
            if output_hidden_states:
                __UpperCamelCase     :Tuple			  =		hidden_states + (hidden_state,)

            __UpperCamelCase     :Optional[Any]			  =		stage_module(__lowercase)

        if output_hidden_states:
            __UpperCamelCase     :Tuple			  =		hidden_states + (hidden_state,)

        if not return_dict:
            return tuple(v for v in [hidden_state, hidden_states] if v is not None)

        return TFBaseModelOutputWithNoAttention(last_hidden_state=__lowercase , hidden_states=__lowercase)


@keras_serializable
class 	lowerCamelCase_     (   tf.keras.layers.Layer ):






    '''simple docstring'''






    a__	:						Optional[Any]						=      RegNetConfig







    def __init__(	self , __lowercase , **__lowercase)       ->	Union[str, Any]:
        super().__init__(**__lowercase)
        __UpperCamelCase     :List[str]			  =		config
        __UpperCamelCase     :List[Any]			  =		TFRegNetEmbeddings(__lowercase , name='''embedder''')
        __UpperCamelCase     :Any			  =		TFRegNetEncoder(__lowercase , name='''encoder''')
        __UpperCamelCase     :Optional[int]			  =		tf.keras.layers.GlobalAveragePoolingaD(keepdims=__lowercase , name='''pooler''')







    @unpack_inputs
    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = None , __lowercase = None , __lowercase = False , )       ->	TFBaseModelOutputWithPoolingAndNoAttention:
        __UpperCamelCase     :Optional[Any]			  =		(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        __UpperCamelCase     :Union[str, Any]			  =		return_dict if return_dict is not None else self.config.use_return_dict

        __UpperCamelCase     :Union[str, Any]			  =		self.embedder(__lowercase , training=__lowercase)

        __UpperCamelCase     :Any			  =		self.encoder(
            __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase)

        __UpperCamelCase     :List[str]			  =		encoder_outputs[0]
        __UpperCamelCase     :List[str]			  =		self.pooler(__lowercase)

        # Change to NCHW output format have uniformity in the modules
        __UpperCamelCase     :str			  =		tf.transpose(__lowercase , perm=(0, 3, 1, 2))
        __UpperCamelCase     :List[Any]			  =		tf.transpose(__lowercase , perm=(0, 3, 1, 2))

        # Change the other hidden state outputs to NCHW as well
        if output_hidden_states:
            __UpperCamelCase     :List[str]			  =		tuple([tf.transpose(__lowercase , perm=(0, 3, 1, 2)) for h in encoder_outputs[1]])

        if not return_dict:
            return (last_hidden_state, pooled_output) + encoder_outputs[1:]

        return TFBaseModelOutputWithPoolingAndNoAttention(
            last_hidden_state=__lowercase , pooler_output=__lowercase , hidden_states=hidden_states if output_hidden_states else encoder_outputs.hidden_states , )


class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    a__	:						int						=      RegNetConfig
    a__	:						List[str]						=      """regnet"""
    a__	:						Optional[int]						=      """pixel_values"""







    @property
    def 			UpperCamelCase__   (	self)       ->	str:
        return {"pixel_values": tf.TensorSpec(shape=(None, self.config.num_channels, 224, 224) , dtype=tf.floataa)}
__lowercase							 =					r'''
    Parameters:
    This model is a Tensorflow
    [tf.keras.layers.Layer](https://www.tensorflow.org/api_docs/python/tf/keras/layers/Layer) sub-class. Use it as a
    regular Tensorflow Module and refer to the Tensorflow documentation for all matter related to general usage and
    behavior.
        config ([`RegNetConfig`]): Model configuration class with all the parameters of the model.
            Initializing with a config file does not load the weights associated with the model, only the
            configuration. Check out the [`~TFPreTrainedModel.from_pretrained`] method to load the model weights.
'''

__lowercase							 =					r'''
    Args:
        pixel_values (`tf.Tensor` of shape `(batch_size, num_channels, height, width)`):
            Pixel values. Pixel values can be obtained using [`AutoImageProcessor`]. See
            [`ConveNextImageProcessor.__call__`] for details.
        output_hidden_states (`bool`, *optional*):
            Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
            more detail.
        return_dict (`bool`, *optional*):
            Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
'''


@add_start_docstrings(
    """The bare RegNet model outputting raw features without any specific head on top."""						,	UpperCAmelCase_						,	)
class 	lowerCamelCase_     (   UpperCAmelCase_ ):






    '''simple docstring'''






    def __init__(	self , __lowercase , *__lowercase , **__lowercase)       ->	List[Any]:
        super().__init__(__lowercase , *__lowercase , **__lowercase)
        __UpperCamelCase     :Tuple			  =		TFRegNetMainLayer(__lowercase , name='''regnet''')







    @unpack_inputs
    @add_start_docstrings_to_model_forward(__lowercase)
    @add_code_sample_docstrings(
        checkpoint=_CHECKPOINT_FOR_DOC , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , modality='''vision''' , expected_output=_EXPECTED_OUTPUT_SHAPE , )
    def 			UpperCamelCase__   (	self , __lowercase , __lowercase = None , __lowercase = None , __lowercase=False , )       ->	Union[TFBaseModelOutputWithPoolingAndNoAttention, Tuple[tf.Tensor]]:
        __UpperCamelCase     :int			  =		(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        __UpperCamelCase     :Optional[Any]			  =		return_dict if return_dict is not None else self.config.use_return_dict

        __UpperCamelCase     :List[Any]			  =		self.regnet(
            pixel_values=__lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase , )
        if not return_dict:
            return (outputs[0],) + outputs[1:]

        return TFBaseModelOutputWithPoolingAndNoAttention(
            last_hidden_state=outputs.last_hidden_state , pooler_output=outputs.pooler_output , hidden_states=outputs.hidden_states , )


@add_start_docstrings(
    """
    RegNet Model with an image classification head on top (a linear layer on top of the pooled features), e.g. for
    ImageNet.
    """						,	UpperCAmelCase_						,	)
class 	lowerCamelCase_     (   UpperCAmelCase_						,	UpperCAmelCase_ ):






    '''simple docstring'''






    def __init__(	self , __lowercase , *__lowercase , **__lowercase)       ->	int:
        super().__init__(__lowercase , *__lowercase , **__lowercase)
        __UpperCamelCase     :Optional[Any]			  =		config.num_labels
        __UpperCamelCase     :str			  =		TFRegNetMainLayer(__lowercase , name='''regnet''')
        # classification head
        __UpperCamelCase     :List[Any]			  =		[
            tf.keras.layers.Flatten(),
            tf.keras.layers.Dense(config.num_labels , name='''classifier.1''') if config.num_labels > 0 else tf.identity,
        ]







    @unpack_inputs
    @add_start_docstrings_to_model_forward(__lowercase)
    @add_code_sample_docstrings(
        checkpoint=_IMAGE_CLASS_CHECKPOINT , output_type=__lowercase , config_class=_CONFIG_FOR_DOC , expected_output=_IMAGE_CLASS_EXPECTED_OUTPUT , )
    def 			UpperCamelCase__   (	self , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase = None , __lowercase=False , )       ->	Union[TFSequenceClassifierOutput, Tuple[tf.Tensor]]:
        __UpperCamelCase     :Optional[int]			  =		(
            output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
        )
        __UpperCamelCase     :int			  =		return_dict if return_dict is not None else self.config.use_return_dict

        __UpperCamelCase     :Union[str, Any]			  =		self.regnet(
            __lowercase , output_hidden_states=__lowercase , return_dict=__lowercase , training=__lowercase)

        __UpperCamelCase     :List[str]			  =		outputs.pooler_output if return_dict else outputs[1]

        __UpperCamelCase     :str			  =		self.classifier[0](__lowercase)
        __UpperCamelCase     :List[Any]			  =		self.classifier[1](__lowercase)

        __UpperCamelCase     :Tuple			  =		None if labels is None else self.hf_compute_loss(labels=__lowercase , logits=__lowercase)

        if not return_dict:
            __UpperCamelCase     :Tuple			  =		(logits,) + outputs[2:]
            return ((loss,) + output) if loss is not None else output

        return TFSequenceClassifierOutput(loss=__lowercase , logits=__lowercase , hidden_states=outputs.hidden_states)









from dataclasses import dataclass
from typing import Optional

import numpy as np
import torch
import torch.nn as nn

from ..utils import BaseOutput, is_torch_version, randn_tensor
from .attention_processor import SpatialNorm
from .unet_ad_blocks import UNetMidBlockaD, get_down_block, get_up_block


@dataclass
class        _a							(			UpperCamelCase__			):
							_lowercase	:			torch.FloatTensor


class        _a							(			nn.Module			):

							def __init__(							self:	int    ,						UpperCamelCase_:	int=3    ,						UpperCamelCase_:	Optional[Any]=3    ,						UpperCamelCase_:	Union[str, Any]=("DownEncoderBlock2D",)    ,						UpperCamelCase_:	Optional[int]=(64,)    ,						UpperCamelCase_:	Tuple=2    ,						UpperCamelCase_:	Dict=32    ,						UpperCamelCase_:	Any="silu"    ,						UpperCamelCase_:	Optional[int]=True    ,						)			->   Union[str, Any]:





									"""simple docstring"""







									super().__init__()
									lowercase__            =      layers_per_block

									lowercase__            =      torch.nn.Convad(
									    UpperCamelCase_    ,						block_out_channels[0]    ,						kernel_size=3    ,						stride=1    ,						padding=1    ,						)

									lowercase__            =      None
									lowercase__            =      nn.ModuleList([]							)

									# down
									lowercase__            =      block_out_channels[0]
									for i, down_block_type in enumerate(UpperCamelCase_							):
											lowercase__            =      output_channel
											lowercase__            =      block_out_channels[i]
											lowercase__            =      i == len(UpperCamelCase_							) - 1

											lowercase__            =      get_down_block(
											    UpperCamelCase_    ,						num_layers=self.layers_per_block    ,						in_channels=UpperCamelCase_    ,						out_channels=UpperCamelCase_    ,						add_downsample=not is_final_block    ,						resnet_eps=1E-6    ,						downsample_padding=0    ,						resnet_act_fn=UpperCamelCase_    ,						resnet_groups=UpperCamelCase_    ,						attention_head_dim=UpperCamelCase_    ,						temb_channels=UpperCamelCase_    ,						)
											self.down_blocks.append(UpperCamelCase_							)

									# mid
									lowercase__            =      UNetMidBlockaD(
									    in_channels=block_out_channels[-1]    ,						resnet_eps=1E-6    ,						resnet_act_fn=UpperCamelCase_    ,						output_scale_factor=1    ,						resnet_time_scale_shift='''default'''    ,						attention_head_dim=block_out_channels[-1]    ,						resnet_groups=UpperCamelCase_    ,						temb_channels=UpperCamelCase_    ,						)

									# out
									lowercase__            =      nn.GroupNorm(num_channels=block_out_channels[-1]    ,						num_groups=UpperCamelCase_    ,						eps=1E-6							)
									lowercase__            =      nn.SiLU()

									lowercase__            =      2 * out_channels if double_z else out_channels
									lowercase__            =      nn.Convad(block_out_channels[-1]    ,						UpperCamelCase_    ,						3    ,						padding=1							)

									lowercase__            =      False


							def       lowerCamelCase_ (							self:	Optional[Any]    ,						UpperCamelCase_:	str							)			->   str:





									"""simple docstring"""







									lowercase__            =      x
									lowercase__            =      self.conv_in(UpperCamelCase_							)

									if self.training and self.gradient_checkpointing:

											def create_custom_forward(UpperCamelCase_:	Dict							):
													def custom_forward(*UpperCamelCase_:	List[str]							):
															return module(*UpperCamelCase_							)

													return custom_forward

											# down
											if is_torch_version('''>='''    ,						'''1.11.0'''							):
													for down_block in self.down_blocks:
															lowercase__            =      torch.utils.checkpoint.checkpoint(
															    create_custom_forward(UpperCamelCase_							)    ,						UpperCamelCase_    ,						use_reentrant=UpperCamelCase_							)
													# middle
													lowercase__            =      torch.utils.checkpoint.checkpoint(
													    create_custom_forward(self.mid_block							)    ,						UpperCamelCase_    ,						use_reentrant=UpperCamelCase_							)
											else:
													for down_block in self.down_blocks:
															lowercase__            =      torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCamelCase_							)    ,						UpperCamelCase_							)
													# middle
													lowercase__            =      torch.utils.checkpoint.checkpoint(create_custom_forward(self.mid_block							)    ,						UpperCamelCase_							)

									else:
											# down
											for down_block in self.down_blocks:
													lowercase__            =      down_block(UpperCamelCase_							)

											# middle
											lowercase__            =      self.mid_block(UpperCamelCase_							)

									# post-process
									lowercase__            =      self.conv_norm_out(UpperCamelCase_							)
									lowercase__            =      self.conv_act(UpperCamelCase_							)
									lowercase__            =      self.conv_out(UpperCamelCase_							)

									return sample


class        _a							(			nn.Module			):

							def __init__(							self:	Dict    ,						UpperCamelCase_:	int=3    ,						UpperCamelCase_:	Optional[Any]=3    ,						UpperCamelCase_:	int=("UpDecoderBlock2D",)    ,						UpperCamelCase_:	Any=(64,)    ,						UpperCamelCase_:	Optional[Any]=2    ,						UpperCamelCase_:	List[Any]=32    ,						UpperCamelCase_:	Optional[Any]="silu"    ,						UpperCamelCase_:	Dict="group"    ,						)			->   Any:





									"""simple docstring"""







									super().__init__()
									lowercase__            =      layers_per_block

									lowercase__            =      nn.Convad(
									    UpperCamelCase_    ,						block_out_channels[-1]    ,						kernel_size=3    ,						stride=1    ,						padding=1    ,						)

									lowercase__            =      None
									lowercase__            =      nn.ModuleList([]							)

									lowercase__            =      in_channels if norm_type == '''spatial''' else None

									# mid
									lowercase__            =      UNetMidBlockaD(
									    in_channels=block_out_channels[-1]    ,						resnet_eps=1E-6    ,						resnet_act_fn=UpperCamelCase_    ,						output_scale_factor=1    ,						resnet_time_scale_shift='''default''' if norm_type == '''group''' else norm_type    ,						attention_head_dim=block_out_channels[-1]    ,						resnet_groups=UpperCamelCase_    ,						temb_channels=UpperCamelCase_    ,						)

									# up
									lowercase__            =      list(reversed(UpperCamelCase_							)							)
									lowercase__            =      reversed_block_out_channels[0]
									for i, up_block_type in enumerate(UpperCamelCase_							):
											lowercase__            =      output_channel
											lowercase__            =      reversed_block_out_channels[i]

											lowercase__            =      i == len(UpperCamelCase_							) - 1

											lowercase__            =      get_up_block(
											    UpperCamelCase_    ,						num_layers=self.layers_per_block + 1    ,						in_channels=UpperCamelCase_    ,						out_channels=UpperCamelCase_    ,						prev_output_channel=UpperCamelCase_    ,						add_upsample=not is_final_block    ,						resnet_eps=1E-6    ,						resnet_act_fn=UpperCamelCase_    ,						resnet_groups=UpperCamelCase_    ,						attention_head_dim=UpperCamelCase_    ,						temb_channels=UpperCamelCase_    ,						resnet_time_scale_shift=UpperCamelCase_    ,						)
											self.up_blocks.append(UpperCamelCase_							)
											lowercase__            =      output_channel

									# out
									if norm_type == "spatial":
											lowercase__            =      SpatialNorm(block_out_channels[0]    ,						UpperCamelCase_							)
									else:
											lowercase__            =      nn.GroupNorm(num_channels=block_out_channels[0]    ,						num_groups=UpperCamelCase_    ,						eps=1E-6							)
									lowercase__            =      nn.SiLU()
									lowercase__            =      nn.Convad(block_out_channels[0]    ,						UpperCamelCase_    ,						3    ,						padding=1							)

									lowercase__            =      False


							def       lowerCamelCase_ (							self:	Optional[Any]    ,						UpperCamelCase_:	Union[str, Any]    ,						UpperCamelCase_:	List[str]=None							)			->   int:





									"""simple docstring"""







									lowercase__            =      z
									lowercase__            =      self.conv_in(UpperCamelCase_							)

									lowercase__            =      next(iter(self.up_blocks.parameters()							)							).dtype
									if self.training and self.gradient_checkpointing:

											def create_custom_forward(UpperCamelCase_:	List[str]							):
													def custom_forward(*UpperCamelCase_:	int							):
															return module(*UpperCamelCase_							)

													return custom_forward

											if is_torch_version('''>='''    ,						'''1.11.0'''							):
													# middle
													lowercase__            =      torch.utils.checkpoint.checkpoint(
													    create_custom_forward(self.mid_block							)    ,						UpperCamelCase_    ,						UpperCamelCase_    ,						use_reentrant=UpperCamelCase_							)
													lowercase__            =      sample.to(UpperCamelCase_							)

													# up
													for up_block in self.up_blocks:
															lowercase__            =      torch.utils.checkpoint.checkpoint(
															    create_custom_forward(UpperCamelCase_							)    ,						UpperCamelCase_    ,						UpperCamelCase_    ,						use_reentrant=UpperCamelCase_							)
											else:
													# middle
													lowercase__            =      torch.utils.checkpoint.checkpoint(
													    create_custom_forward(self.mid_block							)    ,						UpperCamelCase_    ,						UpperCamelCase_							)
													lowercase__            =      sample.to(UpperCamelCase_							)

													# up
													for up_block in self.up_blocks:
															lowercase__            =      torch.utils.checkpoint.checkpoint(create_custom_forward(UpperCamelCase_							)    ,						UpperCamelCase_    ,						UpperCamelCase_							)
									else:
											# middle
											lowercase__            =      self.mid_block(UpperCamelCase_    ,						UpperCamelCase_							)
											lowercase__            =      sample.to(UpperCamelCase_							)

											# up
											for up_block in self.up_blocks:
													lowercase__            =      up_block(UpperCamelCase_    ,						UpperCamelCase_							)

        # post-process
									if latent_embeds is None:
											lowercase__            =      self.conv_norm_out(UpperCamelCase_							)
									else:
											lowercase__            =      self.conv_norm_out(UpperCamelCase_    ,						UpperCamelCase_							)
									lowercase__            =      self.conv_act(UpperCamelCase_							)
									lowercase__            =      self.conv_out(UpperCamelCase_							)

									return sample


class        _a							(			nn.Module			):

							def __init__(							self:	Tuple    ,						UpperCamelCase_:	List[str]    ,						UpperCamelCase_:	Optional[Any]    ,						UpperCamelCase_:	Optional[Any]    ,						UpperCamelCase_:	Optional[int]=None    ,						UpperCamelCase_:	List[str]="random"    ,						UpperCamelCase_:	Union[str, Any]=False    ,						UpperCamelCase_:	Dict=True							)			->   List[Any]:





									"""simple docstring"""







									super().__init__()
									lowercase__            =      n_e
									lowercase__            =      vq_embed_dim
									lowercase__            =      beta
									lowercase__            =      legacy

									lowercase__            =      nn.Embedding(self.n_e    ,						self.vq_embed_dim							)
									self.embedding.weight.data.uniform_(-1.0 / self.n_e    ,						1.0 / self.n_e							)

									lowercase__            =      remap
									if self.remap is not None:
											self.register_buffer('''used'''    ,						torch.tensor(np.load(self.remap							)							)							)
											lowercase__            =      self.used.shape[0]
											lowercase__            =      unknown_index  # "random" or "extra" or integer
											if self.unknown_index == "extra":
													lowercase__            =      self.re_embed
													lowercase__            =      self.re_embed + 1
											print(
											    f'Remapping {self.n_e} indices to {self.re_embed} indices. '
											    f'Using {self.unknown_index} for unknown indices.'							)
									else:
											lowercase__            =      n_e

									lowercase__            =      sane_index_shape

							def       lowerCamelCase_ (							self:	Optional[int]    ,						UpperCamelCase_:	Any							)			->   Dict:





									"""simple docstring"""







									lowercase__            =      inds.shape
									assert len(UpperCamelCase_							) > 1
									lowercase__            =      inds.reshape(ishape[0]    ,						-1							)
									lowercase__            =      self.used.to(UpperCamelCase_							)
									lowercase__            =      (inds[:, :, None] == used[None, None, ...]).long()
									lowercase__            =      match.argmax(-1							)
									lowercase__            =      match.sum(2							) < 1
									if self.unknown_index == "random":
											lowercase__            =      torch.randint(0    ,						self.re_embed    ,						size=new[unknown].shape							).to(device=new.device							)
									else:
											lowercase__            =      self.unknown_index
									return new.reshape(UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	Union[str, Any]    ,						UpperCamelCase_:	Tuple							)			->   str:





									"""simple docstring"""







									lowercase__            =      inds.shape
									assert len(UpperCamelCase_							) > 1
									lowercase__            =      inds.reshape(ishape[0]    ,						-1							)
									lowercase__            =      self.used.to(UpperCamelCase_							)
									if self.re_embed > self.used.shape[0]:  # extra token
											lowercase__            =      0  # simply set to zero
									lowercase__            =      torch.gather(used[None, :][inds.shape[0] * [0], :]    ,						1    ,						UpperCamelCase_							)
									return back.reshape(UpperCamelCase_							)

							def       lowerCamelCase_ (							self:	List[Any]    ,						UpperCamelCase_:	Any							)			->   Tuple:





									"""simple docstring"""







									lowercase__            =      z.permute(0    ,						2    ,						3    ,						1							).contiguous()
									lowercase__            =      z.view(-1    ,						self.vq_embed_dim							)

									# distances from z to embeddings e_j (z - e)^2 = z^2 + e^2 - 2 e * z
									lowercase__            =      torch.argmin(torch.cdist(UpperCamelCase_    ,						self.embedding.weight							)    ,						dim=1							)

									lowercase__            =      self.embedding(UpperCamelCase_							).view(z.shape							)
									lowercase__            =      None
									lowercase__            =      None

									# compute loss for embedding
									if not self.legacy:
											lowercase__            =      self.beta * torch.mean((z_q.detach() - z) ** 2							) + torch.mean((z_q - z.detach()) ** 2							)
									else:
											lowercase__            =      torch.mean((z_q.detach() - z) ** 2							) + self.beta * torch.mean((z_q - z.detach()) ** 2							)

									# preserve gradients
									lowercase__            =      z + (z_q - z).detach()

									# reshape back to match original input shape
									lowercase__            =      z_q.permute(0    ,						3    ,						1    ,						2							).contiguous()

									if self.remap is not None:
											lowercase__            =      min_encoding_indices.reshape(z.shape[0]    ,						-1							)  # add batch axis
											lowercase__            =      self.remap_to_used(UpperCamelCase_							)
											lowercase__            =      min_encoding_indices.reshape(-1    ,						1							)  # flatten

									if self.sane_index_shape:
											lowercase__            =      min_encoding_indices.reshape(z_q.shape[0]    ,						z_q.shape[2]    ,						z_q.shape[3]							)

									return z_q, loss, (perplexity, min_encodings, min_encoding_indices)


							def       lowerCamelCase_ (							self:	List[Any]    ,						UpperCamelCase_:	Tuple    ,						UpperCamelCase_:	List[Any]							)			->   List[str]:





									"""simple docstring"""







									if self.remap is not None:
											lowercase__            =      indices.reshape(shape[0]    ,						-1							)  # add batch axis
											lowercase__            =      self.unmap_to_all(UpperCamelCase_							)
											lowercase__            =      indices.reshape(-1							)  # flatten again

									# get quantized latent vectors
									lowercase__            =      self.embedding(UpperCamelCase_							)

									if shape is not None:
											lowercase__            =      z_q.view(UpperCamelCase_							)
											# reshape back to match original input shape
											lowercase__            =      z_q.permute(0    ,						3    ,						1    ,						2							).contiguous()

									return z_q


class        _a							(			UpperCamelCase__			):

							def __init__(							self:	Union[str, Any]    ,						UpperCamelCase_:	Any    ,						UpperCamelCase_:	List[Any]=False							)			->   str:





									"""simple docstring"""







									lowercase__            =      parameters
									lowercase__     ,		lowercase__            =      torch.chunk(UpperCamelCase_    ,						2    ,						dim=1							)
									lowercase__            =      torch.clamp(self.logvar    ,						-30.0    ,						20.0							)
									lowercase__            =      deterministic
									lowercase__            =      torch.exp(0.5 * self.logvar							)
									lowercase__            =      torch.exp(self.logvar							)
									if self.deterministic:
											lowercase__            =      lowercase__            =      torch.zeros_like(
											    self.mean    ,						device=self.parameters.device    ,						dtype=self.parameters.dtype							)

							def       lowerCamelCase_ (							self:	Any    ,						UpperCamelCase_:	Optional[torch.Generator] = None							)			->   torch.FloatTensor:





									"""simple docstring"""







									lowercase__            =      randn_tensor(
									    self.mean.shape    ,						generator=UpperCamelCase_    ,						device=self.parameters.device    ,						dtype=self.parameters.dtype							)
									lowercase__            =      self.mean + self.std * sample
									return x

							def       lowerCamelCase_ (							self:	List[str]    ,						UpperCamelCase_:	str=None							)			->   Tuple:





									"""simple docstring"""







									if self.deterministic:
											return torch.Tensor([0.0]							)
									else:
											if other is None:
													return 0.5 * torch.sum(torch.pow(self.mean    ,						2							) + self.var - 1.0 - self.logvar    ,						dim=[1, 2, 3]							)
											else:
													return 0.5 * torch.sum(
													    torch.pow(self.mean - other.mean    ,						2							) / other.var
													    + self.var / other.var
													    - 1.0
													    - self.logvar
													    + other.logvar    ,						dim=[1, 2, 3]    ,						)

							def       lowerCamelCase_ (							self:	int    ,						UpperCamelCase_:	Any    ,						UpperCamelCase_:	Any=[1, 2, 3]							)			->   Tuple:





									"""simple docstring"""







									if self.deterministic:
											return torch.Tensor([0.0]							)
									lowercase__            =      np.log(2.0 * np.pi							)
									return 0.5 * torch.sum(logtwopi + self.logvar + torch.pow(sample - self.mean    ,						2							) / self.var    ,						dim=UpperCamelCase_							)


							def       lowerCamelCase_ (							self:	str							)			->   Any:





									"""simple docstring"""







									return self.mean


