






from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


UpperCamelCase    							=      logging.get_logger(__name__)


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Union[tf.Tensor, np.ndarray]							)     ->  List[int]:
   if isinstance(__lowerCAmelCase					,							np.ndarray							):
      return list(tensor.shape							)

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


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Optional[int]					,							__lowerCAmelCase							:					Union[str, Any]					,							__lowerCAmelCase							:					Dict					,							__lowerCAmelCase							:					List[Any]=1e-5					,							__lowerCAmelCase							:					str=-1							)     ->  Union[str, Any]:
   # 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(__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	:			Union[str, Any]					=					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	:			Tuple					=					[1] * inputs.shape.rank
      __UpperCamelCase	:			Tuple					=					shape_list(__lowerCAmelCase							)[axis]
      __UpperCamelCase	:			Union[str, Any]					=					tf.reshape(__lowerCAmelCase					,							__lowerCAmelCase							)
      __UpperCamelCase	:			Tuple					=					tf.reshape(__lowerCAmelCase					,							__lowerCAmelCase							)

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


def 				__lowerCamelCase     (							__lowerCAmelCase							:					Dict					,							__lowerCAmelCase							:					Optional[Any]=0					,							__lowerCAmelCase							:					Tuple=-1							)     ->  List[str]:
   # 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

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


def 				__lowerCamelCase     (							__lowerCAmelCase							:					tf.Tensor							)     ->  tf.Tensor:
   if not isinstance(__lowerCAmelCase					,							tf.Tensor							):
      __UpperCamelCase	:			List[str]					=					tf.convert_to_tensor(__lowerCAmelCase							)  # 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	:			Optional[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	:			str					=					(
       tf.cast(1					,							encoder_attention_mask.dtype							) - encoder_extended_attention_mask
   ) * encoder_extended_attention_mask.dtype.min

   return encoder_extended_attention_mask


def 				__lowerCamelCase     (							__lowerCAmelCase							:					tf.Tensor					,							__lowerCAmelCase							:					int					,							__lowerCAmelCase							:					str = "input_ids"							)     ->  None:
   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 				__lowerCamelCase     (							__lowerCAmelCase							:					Any					,							__lowerCAmelCase							:					Tuple					,							__lowerCAmelCase							:					List[Any]							)     ->  int:
   __UpperCamelCase	:			Optional[int]					=					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.
   __UpperCamelCase	:			Dict					=					[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	:			Optional[Any]					=					np.asarray(__lowerCAmelCase							)

   __UpperCamelCase	:			List[Any]					=					1
   __UpperCamelCase	:			List[str]					=					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	:			Union[str, Any]					=					np.array_split(__lowerCAmelCase					,							__lowerCAmelCase							)

   if num_chunks > 1:
      for chunk_id, chunk_data in enumerate(__lowerCAmelCase							):
         __UpperCamelCase	:			str					=					chunk_data
   else:
      __UpperCamelCase	:			Optional[int]					=					data


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

   def _expand_single_ad_tensor(__lowerCAmelCase							:					Optional[Any]							):
      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							)











from __future__ import annotations


def 				__lowerCamelCase     (							__lowerCAmelCase							:					str					,							__lowerCAmelCase							:					Tuple					,							__lowerCAmelCase							:					int					,							__lowerCAmelCase							:					Tuple							)     ->  Optional[Any]:  # noqa: E741
   while r - l > 1:
      __UpperCamelCase	:			int					=					(l + r) // 2
      if v[m] >= key:
         __UpperCamelCase	:			Dict					=					m
      else:
         __UpperCamelCase	:			Optional[Any]					=					m  # noqa: E741
   return r


def 				__lowerCamelCase     (							__lowerCAmelCase							:					list[int]							)     ->  int:
   if len(__lowerCAmelCase							) == 0:
      return 0

   __UpperCamelCase	:			Optional[Any]					=					[0] * len(__lowerCAmelCase							)
   __UpperCamelCase	:			Optional[int]					=					1

   __UpperCamelCase	:			Union[str, Any]					=					v[0]

   for i in range(1					,							len(__lowerCAmelCase							)							):
      if v[i] < tail[0]:
         __UpperCamelCase	:			Dict					=					v[i]
      elif v[i] > tail[length - 1]:
         __UpperCamelCase	:			Optional[int]					=					v[i]
         length += 1
      else:
         __UpperCamelCase	:			List[Any]					=					v[i]

   return length


if __name__ == "__main__":
       import doctest

       doctest.testmod()



