



from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__lowerCamelCase  =			logging.get_logger(__name__)







def    _snake_case (       __snake_case    )     ->     List[int]:






      '''simple docstring'''







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

      UpperCAmelCase_  :	List[str]				      =		tf.shape(__snake_case    )

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

      UpperCAmelCase_  :	int				      =		tensor.shape.as_list()

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







def    _snake_case (       __snake_case					,  __snake_case = None					,  __snake_case = None    )     ->     tf.Tensor:






      '''simple docstring'''







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







def    _snake_case (       __snake_case					,  __snake_case					,  __snake_case					,  __snake_case=1E-5					,  __snake_case=-1    )     ->     List[str]:






      '''simple docstring'''







      if weight.shape.rank != 1 or bias.shape.rank != 1 or not isinstance(__snake_case					,  __snake_case    ):
            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_  :	Union[str, Any]				      =		tf.nn.moments(__snake_case					,  axes=[axis]					,  keepdims=__snake_case    )

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

      # Compute layer normalization using the batch_normalization
      # function.
      UpperCAmelCase_  :	Optional[int]				      =		tf.nn.batch_normalization(
          __snake_case					,  __snake_case					,  __snake_case					,  offset=__snake_case					,  scale=__snake_case					,  variance_epsilon=__snake_case					,  )
      return outputs







def    _snake_case (       __snake_case					,  __snake_case=0					,  __snake_case=-1    )     ->     Union[str, Any]:






      '''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_  :	str				      =		tf.shape(__snake_case    )
      UpperCAmelCase_  :	List[Any]				      =		tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]    )
      UpperCAmelCase_  :	Any				      =		tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]					,  axis=0    )
      return tf.reshape(__snake_case					,  __snake_case    )







def    _snake_case (       __snake_case    )     ->     tf.Tensor:






      '''simple docstring'''







      if not isinstance(__snake_case					,  tf.Tensor    ):
            UpperCAmelCase_  :	Tuple				      =		tf.convert_to_tensor(__snake_case    )  # Catches stray NumPy inputs
      if encoder_attention_mask.shape.rank == 3:
            UpperCAmelCase_  :	Optional[Any]				      =		encoder_attention_mask[:, None, :, :]
      if encoder_attention_mask.shape.rank == 2:
            UpperCAmelCase_  :	str				      =		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_  :	str				      =		(
          tf.cast(1					,  encoder_attention_mask.dtype    ) - encoder_extended_attention_mask
      ) * encoder_extended_attention_mask.dtype.min

      return encoder_extended_attention_mask







def    _snake_case (       __snake_case					,  __snake_case					,  __snake_case = "input_ids"    )     ->     None:






      '''simple docstring'''







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







def    _snake_case (       __snake_case					,  __snake_case					,  __snake_case    )     ->     Union[str, Any]:






      '''simple docstring'''







      UpperCAmelCase_  :	int				      =		6_4_5_1_2
      # 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[str]				      =		[x for x in data if len(__snake_case    ) > 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_  :	Union[str, Any]				      =		np.asarray(__snake_case    )

      UpperCAmelCase_  :	Optional[int]				      =		1
      UpperCAmelCase_  :	Any				      =		np.array_split(__snake_case					,  __snake_case    )

      # 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_  :	List[str]				      =		np.array_split(__snake_case					,  __snake_case    )

      if num_chunks > 1:
            for chunk_id, chunk_data in enumerate(__snake_case    ):
                  UpperCAmelCase_  :	Dict				      =		chunk_data
      else:
            UpperCAmelCase_  :	List[Any]				      =		data







def    _snake_case (       __snake_case					,  __snake_case    )     ->     List[str]:






      '''simple docstring'''







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







def    _snake_case (       __snake_case    )     ->     Dict:






      '''simple docstring'''







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

      return tf.nest.map_structure(_expand_single_ad_tensor					,  __snake_case    )





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


__lowerCamelCase         =			logging.get_logger(__name__)

__lowerCamelCase         =			{
    '''microsoft/trocr-base-handwritten''': (
        '''https://huggingface.co/microsoft/trocr-base-handwritten/resolve/main/config.json'''
    ),
    # See all TrOCR models at https://huggingface.co/models?filter=trocr
}


class   snake_case_ (lowercase__  ):




       """simple docstring"""






       _lowerCamelCase			    =				"""trocr"""
       _lowerCamelCase			    =				["""past_key_values"""]
       _lowerCamelCase			    =				{
           """num_attention_heads""": """decoder_attention_heads""",
           """hidden_size""": """d_model""",
           """num_hidden_layers""": """decoder_layers""",
       }



       def __init__(     self     ,lowercase=50265     ,lowercase=1024     ,lowercase=12     ,lowercase=16     ,lowercase=4096     ,lowercase="gelu"     ,lowercase=512     ,lowercase=0.1     ,lowercase=0.0     ,lowercase=0.0     ,lowercase=2     ,lowercase=0.02     ,lowercase=0.0     ,lowercase=True     ,lowercase=False     ,lowercase=True     ,lowercase=True     ,lowercase=1     ,lowercase=0     ,lowercase=2     ,**lowercase     ,):

             """simple docstring"""





             UpperCAmelCase_  :	int				      =		vocab_size
             UpperCAmelCase_  :	Tuple				      =		d_model
             UpperCAmelCase_  :	List[str]				      =		decoder_layers
             UpperCAmelCase_  :	Union[str, Any]				      =		decoder_attention_heads
             UpperCAmelCase_  :	Optional[Any]				      =		decoder_ffn_dim
             UpperCAmelCase_  :	Tuple				      =		activation_function
             UpperCAmelCase_  :	List[Any]				      =		max_position_embeddings
             UpperCAmelCase_  :	List[Any]				      =		dropout
             UpperCAmelCase_  :	List[str]				      =		attention_dropout
             UpperCAmelCase_  :	Union[str, Any]				      =		activation_dropout
             UpperCAmelCase_  :	Optional[int]				      =		init_std
             UpperCAmelCase_  :	Dict				      =		decoder_layerdrop
             UpperCAmelCase_  :	List[str]				      =		use_cache
             UpperCAmelCase_  :	Dict				      =		scale_embedding
             UpperCAmelCase_  :	Dict				      =		use_learned_position_embeddings
             UpperCAmelCase_  :	Optional[Any]				      =		layernorm_embedding

             super().__init__(
                 pad_token_id=lowercase     ,bos_token_id=lowercase     ,eos_token_id=lowercase     ,decoder_start_token_id=lowercase     ,**lowercase     ,)
