'''simple docstring'''




from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


_a   :	List[Any] 							=   logging.get_logger(__name__)

def _lowercase	(      lowerCamelCase__						)					->       List[int]:





       """simple docstring"""


       if isinstance(lowerCamelCase__							,    np.ndarray						):
              return list(tensor.shape						)

       __UpperCAmelCase  :				List[Any]       				=		tf.shape(lowerCamelCase__						)

       if tensor.shape == tf.TensorShape(lowerCamelCase__						):
              return dynamic

       __UpperCAmelCase  :				List[str]       				=		tensor.shape.as_list()

       return [dynamic[i] if s is None else s for i, s in enumerate(lowerCamelCase__						)]

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__ = None							,    lowerCamelCase__ = None						)					->       tf.Tensor:





       """simple docstring"""


       return tf.nn.softmax(logits=logits + 1e-9							,    axis=lowerCamelCase__							,    name=lowerCamelCase__						)

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__=1e-5							,    lowerCamelCase__=-1						)					->       str:





       """simple docstring"""


       if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(lowerCamelCase__							,    lowerCamelCase__						):
              raise NotImplementedError("Only 1D weight and bias tensors are supported for now, with only a single axis."						)

       # Get mean and variance on the axis to be normalized
       __UpperCAmelCase				, __UpperCAmelCase  :				Tuple       				=		tf.nn.moments(lowerCamelCase__							,    axes=[axis]							,    keepdims=lowerCamelCase__						)

       if axis != -1:
              # Reshape scale and weight to have the same rank as inputs, but with 1 dimensions
              # on every dimension except axis
              __UpperCAmelCase  :				Dict       				=		[1] * inputs.shape.rank
              __UpperCAmelCase  :				Any       				=		shape_list(lowerCamelCase__						)[axis]
              __UpperCAmelCase  :				Tuple       				=		tf.reshape(lowerCamelCase__							,    lowerCamelCase__						)
              __UpperCAmelCase  :				str       				=		tf.reshape(lowerCamelCase__							,    lowerCamelCase__						)

       # Compute layer normalization using the batch_normalization
       # function.
       __UpperCAmelCase  :				List[str]       				=		tf.nn.batch_normalization(
           lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__							,    offset=lowerCamelCase__							,    scale=lowerCamelCase__							,    variance_epsilon=lowerCamelCase__							,    )
       return outputs

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__=0							,    lowerCamelCase__=-1						)					->       str:





       """simple docstring"""


       if end_dim < 0:
              end_dim += input.shape.rank
       if start_dim < 0:
              start_dim += input.shape.rank

       if start_dim == end_dim:
              return input

       __UpperCAmelCase  :				List[Any]       				=		tf.shape(lowerCamelCase__						)
       __UpperCAmelCase  :				Optional[Any]       				=		tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]						)
       __UpperCAmelCase  :				List[str]       				=		tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]							,    axis=0						)
       return tf.reshape(lowerCamelCase__							,    lowerCamelCase__						)

def _lowercase	(      lowerCamelCase__						)					->       tf.Tensor:





       """simple docstring"""


       if not isinstance(lowerCamelCase__							,    tf.Tensor						):
              __UpperCAmelCase  :				Optional[Any]       				=		tf.convert_to_tensor(lowerCamelCase__						)  # Catches stray NumPy inputs
       if encoder_attention_mask.shape.rank == 3:
              __UpperCAmelCase  :				Union[str, Any]       				=		encoder_attention_mask[:, None, :, :]
       if encoder_attention_mask.shape.rank == 2:
              __UpperCAmelCase  :				Any       				=		encoder_attention_mask[:, None, None, :]
       # T5 has a mask that can compare sequence ids, we can simulate this here with this transposition
       # Cf. https://github.com/tensorflow/mesh/blob/8d2465e9bc93129b913b5ccc6a59aa97abd96ec6/mesh_tensorflow
       # /transformer/transformer_layers.py#L270
       # encoder_extended_attention_mask = (encoder_extended_attention_mask ==
       # encoder_extended_attention_mask.transpose(-1, -2))
       __UpperCAmelCase  :				Dict       				=		(
           tf.cast(1							,    encoder_attention_mask.dtype						) - encoder_extended_attention_mask
       ) * encoder_extended_attention_mask.dtype.min

       return encoder_extended_attention_mask

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__ = "input_ids"						)					->       None:





       """simple docstring"""


       tf.debugging.assert_less(
           lowerCamelCase__							,    tf.cast(lowerCamelCase__							,    dtype=tensor.dtype						)							,    message=(
               f"""The maximum value of {tensor_name} ({tf.math.reduce_max(lowerCamelCase__						)}) must be smaller than the embedding """
               f"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."""
           )							,    )

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__							,    lowerCamelCase__						)					->       str:





       """simple docstring"""


       __UpperCAmelCase  :				Tuple       				=		6_4512
       # Check that no item in `data` is larger than `HDF5_OBJECT_HEADER_LIMIT`
       # because in that case even chunking the array would not make the saving
       # possible.
       __UpperCAmelCase  :				List[Any]       				=		[x for x in data if len(lowerCamelCase__						) > HDF5_OBJECT_HEADER_LIMIT]

       # Expecting this to never be true.
       if bad_attributes:
              raise RuntimeError(
                  "The following attributes cannot be saved to HDF5 file because "
                  f"""they are larger than {HDF5_OBJECT_HEADER_LIMIT} """
                  f"""bytes: {bad_attributes}"""						)

       __UpperCAmelCase  :				Any       				=		np.asarray(lowerCamelCase__						)

       __UpperCAmelCase  :				str       				=		1
       __UpperCAmelCase  :				Tuple       				=		np.array_split(lowerCamelCase__							,    lowerCamelCase__						)

       # This will never loop forever thanks to the test above.
       while any(x.nbytes > HDF5_OBJECT_HEADER_LIMIT for x in chunked_data						):
              num_chunks += 1
              __UpperCAmelCase  :				Tuple       				=		np.array_split(lowerCamelCase__							,    lowerCamelCase__						)

       if num_chunks > 1:
              for chunk_id, chunk_data in enumerate(lowerCamelCase__						):
                     __UpperCAmelCase  :				Tuple       				=		chunk_data
       else:
              __UpperCAmelCase  :				int       				=		data

def _lowercase	(      lowerCamelCase__							,    lowerCamelCase__						)					->       Union[str, Any]:





       """simple docstring"""


       if name in group.attrs:
              __UpperCAmelCase  :				Optional[int]       				=		[n.decode("utf8"						) if hasattr(lowerCamelCase__							,    "decode"						) else n for n in group.attrs[name]]
       else:
              __UpperCAmelCase  :				Union[str, Any]       				=		[]
              __UpperCAmelCase  :				Optional[Any]       				=		0
              while "%s%d" % (name, chunk_id) in group.attrs:
                     data.extend(
                         [n.decode("utf8"						) if hasattr(lowerCamelCase__							,    "decode"						) else n for n in group.attrs["%s%d" % (name, chunk_id)]]						)
                     chunk_id += 1
       return data


def _lowercase	(      lowerCamelCase__						)					->       List[Any]:





       """simple docstring"""


       def _expand_single_ad_tensor(lowerCamelCase__						):
              if isinstance(lowerCamelCase__							,    tf.Tensor						) and t.shape.rank == 1:
                     return tf.expand_dims(lowerCamelCase__							,    axis=-1						)
              return t

       return tf.nest.map_structure(_expand_single_ad_tensor							,    lowerCamelCase__						)







'''simple docstring'''




from ...configuration_utils import PretrainedConfig
from ...utils import logging


_a   :	Any 							=   logging.get_logger(__name__)

_a   :	List[Any] 							=   {
    "microsoft/cvt-13": "https://huggingface.co/microsoft/cvt-13/resolve/main/config.json",
    # See all Cvt models at https://huggingface.co/models?filter=cvt
}






class 		__A       (__magic_name__   ):
       snake_case       :Any				    =					"cvt"






       def __init__(      self				,     UpperCamelCase_=3				,     UpperCamelCase_=[7, 3, 3]				,     UpperCamelCase_=[4, 2, 2]				,     UpperCamelCase_=[2, 1, 1]				,     UpperCamelCase_=[64, 1_92, 3_84]				,     UpperCamelCase_=[1, 3, 6]				,     UpperCamelCase_=[1, 2, 10]				,     UpperCamelCase_=[4.0, 4.0, 4.0]				,     UpperCamelCase_=[0.0, 0.0, 0.0]				,     UpperCamelCase_=[0.0, 0.0, 0.0]				,     UpperCamelCase_=[0.0, 0.0, 0.1]				,     UpperCamelCase_=[True, True, True]				,     UpperCamelCase_=[False, False, True]				,     UpperCamelCase_=["dw_bn", "dw_bn", "dw_bn"]				,     UpperCamelCase_=[3, 3, 3]				,     UpperCamelCase_=[1, 1, 1]				,     UpperCamelCase_=[2, 2, 2]				,     UpperCamelCase_=[1, 1, 1]				,     UpperCamelCase_=[1, 1, 1]				,     UpperCamelCase_=0.0_2				,     UpperCamelCase_=1E-12				,     **UpperCamelCase_				,     ):
              super().__init__(**UpperCamelCase_      )
              __UpperCAmelCase  :				Optional[int]       				=		num_channels
              __UpperCAmelCase  :				Optional[Any]       				=		patch_sizes
              __UpperCAmelCase  :				List[str]       				=		patch_stride
              __UpperCAmelCase  :				Tuple       				=		patch_padding
              __UpperCAmelCase  :				int       				=		embed_dim
              __UpperCAmelCase  :				str       				=		num_heads
              __UpperCAmelCase  :				Any       				=		depth
              __UpperCAmelCase  :				List[str]       				=		mlp_ratio
              __UpperCAmelCase  :				List[str]       				=		attention_drop_rate
              __UpperCAmelCase  :				Dict       				=		drop_rate
              __UpperCAmelCase  :				Dict       				=		drop_path_rate
              __UpperCAmelCase  :				str       				=		qkv_bias
              __UpperCAmelCase  :				Optional[int]       				=		cls_token
              __UpperCAmelCase  :				Optional[Any]       				=		qkv_projection_method
              __UpperCAmelCase  :				Tuple       				=		kernel_qkv
              __UpperCAmelCase  :				Optional[Any]       				=		padding_kv
              __UpperCAmelCase  :				Optional[int]       				=		stride_kv
              __UpperCAmelCase  :				Any       				=		padding_q
              __UpperCAmelCase  :				List[Any]       				=		stride_q
              __UpperCAmelCase  :				Union[str, Any]       				=		initializer_range
              __UpperCAmelCase  :				Any       				=		layer_norm_eps






