
'''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     UpperCAmelCase_	(						unittest.TestCase					):






						'''simple docstring'''






						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase       ,  _lowercase ):

												"""simple docstring"""



												self.assertEqual(len(_lowercase )       ,  len(_lowercase ) )
												for a, b in zip(_lowercase       ,  _lowercase ):
																		self.assertAlmostEqual(_lowercase       ,  _lowercase       ,  delta=_lowercase )




						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					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(_lowercase ):
																		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 ):

												"""simple docstring"""



												_lowerCAmelCase    		=					None
												ops.enable_eager_execution_internal()
												_lowerCAmelCase    		=					tf.config.list_physical_devices("""CPU""" )
												if len(_lowercase ) == 1:
																		tf.config.set_logical_device_configuration(
																		    physical_devices[0]       ,  [tf.config.LogicalDeviceConfiguration(), tf.config.LogicalDeviceConfiguration()] )
												_lowerCAmelCase    		=					tf.config.list_logical_devices(device_type="""CPU""" )
												_lowerCAmelCase    		=					tf.distribute.MirroredStrategy(devices=devices[:2] )

												with strategy.scope():
																		_lowerCAmelCase    		=					GradientAccumulator()
																		_lowerCAmelCase    		=					tf.Variable([4.0, 3.0] )
																		_lowerCAmelCase		,       _lowerCAmelCase    		=					create_optimizer(5e-5       ,  10       ,  5 )
																		_lowerCAmelCase    		=					tf.Variable([0.0, 0.0]       ,  trainable=_lowercase )

												def accumulate_on_replica(_lowercase ):
																		accumulator([gradient] )

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

												@tf.function
												def accumulate(_lowercase       ,  _lowercase ):
																		with strategy.scope():
																								_lowerCAmelCase    		=					strategy.experimental_local_results(_lowercase )
																								local_variables[0].assign(_lowercase )
																								local_variables[1].assign(_lowercase )
																								strategy.run(_lowercase       ,  args=(gradient_placeholder,) )

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

												def _check_local_values(_lowercase       ,  _lowercase ):
																		_lowerCAmelCase    		=					strategy.experimental_local_results(accumulator._gradients[0] )
																		self.assertListAlmostEqual(values[0].value()       ,  _lowercase       ,  tol=1e-2 )
																		self.assertListAlmostEqual(values[1].value()       ,  _lowercase       ,  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] )


'''simple docstring'''



import builtins
import sys

from ...utils.imports import _is_package_available
from . import cursor, input
from .helpers import Direction, clear_line, forceWrite, linebreak, move_cursor, reset_cursor, writeColor
from .keymap import KEYMAP


_lowercase          =						False
try:
						_lowercase          =						_is_package_available("""google.colab""")
except ModuleNotFoundError:
						pass




@input.register
class     UpperCAmelCase_	:






						'''simple docstring'''






						def __init__(   self       ,  _lowercase = None       ,  _lowercase = [] ):

												"""simple docstring"""



												_lowerCAmelCase    		=					0
												_lowerCAmelCase    		=					choices
												_lowerCAmelCase    		=					prompt
												if sys.platform == "win32":
																		_lowerCAmelCase    		=					"""*"""
												else:
																		_lowerCAmelCase    		=					"""➔ """




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase = "" ):

												"""simple docstring"""



												if sys.platform != "win32":
																		writeColor(self.choices[index]       ,  32       ,  _lowercase )
												else:
																		forceWrite(self.choices[index]       ,  _lowercase )




						def    _lowercase      (   self       ,  _lowercase ):

												"""simple docstring"""



												if index == self.position:
																		forceWrite(F' {self.arrow_char} ' )
																		self.write_choice(_lowercase )
												else:
																		forceWrite(F'    {self.choices[index]}' )
												reset_cursor()




						def    _lowercase      (   self       ,  _lowercase       ,  _lowercase = 1 ):

												"""simple docstring"""



												_lowerCAmelCase    		=					self.position
												if direction == Direction.DOWN:
																		if self.position + 1 >= len(self.choices ):
																								return
																		self.position += num_spaces
												else:
																		if self.position - 1 < 0:
																								return
																		self.position -= num_spaces
												clear_line()
												self.print_choice(_lowercase )
												move_cursor(_lowercase       ,  direction.name )
												self.print_choice(self.position )




						@input.mark(KEYMAP["""up"""] )
						def    _lowercase      (   self ):

												"""simple docstring"""



												self.move_direction(Direction.UP )




						@input.mark(KEYMAP["""down"""] )
						def    _lowercase      (   self ):

												"""simple docstring"""



												self.move_direction(Direction.DOWN )




						@input.mark(KEYMAP["""newline"""] )
						def    _lowercase      (   self ):

												"""simple docstring"""



												move_cursor(len(self.choices ) - self.position       ,  """DOWN""" )
												return self.position




						@input.mark(KEYMAP["""interrupt"""] )
						def    _lowercase      (   self ):

												"""simple docstring"""



												move_cursor(len(self.choices ) - self.position       ,  """DOWN""" )
												raise KeyboardInterrupt




						@input.mark_multiple(*[KEYMAP[str(_lowercase )] for number in range(10 )] )
						def    _lowercase      (   self ):

												"""simple docstring"""



												_lowerCAmelCase    		=					int(chr(self.current_selection ) )
												_lowerCAmelCase    		=					index - self.position
												if index == self.position:
																		return
												if index < len(self.choices ):
																		if self.position > index:
																								self.move_direction(Direction.UP       ,  -movement )
																		elif self.position < index:
																								self.move_direction(Direction.DOWN       ,  _lowercase )
																		else:
																								return
												else:
																		return




						def    _lowercase      (   self       ,  _lowercase = 0 ):

												"""simple docstring"""



												if self.prompt:
																		linebreak()
																		forceWrite(self.prompt       ,  """\n""" )
																		if in_colab:
																								forceWrite("""Please input a choice index (starting from 0), and press enter"""       ,  """\n""" )
																		else:
																								forceWrite("""Please select a choice using the arrow or number keys, and selecting with enter"""       ,  """\n""" )
												_lowerCAmelCase    		=					default_choice
												for i in range(len(self.choices ) ):
																		self.print_choice(_lowercase )
																		forceWrite("""\n""" )
												move_cursor(len(self.choices ) - self.position       ,  """UP""" )
												with cursor.hide():
																		while True:
																								if in_colab:
																														try:
																																				_lowerCAmelCase    		=					int(builtins.input() )
																														except ValueError:
																																				_lowerCAmelCase    		=					default_choice
																								else:
																														_lowerCAmelCase    		=					self.handle_input()
																								if choice is not None:
																														reset_cursor()
																														for _ in range(len(self.choices ) + 1 ):
																																				move_cursor(1       ,  """UP""" )
																																				clear_line()
																														self.write_choice(_lowercase       ,  """\n""" )
																														return choice
