





from dataclasses import dataclass, field
from typing import Tuple

from ..utils import cached_property, is_tf_available, logging, requires_backends
from .benchmark_args_utils import BenchmarkArguments


if is_tf_available():
 import tensorflow as tf


_lowerCAmelCase							:					Optional[int]		    =		logging.get_logger(__name__)


@dataclass
class     __magic_name__     (							__UpperCAmelCase							):





     """simple docstring"""



     __UpperCamelCase    			=   [
         'no_inference',
         'no_cuda',
         'no_tpu',
         'no_speed',
         'no_memory',
         'no_env_print',
         'no_multi_process',
     ]



     def __init__(							self				:str	,					**snake_case				:Optional[Any]     ):





        '''simple docstring'''




        for deprecated_arg in self.deprecated_args:
           if deprecated_arg in kwargs:
              A_    : Dict								=	deprecated_arg[3:]
              A_    : List[Any]								=	not kwargs.pop(snake_case     )
              logger.warning(
                  f"{deprecated_arg} is depreciated. Please use --no-{positive_arg} or"
                  f" {positive_arg}={kwargs[positive_arg]}"     )
        A_    : Any								=	kwargs.pop("tpu_name"	,					self.tpu_name     )
        A_    : Tuple								=	kwargs.pop("device_idx"	,					self.device_idx     )
        A_    : List[str]								=	kwargs.pop("eager_mode"	,					self.eager_mode     )
        A_    : Dict								=	kwargs.pop("use_xla"	,					self.use_xla     )
        super().__init__(**snake_case     )

     __UpperCamelCase    			=   field(
         default=__UpperCAmelCase			, metadata={'''help''': '''Name of TPU'''}			, )
     __UpperCamelCase    			=   field(
         default=0			, metadata={'''help''': '''CPU / GPU device index. Defaults to 0.'''}			, )
     __UpperCamelCase    			=   field(default=__UpperCAmelCase			, metadata={'''help''': '''Benchmark models in eager model.'''}							)
     __UpperCamelCase    			=   field(
         default=__UpperCAmelCase			, metadata={
             '''help''': '''Benchmark models using XLA JIT compilation. Note that `eager_model` has to be set to `False`.'''
         }			, )



     @cached_property
     def   SCREAMING_SNAKE_CASE						(							self				:Dict     ):





        '''simple docstring'''




        requires_backends(self	,					["tf"]     )
        A_    : Optional[Any]								=	None
        if self.tpu:
           try:
              if self.tpu_name:
                 A_    : Union[str, Any]								=	tf.distribute.cluster_resolver.TPUClusterResolver(self.tpu_name     )
              else:
                 A_    : Optional[int]								=	tf.distribute.cluster_resolver.TPUClusterResolver()
           except ValueError:
              A_    : Optional[int]								=	None
        return tpu



     @cached_property
     def   SCREAMING_SNAKE_CASE						(							self				:Union[str, Any]     ):





        '''simple docstring'''




        requires_backends(self	,					["tf"]     )
        if self.is_tpu:
           tf.config.experimental_connect_to_cluster(self._setup_tpu     )
           tf.tpu.experimental.initialize_tpu_system(self._setup_tpu     )

           A_    : Dict								=	tf.distribute.TPUStrategy(self._setup_tpu     )
        else:
           # currently no multi gpu is allowed
           if self.is_gpu:
              # TODO: Currently only single GPU is supported
              tf.config.set_visible_devices(self.gpu_list[self.device_idx]	,					"GPU"     )
              A_    : int								=	tf.distribute.OneDeviceStrategy(device=f"/gpu:{self.device_idx}"     )
           else:
              tf.config.set_visible_devices([]	,					"GPU"     )  # disable GPU
              A_    : str								=	tf.distribute.OneDeviceStrategy(device=f"/cpu:{self.device_idx}"     )

        return strategy



     @property
     def   SCREAMING_SNAKE_CASE						(							self				:Optional[Any]     ):





        '''simple docstring'''




        requires_backends(self	,					["tf"]     )
        return self._setup_tpu is not None



     @property
     def   SCREAMING_SNAKE_CASE						(							self				:Any     ):





        '''simple docstring'''




        requires_backends(self	,					["tf"]     )
        return self._setup_strategy



     @property
     def   SCREAMING_SNAKE_CASE						(							self				:Tuple     ):





        '''simple docstring'''




        requires_backends(self	,					["tf"]     )
        return tf.config.list_physical_devices("GPU"     )



     @property
     def   SCREAMING_SNAKE_CASE						(							self				:Union[str, Any]     ):





        '''simple docstring'''




        requires_backends(self	,					["tf"]     )
        if self.cuda:
           return len(self.gpu_list     )
        return 0





     @property
     def   SCREAMING_SNAKE_CASE						(							self				:int     ):





        '''simple docstring'''




        return self.n_gpu > 0





'''simple docstring'''




import unittest

import numpy as np
import torch

from .utils_summarization import build_mask, compute_token_type_ids, process_story, truncate_or_pad







class 	_lowerCAmelCase							(			unittest.TestCase ):


	def     _a	(self							):
				A_	:						Optional[Any]	=     10


	def     _a	(self							):
				A_	:						Dict	=     [1, 2, 3, 4]
				A_	:						List[Any]	=     [1, 2, 3, 4, 0, 0, 0, 0, 0, 0]
				self.assertEqual(truncate_or_pad(lowercase       ,      self.block_size       ,      0							)       ,      lowercase							)


	def     _a	(self							):
				A_	:						List[Any]	=     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
				A_	:						Tuple	=     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
				self.assertEqual(truncate_or_pad(lowercase       ,      self.block_size       ,      0							)       ,      lowercase							)


	def     _a	(self							):
				A_	:						Optional[Any]	=     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
				A_	:						Any	=     [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
				self.assertEqual(truncate_or_pad(lowercase       ,      self.block_size       ,      0							)       ,      lowercase							)


	def     _a	(self							):
				A_	:						List[str]	=     """It was the year of Our Lord one thousand seven hundred and
        seventy-five.\n\nSpiritual revelations were conceded to England at that
        favoured period, as at this."""
				A_,    A_	:						Dict	=     process_story(lowercase							)
				self.assertEqual(lowercase       ,      []							)


	def     _a	(self							):
				A_	:						Optional[int]	=     """"""
				A_,    A_	:						List[str]	=     process_story(lowercase							)
				self.assertEqual(lowercase       ,      []							)
				self.assertEqual(lowercase       ,      []							)


	def     _a	(self							):
				A_	:						Optional[Any]	=     (
				    """It was the year of Our Lord one thousand seven hundred and """
				    """seventy-five\n\nSpiritual revelations were conceded to England """
				    """at that favoured period, as at this.\n@highlight\n\nIt was the best of times"""
				)
				A_,    A_	:						int	=     process_story(lowercase							)

				A_	:						Optional[Any]	=     [
				    """It was the year of Our Lord one thousand seven hundred and seventy-five.""",
				    """Spiritual revelations were conceded to England at that favoured period, as at this.""",
				]
				self.assertEqual(lowercase       ,      lowercase							)

				A_	:						Dict	=     ["""It was the best of times."""]
				self.assertEqual(lowercase       ,      lowercase							)


	def     _a	(self							):
				A_	:						Optional[int]	=     torch.tensor([1, 2, 3, 4]							)
				A_	:						Dict	=     torch.tensor([1, 1, 1, 1]							)
				np.testing.assert_array_equal(build_mask(lowercase       ,      0							).numpy()       ,      expected.numpy()							)


	def     _a	(self							):
				A_	:						str	=     torch.tensor([1, 2, 3, 4, 23, 23, 23]							)
				A_	:						str	=     torch.tensor([1, 1, 1, 1, 0, 0, 0]							)
				np.testing.assert_array_equal(build_mask(lowercase       ,      23							).numpy()       ,      expected.numpy()							)


	def     _a	(self							):
				A_	:						Any	=     torch.tensor([8, 2, 3, 4, 1, 1, 1]							)
				A_	:						List[str]	=     torch.tensor([1, 1, 1, 1, 0, 0, 0]							)
				np.testing.assert_array_equal(build_mask(lowercase       ,      1							).numpy()       ,      expected.numpy()							)


	def     _a	(self							):
				A_	:						List[Any]	=     101
				A_	:						List[Any]	=     torch.tensor([[1, 2, 3, 4, 5, 6], [1, 2, 3, 101, 5, 6], [1, 101, 3, 4, 101, 6]]							)
				A_	:						List[str]	=     torch.tensor([[1, 1, 1, 1, 1, 1], [1, 1, 1, 0, 0, 0], [1, 0, 0, 0, 1, 1]]							)

				A_	:						Dict	=     compute_token_type_ids(lowercase       ,      lowercase							)
				np.testing.assert_array_equal(lowercase       ,      lowercase							)