





import os
import sys
from contextlib import contextmanager


# Windows only
if os.name == "nt":
   import ctypes
   import msvcrt  # noqa




   class 			__UpperCamelCase    (							ctypes.Structure    ):
        # _fields is a specific attr expected by ctypes
        __A	:  int							  =   [("""size""", ctypes.c_int), ("""visible""", ctypes.c_byte)]
def      A__       (    )  ->  Union[str, Any]:






   """simple docstring"""







   if os.name == "nt":
      _UpperCAmelCase           =   CursorInfo()
      _UpperCAmelCase           =   ctypes.windll.kernelaa.GetStdHandle(-11						)
      ctypes.windll.kernelaa.GetConsoleCursorInfo(SCREAMING_SNAKE_CASE_				,	ctypes.byref(SCREAMING_SNAKE_CASE_						)						)
      _UpperCAmelCase           =   False
      ctypes.windll.kernelaa.SetConsoleCursorInfo(SCREAMING_SNAKE_CASE_				,	ctypes.byref(SCREAMING_SNAKE_CASE_						)						)
   elif os.name == "posix":
      sys.stdout.write('''\033[?25l'''						)
      sys.stdout.flush()
def      A__       (    )  ->  List[Any]:






   """simple docstring"""







   if os.name == "nt":
      _UpperCAmelCase           =   CursorInfo()
      _UpperCAmelCase           =   ctypes.windll.kernelaa.GetStdHandle(-11						)
      ctypes.windll.kernelaa.GetConsoleCursorInfo(SCREAMING_SNAKE_CASE_				,	ctypes.byref(SCREAMING_SNAKE_CASE_						)						)
      _UpperCAmelCase           =   True
      ctypes.windll.kernelaa.SetConsoleCursorInfo(SCREAMING_SNAKE_CASE_				,	ctypes.byref(SCREAMING_SNAKE_CASE_						)						)
   elif os.name == "posix":
      sys.stdout.write('''\033[?25h'''						)
      sys.stdout.flush()
@contextmanager
def      A__       (    )  ->  str:






   """simple docstring"""







   try:
      hide_cursor()
      yield
   finally:
      show_cursor()






"""simple docstring"""






from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


__UpperCAmelCase						=			logging.get_logger(__name__)






def      lowercase__ (					lowerCAmelCase__   :			Union[tf.Tensor, np.ndarray]			)    ->			List[int]:



			'''simple docstring'''
			if isinstance(lowerCAmelCase__							,			np.ndarray			):
						return list(tensor.shape			)

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)

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

			a__  :	Union[str, Any]		 =			tensor.shape.as_list()

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






def      lowercase__ (					lowerCAmelCase__   :			tf.Tensor							,			lowerCAmelCase__   :			Optional[int] = None							,			lowerCAmelCase__   :			Optional[str] = None			)    ->			tf.Tensor:



			'''simple docstring'''
			return tf.nn.softmax(logits=logits + 1E-9							,			axis=lowerCAmelCase__							,			name=lowerCAmelCase__			)






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			List[str]							,			lowerCAmelCase__   :			Any							,			lowerCAmelCase__   :			Union[str, Any]=1E-5							,			lowerCAmelCase__   :			str=-1			)    ->			int:



			'''simple docstring'''
			# 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
			a__ ,	a__  :	Dict		 =			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
						a__  :	Dict		 =			[1] * inputs.shape.rank
						a__  :	Dict		 =			shape_list(lowerCAmelCase__			)[axis]
						a__  :	Any		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)
						a__  :	List[Any]		 =			tf.reshape(lowerCAmelCase__							,			lowerCAmelCase__			)

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






def      lowercase__ (					lowerCAmelCase__   :			Optional[int]							,			lowerCAmelCase__   :			Any=0							,			lowerCAmelCase__   :			List[str]=-1			)    ->			List[str]:



			'''simple docstring'''
			# 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

			a__  :	Optional[int]		 =			tf.shape(lowerCAmelCase__			)
			a__  :	str		 =			tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]			)
			a__  :	Union[str, Any]		 =			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			)    ->			tf.Tensor:



			'''simple docstring'''
			if not isinstance(lowerCAmelCase__							,			tf.Tensor			):
						a__  :	Optional[Any]		 =			tf.convert_to_tensor(lowerCAmelCase__			)  # Catches stray NumPy inputs
			if encoder_attention_mask.shape.rank == 3:
						a__  :	Tuple		 =			encoder_attention_mask[:, None, :, :]
			if encoder_attention_mask.shape.rank == 2:
						a__  :	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))
			a__  :	int		 =			(
			    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__   :			tf.Tensor							,			lowerCAmelCase__   :			int							,			lowerCAmelCase__   :			str = "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__   :			Dict							,			lowerCAmelCase__   :			str							,			lowerCAmelCase__   :			Dict			)    ->			Tuple:



			'''simple docstring'''
			a__  :	Optional[Any]		 =			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.
			a__  :	Optional[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}"			)

			a__  :	List[str]		 =			np.asarray(lowerCAmelCase__			)

			a__  :	List[str]		 =			1
			a__  :	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
						a__  :	str		 =			np.array_split(lowerCAmelCase__							,			lowerCAmelCase__			)

			if num_chunks > 1:
						for chunk_id, chunk_data in enumerate(lowerCAmelCase__			):
									a__  :	List[Any]		 =			chunk_data
			else:
						a__  :	List[str]		 =			data






def      lowercase__ (					lowerCAmelCase__   :			List[Any]							,			lowerCAmelCase__   :			Tuple			)    ->			Tuple:



			'''simple docstring'''
			if name in group.attrs:
						a__  :	str		 =			[n.decode("utf8"			) if hasattr(lowerCAmelCase__							,			"decode"			) else n for n in group.attrs[name]]
			else:
						a__  :	str		 =			[]
						a__  :	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__   :			Tuple			)    ->			List[Any]:



			'''simple docstring'''

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