


"""simple docstring"""





from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


snake_case__						:   Optional[Any]			 = logging.get_logger(__name__)


def    _snake_case  (  _snake_case :	Union[tf.Tensor, np.ndarray]	):
      if isinstance(_snake_case       ,      np.ndarray	):
            return list(tensor.shape	)

      lowerCAmelCase    :		Any				=      tf.shape(_snake_case	)

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

      lowerCAmelCase    :		Optional[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 :	tf.Tensor       ,      _snake_case :	Optional[int] = None       ,      _snake_case :	Optional[str] = None	):
      return tf.nn.softmax(logits=logits + 1E-9       ,      axis=_snake_case       ,      name=_snake_case	)


def    _snake_case  (  _snake_case :	List[str]       ,      _snake_case :	Dict       ,      _snake_case :	Optional[int]       ,      _snake_case :	Any=1E-5       ,      _snake_case :	Union[str, Any]=-1	):
      # This is a very simplified functional layernorm, designed to duplicate
      # the functionality of PyTorch nn.functional.layer_norm when this is needed to port
      # models in Transformers.

      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
      lowerCAmelCase,					lowerCAmelCase    :		Tuple				=      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
            lowerCAmelCase    :		Any				=      [1] * inputs.shape.rank
            lowerCAmelCase    :		Optional[Any]				=      shape_list(_snake_case	)[axis]
            lowerCAmelCase    :		Union[str, Any]				=      tf.reshape(_snake_case       ,      _snake_case	)
            lowerCAmelCase    :		Tuple				=      tf.reshape(_snake_case       ,      _snake_case	)

      # Compute layer normalization using the batch_normalization
      # function.
      lowerCAmelCase    :		Dict				=      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 :	Dict       ,      _snake_case :	Optional[int]=0       ,      _snake_case :	Tuple=-1	):
      # Replicates the behavior of torch.flatten in TF

      # If end_dim or start_dim is negative, count them from the end
      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

      lowerCAmelCase    :		Optional[Any]				=      tf.shape(_snake_case	)
      lowerCAmelCase    :		Tuple				=      tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]	)
      lowerCAmelCase    :		str				=      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	):
      if not isinstance(_snake_case       ,      tf.Tensor	):
            lowerCAmelCase    :		Any				=      tf.convert_to_tensor(_snake_case	)  # Catches stray NumPy inputs
      if encoder_attention_mask.shape.rank == 3:
            lowerCAmelCase    :		Optional[int]				=      encoder_attention_mask[:, None, :, :]
      if encoder_attention_mask.shape.rank == 2:
            lowerCAmelCase    :		int				=      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))
      lowerCAmelCase    :		Any				=      (
          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 :	tf.Tensor       ,      _snake_case :	int       ,      _snake_case :	str = "input_ids"	):
      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 :	List[Any]       ,      _snake_case :	Optional[int]       ,      _snake_case :	str	):
      lowerCAmelCase    :		Tuple				=      64512
      # 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.
      lowerCAmelCase    :		Optional[Any]				=      [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}'''	)

      lowerCAmelCase    :		Optional[int]				=      np.asarray(_snake_case	)

      lowerCAmelCase    :		Tuple				=      1
      lowerCAmelCase    :		Optional[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
            lowerCAmelCase    :		Optional[int]				=      np.array_split(_snake_case       ,      _snake_case	)

      if num_chunks > 1:
            for chunk_id, chunk_data in enumerate(_snake_case	):
                  lowerCAmelCase    :		int				=      chunk_data
      else:
            lowerCAmelCase    :		List[Any]				=      data


def    _snake_case  (  _snake_case :	str       ,      _snake_case :	Union[str, Any]	):
      if name in group.attrs:
            lowerCAmelCase    :		Union[str, Any]				=      [n.decode('''utf8'''	) if hasattr(_snake_case       ,      '''decode'''	) else n for n in group.attrs[name]]
      else:
            lowerCAmelCase    :		Dict				=      []
            lowerCAmelCase    :		List[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 :	Optional[int]	):

      def _expand_single_ad_tensor(_snake_case :	List[str]	):
            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	)






"""simple docstring"""





snake_case__						:   str			 = [
    999,
    800,
    799,
    600,
    599,
    500,
    400,
    399,
    377,
    355,
    333,
    311,
    288,
    266,
    244,
    222,
    200,
    199,
    177,
    155,
    133,
    111,
    88,
    66,
    44,
    22,
    0,
]

snake_case__						:   Optional[Any]			 = [
    999,
    976,
    952,
    928,
    905,
    882,
    858,
    857,
    810,
    762,
    715,
    714,
    572,
    429,
    428,
    286,
    285,
    238,
    190,
    143,
    142,
    118,
    95,
    71,
    47,
    24,
    0,
]

snake_case__						:   Any			 = [
    999,
    988,
    977,
    966,
    955,
    944,
    933,
    922,
    911,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    350,
    300,
    299,
    266,
    233,
    200,
    199,
    179,
    159,
    140,
    120,
    100,
    99,
    88,
    77,
    66,
    55,
    44,
    33,
    22,
    11,
    0,
]

snake_case__						:   Optional[Any]			 = [
    999,
    995,
    992,
    989,
    985,
    981,
    978,
    975,
    971,
    967,
    964,
    961,
    957,
    956,
    951,
    947,
    942,
    937,
    933,
    928,
    923,
    919,
    914,
    913,
    908,
    903,
    897,
    892,
    887,
    881,
    876,
    871,
    870,
    864,
    858,
    852,
    846,
    840,
    834,
    828,
    827,
    820,
    813,
    806,
    799,
    792,
    785,
    784,
    777,
    770,
    763,
    756,
    749,
    742,
    741,
    733,
    724,
    716,
    707,
    699,
    698,
    688,
    677,
    666,
    656,
    655,
    645,
    634,
    623,
    613,
    612,
    598,
    584,
    570,
    569,
    555,
    541,
    527,
    526,
    505,
    484,
    483,
    462,
    440,
    439,
    396,
    395,
    352,
    351,
    308,
    307,
    264,
    263,
    220,
    219,
    176,
    132,
    88,
    44,
    0,
]

snake_case__						:   int			 = [
    999,
    997,
    995,
    992,
    990,
    988,
    986,
    984,
    981,
    979,
    977,
    975,
    972,
    970,
    968,
    966,
    964,
    961,
    959,
    957,
    956,
    954,
    951,
    949,
    946,
    944,
    941,
    939,
    936,
    934,
    931,
    929,
    926,
    924,
    921,
    919,
    916,
    914,
    913,
    910,
    907,
    905,
    902,
    899,
    896,
    893,
    891,
    888,
    885,
    882,
    879,
    877,
    874,
    871,
    870,
    867,
    864,
    861,
    858,
    855,
    852,
    849,
    846,
    843,
    840,
    837,
    834,
    831,
    828,
    827,
    824,
    821,
    817,
    814,
    811,
    808,
    804,
    801,
    798,
    795,
    791,
    788,
    785,
    784,
    780,
    777,
    774,
    770,
    766,
    763,
    760,
    756,
    752,
    749,
    746,
    742,
    741,
    737,
    733,
    730,
    726,
    722,
    718,
    714,
    710,
    707,
    703,
    699,
    698,
    694,
    690,
    685,
    681,
    677,
    673,
    669,
    664,
    660,
    656,
    655,
    650,
    646,
    641,
    636,
    632,
    627,
    622,
    618,
    613,
    612,
    607,
    602,
    596,
    591,
    586,
    580,
    575,
    570,
    569,
    563,
    557,
    551,
    545,
    539,
    533,
    527,
    526,
    519,
    512,
    505,
    498,
    491,
    484,
    483,
    474,
    466,
    457,
    449,
    440,
    439,
    428,
    418,
    407,
    396,
    395,
    381,
    366,
    352,
    351,
    330,
    308,
    307,
    286,
    264,
    263,
    242,
    220,
    219,
    176,
    175,
    132,
    131,
    88,
    44,
    0,
]

snake_case__						:   Union[str, Any]			 = [
    999,
    991,
    982,
    974,
    966,
    958,
    950,
    941,
    933,
    925,
    916,
    908,
    900,
    899,
    874,
    850,
    825,
    800,
    799,
    700,
    600,
    500,
    400,
    300,
    200,
    100,
    0,
]

snake_case__						:   List[Any]			 = [
    999,
    992,
    985,
    978,
    971,
    964,
    957,
    949,
    942,
    935,
    928,
    921,
    914,
    907,
    900,
    899,
    879,
    859,
    840,
    820,
    800,
    799,
    766,
    733,
    700,
    699,
    650,
    600,
    599,
    500,
    499,
    400,
    399,
    300,
    299,
    200,
    199,
    100,
    99,
    0,
]

snake_case__						:   Optional[int]			 = [
    999,
    996,
    992,
    989,
    985,
    982,
    979,
    975,
    972,
    968,
    965,
    961,
    958,
    955,
    951,
    948,
    944,
    941,
    938,
    934,
    931,
    927,
    924,
    920,
    917,
    914,
    910,
    907,
    903,
    900,
    899,
    891,
    884,
    876,
    869,
    861,
    853,
    846,
    838,
    830,
    823,
    815,
    808,
    800,
    799,
    788,
    777,
    766,
    755,
    744,
    733,
    722,
    711,
    700,
    699,
    688,
    677,
    666,
    655,
    644,
    633,
    622,
    611,
    600,
    599,
    585,
    571,
    557,
    542,
    528,
    514,
    500,
    499,
    485,
    471,
    457,
    442,
    428,
    414,
    400,
    399,
    379,
    359,
    340,
    320,
    300,
    299,
    279,
    259,
    240,
    220,
    200,
    199,
    166,
    133,
    100,
    99,
    66,
    33,
    0,
]


