


from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__snake_case   							=						logging.get_logger(__name__)






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


     """simple docstring"""


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

     __UpperCamelCase =			tf.shape(_lowercase )

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

     __UpperCamelCase =			tensor.shape.as_list()

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






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


     """simple docstring"""


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






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


     """simple docstring"""


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

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

     # Compute layer normalization using the batch_normalization
     # function.
     __UpperCamelCase =			tf.nn.batch_normalization(
         _lowercase					,  _lowercase					,  _lowercase					,  offset=_lowercase					,  scale=_lowercase					,  variance_epsilon=_lowercase					,  )
     return outputs






def 		_A		(		_lowercase					,  _lowercase=0					,  _lowercase=-1 )					-> Tuple:


     """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 =			tf.shape(_lowercase )
     __UpperCamelCase =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1] )
     __UpperCamelCase =			tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]					,  axis=0 )
     return tf.reshape(_lowercase					,  _lowercase )






def 		_A		(		_lowercase )					-> tf.Tensor:


     """simple docstring"""


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

     return encoder_extended_attention_mask






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


     """simple docstring"""


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






def 		_A		(		_lowercase					,  _lowercase					,  _lowercase )					-> Optional[int]:


     """simple docstring"""


     __UpperCamelCase =			6_45_12
     # 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 =			[x for x in data if len(_lowercase ) > 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 =			np.asarray(_lowercase )

     __UpperCamelCase =			1
     __UpperCamelCase =			np.array_split(_lowercase					,  _lowercase )

     # 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 =			np.array_split(_lowercase					,  _lowercase )

     if num_chunks > 1:
          for chunk_id, chunk_data in enumerate(_lowercase ):
               __UpperCamelCase =			chunk_data
     else:
          __UpperCamelCase =			data






def 		_A		(		_lowercase					,  _lowercase )					-> Tuple:


     """simple docstring"""


     if name in group.attrs:
          __UpperCamelCase =			[n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs[name]]
     else:
          __UpperCamelCase =			[]
          __UpperCamelCase =			0
          while "%s%d" % (name, chunk_id) in group.attrs:
               data.extend(
                   [n.decode('utf8' ) if hasattr(_lowercase					,  'decode' ) else n for n in group.attrs['%s%d' % (name, chunk_id)]] )
               chunk_id += 1
     return data






def 		_A		(		_lowercase )					-> Tuple:


     """simple docstring"""


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

     return tf.nest.map_structure(_expand_single_ad_tensor					,  _lowercase )






from collections import OrderedDict
from typing import Mapping

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


__snake_case   							=						logging.get_logger(__name__)

__snake_case   							=						{
    '''bert-base-uncased''': '''https://huggingface.co/bert-base-uncased/resolve/main/config.json''',
    '''bert-large-uncased''': '''https://huggingface.co/bert-large-uncased/resolve/main/config.json''',
    '''bert-base-cased''': '''https://huggingface.co/bert-base-cased/resolve/main/config.json''',
    '''bert-large-cased''': '''https://huggingface.co/bert-large-cased/resolve/main/config.json''',
    '''bert-base-multilingual-uncased''': '''https://huggingface.co/bert-base-multilingual-uncased/resolve/main/config.json''',
    '''bert-base-multilingual-cased''': '''https://huggingface.co/bert-base-multilingual-cased/resolve/main/config.json''',
    '''bert-base-chinese''': '''https://huggingface.co/bert-base-chinese/resolve/main/config.json''',
    '''bert-base-german-cased''': '''https://huggingface.co/bert-base-german-cased/resolve/main/config.json''',
    '''bert-large-uncased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking/resolve/main/config.json'''
    ),
    '''bert-large-uncased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-uncased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-large-cased-whole-word-masking-finetuned-squad''': (
        '''https://huggingface.co/bert-large-cased-whole-word-masking-finetuned-squad/resolve/main/config.json'''
    ),
    '''bert-base-cased-finetuned-mrpc''': '''https://huggingface.co/bert-base-cased-finetuned-mrpc/resolve/main/config.json''',
    '''bert-base-german-dbmdz-cased''': '''https://huggingface.co/bert-base-german-dbmdz-cased/resolve/main/config.json''',
    '''bert-base-german-dbmdz-uncased''': '''https://huggingface.co/bert-base-german-dbmdz-uncased/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese''': '''https://huggingface.co/cl-tohoku/bert-base-japanese/resolve/main/config.json''',
    '''cl-tohoku/bert-base-japanese-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-whole-word-masking/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char/resolve/main/config.json'''
    ),
    '''cl-tohoku/bert-base-japanese-char-whole-word-masking''': (
        '''https://huggingface.co/cl-tohoku/bert-base-japanese-char-whole-word-masking/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-cased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-cased-v1/resolve/main/config.json'''
    ),
    '''TurkuNLP/bert-base-finnish-uncased-v1''': (
        '''https://huggingface.co/TurkuNLP/bert-base-finnish-uncased-v1/resolve/main/config.json'''
    ),
    '''wietsedv/bert-base-dutch-cased''': '''https://huggingface.co/wietsedv/bert-base-dutch-cased/resolve/main/config.json''',
    # See all BERT models at https://huggingface.co/models?filter=bert
}



class 	__lowerCamelCase			(_a						):
       _lowercase											=     """bert"""







       def __init__(			self: Any,A_: Dict=3_0522,A_: Optional[Any]=768,A_: Union[str, Any]=12,A_: List[Any]=12,A_: Optional[int]=3072,A_: Union[str, Any]="gelu",A_: List[str]=0.1,A_: Dict=0.1,A_: Optional[int]=512,A_: Optional[Any]=2,A_: Union[str, Any]=0.0_2,A_: List[Any]=1E-12,A_: Optional[int]=0,A_: List[Any]="absolute",A_: str=True,A_: Union[str, Any]=None,**A_: int,):






            '''simple docstring'''




            super().__init__(pad_token_id=A_,**A_					)

            __UpperCamelCase =			vocab_size
            __UpperCamelCase =			hidden_size
            __UpperCamelCase =			num_hidden_layers
            __UpperCamelCase =			num_attention_heads
            __UpperCamelCase =			hidden_act
            __UpperCamelCase =			intermediate_size
            __UpperCamelCase =			hidden_dropout_prob
            __UpperCamelCase =			attention_probs_dropout_prob
            __UpperCamelCase =			max_position_embeddings
            __UpperCamelCase =			type_vocab_size
            __UpperCamelCase =			initializer_range
            __UpperCamelCase =			layer_norm_eps
            __UpperCamelCase =			position_embedding_type
            __UpperCamelCase =			use_cache
            __UpperCamelCase =			classifier_dropout



class 	__lowerCamelCase			(_a						):







       @property
       def 		snake_case_	(			self: Optional[int]					):






            '''simple docstring'''




            if self.task == "multiple-choice":
                 __UpperCamelCase =			{0: 'batch', 1: 'choice', 2: 'sequence'}
            else:
                 __UpperCamelCase =			{0: 'batch', 1: 'sequence'}
            return OrderedDict(
                [
                    ('input_ids', dynamic_axis),
                    ('attention_mask', dynamic_axis),
                    ('token_type_ids', dynamic_axis),
                ]					)


