



'''simple docstring'''



from typing import List, Optional, Union

import numpy as np
import tensorflow as tf

from .utils import logging


lowerCAmelCase_  :							Any             =    logging.get_logger(__name__)
def        UpperCAmelCase (    A	:					Union[tf.Tensor, np.ndarray]					):
							if isinstance(A       ,		np.ndarray					):
														return list(tensor.shape					)

							SCREAMING_SNAKE_CASE       :   int         =      tf.shape(A					)

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

							SCREAMING_SNAKE_CASE       :   Tuple         =      tensor.shape.as_list()

							return [dynamic[i] if s is None else s for i, s in enumerate(A					)]
def        UpperCAmelCase (    A	:					tf.Tensor       ,		A	:					Optional[int] = None       ,		A	:					Optional[str] = None					):
							return tf.nn.softmax(logits=logits + 1e-9       ,		axis=A       ,		name=A					)
def        UpperCAmelCase (    A	:					Union[str, Any]       ,		A	:					Tuple       ,		A	:					List[str]       ,		A	:					int=1e-5       ,		A	:					Optional[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(A       ,		A					):
														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
							SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   str         =      tf.nn.moments(A       ,		axes=[axis]       ,		keepdims=A					)

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

							# Compute layer normalization using the batch_normalization
							# function.
							SCREAMING_SNAKE_CASE       :   Dict         =      tf.nn.batch_normalization(
							    A       ,		A       ,		A       ,		offset=A       ,		scale=A       ,		variance_epsilon=A       ,		)
							return outputs
def        UpperCAmelCase (    A	:					List[str]       ,		A	:					List[Any]=0       ,		A	:					List[str]=-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

							SCREAMING_SNAKE_CASE       :   List[str]         =      tf.shape(A					)
							SCREAMING_SNAKE_CASE       :   Optional[Any]         =      tf.math.reduce_prod(in_shape[start_dim : end_dim + 1]					)
							SCREAMING_SNAKE_CASE       :   List[str]         =      tf.concat([in_shape[:start_dim], [flattened_dim], in_shape[end_dim + 1 :]]       ,		axis=0					)
							return tf.reshape(A       ,		A					)
def        UpperCAmelCase (    A	:					tf.Tensor					):
							if not isinstance(A       ,		tf.Tensor					):
														SCREAMING_SNAKE_CASE       :   Dict         =      tf.convert_to_tensor(A					)  # Catches stray NumPy inputs
							if encoder_attention_mask.shape.rank == 3:
														SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      encoder_attention_mask[:, None, :, :]
							if encoder_attention_mask.shape.rank == 2:
														SCREAMING_SNAKE_CASE       :   Union[str, 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))
							SCREAMING_SNAKE_CASE       :   Optional[Any]         =      (
							    tf.cast(1       ,		encoder_attention_mask.dtype					) - encoder_extended_attention_mask
							) * encoder_extended_attention_mask.dtype.min

							return encoder_extended_attention_mask
def        UpperCAmelCase (    A	:					tf.Tensor       ,		A	:					int       ,		A	:					str = "input_ids"					):
							tf.debugging.assert_less(
							    A       ,		tf.cast(A       ,		dtype=tensor.dtype					)       ,		message=(
							        F"""The maximum value of {tensor_name} ({tf.math.reduce_max(A					)}) must be smaller than the embedding """
							        F"""layer's input dimension ({embed_dim}). The likely cause is some problem at tokenization time."""
							    )       ,		)
def        UpperCAmelCase (    A	:					Union[str, Any]       ,		A	:					int       ,		A	:					Dict					):
							SCREAMING_SNAKE_CASE       :   List[Any]         =      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.
							SCREAMING_SNAKE_CASE       :   Tuple         =      [x for x in data if len(A					) > 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}"""					)

							SCREAMING_SNAKE_CASE       :   int         =      np.asarray(A					)

							SCREAMING_SNAKE_CASE       :   Any         =      1
							SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      np.array_split(A       ,		A					)

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

							if num_chunks > 1:
														for chunk_id, chunk_data in enumerate(A					):
																					SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      chunk_data
							else:
														SCREAMING_SNAKE_CASE       :   Union[str, Any]         =      data
def        UpperCAmelCase (    A	:					Optional[Any]       ,		A	:					Any					):
							if name in group.attrs:
														SCREAMING_SNAKE_CASE       :   Optional[Any]         =      [n.decode('''utf8'''					) if hasattr(A       ,		'''decode'''					) else n for n in group.attrs[name]]
							else:
														SCREAMING_SNAKE_CASE       :   Optional[int]         =      []
														SCREAMING_SNAKE_CASE       :   List[Any]         =      0
														while "%s%d" % (name, chunk_id) in group.attrs:
																					data.extend(
																					    [n.decode('''utf8'''					) if hasattr(A       ,		'''decode'''					) else n for n in group.attrs['''%s%d''' % (name, chunk_id)]]					)
																					chunk_id += 1
							return data






def        UpperCAmelCase (    A	:					List[str]					):

							def _expand_single_ad_tensor(A	:					List[str]					):
														if isinstance(A       ,		tf.Tensor					) and t.shape.rank == 1:
																					return tf.expand_dims(A       ,		axis=-1					)
														return t

							return tf.nest.map_structure(_expand_single_ad_tensor       ,		A					)









'''simple docstring'''



import unittest

from transformers import is_tf_available
from transformers.testing_utils import require_tf


if is_tf_available():
							import tensorflow as tf
							from tensorflow.python.eager import context
							from tensorflow.python.framework import ops

							from transformers import GradientAccumulator, create_optimizer
@require_tf
class 						lowerCamelCase_				(       unittest.TestCase      ):







						def        __lowercase     (	self :   List[Any]					,     lowerCAmelCase__ :   str					,     lowerCAmelCase__ :   Dict					,     lowerCAmelCase__ :   int					):

													"""simple docstring"""
													self.assertEqual(len(lowerCAmelCase__					)					,     len(lowerCAmelCase__					)					)
													for a, b in zip(lowerCAmelCase__					,     lowerCAmelCase__					):
																				self.assertAlmostEqual(lowerCAmelCase__					,     lowerCAmelCase__					,     delta=lowerCAmelCase__					)







						def        __lowercase     (	self :   Dict					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   List[Any]         =      GradientAccumulator()
													accumulator([tf.constant([1.0, 2.0]					)]					)
													accumulator([tf.constant([-2.0, 1.0]					)]					)
													accumulator([tf.constant([-1.0, 2.0]					)]					)
													with self.assertRaises(lowerCAmelCase__					):
																				accumulator([tf.constant([1.0, 1.0]					), tf.constant([2.0, 2.0]					)]					)
													self.assertEqual(accumulator.step					,     3					)
													self.assertEqual(len(accumulator.gradients					)					,     1					)
													self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist()					,     [-2.0, 5.0]					,     tol=1e-2					)
													accumulator.reset()
													self.assertEqual(accumulator.step					,     0					)
													self.assertListAlmostEqual(accumulator.gradients[0].numpy().tolist()					,     [0.0, 0.0]					,     tol=1e-2					)







						def        __lowercase     (	self :   List[str]					):

													"""simple docstring"""
													SCREAMING_SNAKE_CASE       :   Optional[int]         =      None
													ops.enable_eager_execution_internal()
													SCREAMING_SNAKE_CASE       :   List[Any]         =      tf.config.list_physical_devices('''CPU'''					)
													if len(lowerCAmelCase__					) == 1:
																				tf.config.set_logical_device_configuration(
																				    physical_devices[0]					,     [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()]					)
													SCREAMING_SNAKE_CASE       :   Tuple         =      tf.config.list_logical_devices(device_type='''CPU'''					)
													SCREAMING_SNAKE_CASE       :   List[Any]         =      tf.distribute.MirroredStrategy(devices=devices[:2]					)

													with strategy.scope():
																				SCREAMING_SNAKE_CASE       :   Optional[Any]         =      GradientAccumulator()
																				SCREAMING_SNAKE_CASE       :   Dict         =      tf.Variable([4.0, 3.0]					)
																				SCREAMING_SNAKE_CASE       ,SCREAMING_SNAKE_CASE       :   Optional[int]         =      create_optimizer(5e-5					,     10					,     5					)
																				SCREAMING_SNAKE_CASE       :   List[Any]         =      tf.Variable([0.0, 0.0]					,     trainable=lowerCAmelCase__					)

													def accumulate_on_replica(lowerCAmelCase__ :   List[str]					):
																				accumulator([gradient]					)

													def apply_on_replica():
																				optimizer.apply_gradients(list(zip(accumulator.gradients					,     [variable]					)					)					)

													@tf.function
													def accumulate(lowerCAmelCase__ :   str					,     lowerCAmelCase__ :   List[Any]					):
																				with strategy.scope():
																											SCREAMING_SNAKE_CASE       :   Optional[Any]         =      strategy.experimental_local_results(lowerCAmelCase__					)
																											local_variables[0].assign(lowerCAmelCase__					)
																											local_variables[1].assign(lowerCAmelCase__					)
																											strategy.run(lowerCAmelCase__					,     args=(gradient_placeholder,)					)

													@tf.function
													def apply_grad():
																				with strategy.scope():
																											strategy.run(lowerCAmelCase__					)

													def _check_local_values(lowerCAmelCase__ :   Dict					,     lowerCAmelCase__ :   int					):
																				SCREAMING_SNAKE_CASE       :   Tuple         =      strategy.experimental_local_results(accumulator._gradients[0]					)
																				self.assertListAlmostEqual(values[0].value()					,     lowerCAmelCase__					,     tol=1e-2					)
																				self.assertListAlmostEqual(values[1].value()					,     lowerCAmelCase__					,     tol=1e-2					)

													accumulate([1.0, 2.0]					,     [-1.0, 1.0]					)
													accumulate([3.0, -1.0]					,     [-1.0, -1.0]					)
													accumulate([-2.0, 2.0]					,     [3.0, -2.0]					)
													self.assertEqual(accumulator.step					,     3					)
													_check_local_values([2.0, 3.0]					,     [1.0, -2.0]					)
													apply_grad()
													self.assertListAlmostEqual(variable.value()					,     [4.0, 3.0]					,     tol=1e-2					)
													accumulator.reset()
													self.assertEqual(accumulator.step					,     0					)
													_check_local_values([0.0, 0.0]					,     [0.0, 0.0]					)




