






from __future__ import annotations

import unittest

from transformers import AutoTokenizer, PegasusConfig, is_tf_available
from transformers.testing_utils import require_sentencepiece, require_tf, require_tokenizers, slow
from transformers.utils import cached_property

from ...test_configuration_common import ConfigTester
from ...test_modeling_tf_common import TFModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_tf_available():
						import tensorflow as tf

						from transformers import TFAutoModelForSeqaSeqLM, TFPegasusForConditionalGeneration, TFPegasusModel


@require_tf
class        __UpperCamelCase    :
	__snake_case	:str   =       PegasusConfig
	__snake_case	:List[Any]   =       {}
	__snake_case	:Union[str, Any]   =       'gelu'







	def __init__(  self      :							List[Any]       ,				_lowerCAmelCase      :							int       ,				_lowerCAmelCase      :							List[Any]=13       ,				_lowerCAmelCase      :							Optional[int]=7       ,				_lowerCAmelCase      :							Dict=True       ,				_lowerCAmelCase      :							Tuple=False       ,				_lowerCAmelCase      :							Dict=99       ,				_lowerCAmelCase      :							Union[str, Any]=32       ,				_lowerCAmelCase      :							Union[str, Any]=2       ,				_lowerCAmelCase      :							Any=4       ,				_lowerCAmelCase      :							Any=37       ,				_lowerCAmelCase      :							List[Any]=0.1       ,				_lowerCAmelCase      :							str=0.1       ,				_lowerCAmelCase      :							Tuple=40       ,				_lowerCAmelCase      :							Optional[int]=2       ,				_lowerCAmelCase      :							str=1       ,				_lowerCAmelCase      :							Optional[int]=0       ,				)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  parent
		__lowercase             =  batch_size
		__lowercase             =  seq_length
		__lowercase             =  is_training
		__lowercase             =  use_labels
		__lowercase             =  vocab_size
		__lowercase             =  hidden_size
		__lowercase             =  num_hidden_layers
		__lowercase             =  num_attention_heads
		__lowercase             =  intermediate_size

		__lowercase             =  hidden_dropout_prob
		__lowercase             =  attention_probs_dropout_prob
		__lowercase             =  max_position_embeddings
		__lowercase             =  eos_token_id
		__lowercase             =  pad_token_id
		__lowercase             =  bos_token_id







	def  _a   (  self      :							str			)		-> Optional[Any]:
		"""simple docstring"""







		__lowercase             =  ids_tensor([self.batch_size, self.seq_length - 1]       ,				self.vocab_size			)
		__lowercase             =  tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size			)       ,				1			)
		__lowercase             =  tf.concat([input_ids, eos_tensor]       ,				axis=1			)

		__lowercase             =  ids_tensor([self.batch_size, self.seq_length]       ,				self.vocab_size			)

		__lowercase             =  self.config_cls(
		    vocab_size=self.vocab_size       ,				d_model=self.hidden_size       ,				encoder_layers=self.num_hidden_layers       ,				decoder_layers=self.num_hidden_layers       ,				encoder_attention_heads=self.num_attention_heads       ,				decoder_attention_heads=self.num_attention_heads       ,				encoder_ffn_dim=self.intermediate_size       ,				decoder_ffn_dim=self.intermediate_size       ,				dropout=self.hidden_dropout_prob       ,				attention_dropout=self.attention_probs_dropout_prob       ,				max_position_embeddings=self.max_position_embeddings       ,				eos_token_ids=[2]       ,				bos_token_id=self.bos_token_id       ,				pad_token_id=self.pad_token_id       ,				decoder_start_token_id=self.pad_token_id       ,				**self.config_updates       ,				)
		__lowercase             =  prepare_pegasus_inputs_dict(_lowerCAmelCase       ,				_lowerCAmelCase       ,				_lowerCAmelCase			)
		return config, inputs_dict







	def  _a   (  self      :							Tuple       ,				_lowerCAmelCase      :							List[str]       ,				_lowerCAmelCase      :							List[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  TFPegasusModel(config=_lowerCAmelCase			).get_decoder()
		__lowercase             =  inputs_dict["""input_ids"""]

		__lowercase             =  input_ids[:1, :]
		__lowercase             =  inputs_dict["""attention_mask"""][:1, :]
		__lowercase             =  inputs_dict["""head_mask"""]
		__lowercase             =  1

		# first forward pass
		__lowercase             =  model(_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				head_mask=_lowerCAmelCase       ,				use_cache=_lowerCAmelCase			)

		__lowercase       ,						__lowercase             =  outputs.to_tuple()

		# create hypothetical next token and extent to next_input_ids
		__lowercase             =  ids_tensor((self.batch_size, 3)       ,				config.vocab_size			)
		__lowercase             =  tf.cast(ids_tensor((self.batch_size, 3)       ,				2			)       ,				tf.inta			)

		# append to next input_ids and
		__lowercase             =  tf.concat([input_ids, next_tokens]       ,				axis=-1			)
		__lowercase             =  tf.concat([attention_mask, next_attn_mask]       ,				axis=-1			)

		__lowercase             =  model(_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase			)[0]
		__lowercase             =  model(_lowerCAmelCase       ,				attention_mask=_lowerCAmelCase       ,				past_key_values=_lowerCAmelCase			)[0]

		self.parent.assertEqual(next_tokens.shape[1]       ,				output_from_past.shape[1]			)

		# select random slice
		__lowercase             =  int(ids_tensor((1,)       ,				output_from_past.shape[-1]			)			)
		__lowercase             =  output_from_no_past[:, -3:, random_slice_idx]
		__lowercase             =  output_from_past[:, :, random_slice_idx]

		# test that outputs are equal for slice
		tf.debugging.assert_near(_lowerCAmelCase       ,				_lowerCAmelCase       ,				rtol=1e-3			)





def 				snake_case  (     lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase				,  lowerCamelCase=None				,  lowerCamelCase=None				,  lowerCamelCase=None				,  lowerCamelCase=None				,  lowerCamelCase=None				,  ):




	'''simple docstring'''







	if attention_mask is None:
		__lowercase             =  tf.cast(tf.math.not_equal(lowerCamelCase				,  config.pad_token_id					)				,  tf.inta					)
	if decoder_attention_mask is None:
		__lowercase             =  tf.concat(
		    [
		        tf.ones(decoder_input_ids[:, :1].shape				,  dtype=tf.inta					),
		        tf.cast(tf.math.not_equal(decoder_input_ids[:, 1:]				,  config.pad_token_id					)				,  tf.inta					),
		    ]				,  axis=-1				,  )
	if head_mask is None:
		__lowercase             =  tf.ones((config.encoder_layers, config.encoder_attention_heads)					)
	if decoder_head_mask is None:
		__lowercase             =  tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
	if cross_attn_head_mask is None:
		__lowercase             =  tf.ones((config.decoder_layers, config.decoder_attention_heads)					)
	return {
	    "input_ids": input_ids,
	    "decoder_input_ids": decoder_input_ids,
	    "attention_mask": attention_mask,
	    "decoder_attention_mask": decoder_attention_mask,
	    "head_mask": head_mask,
	    "decoder_head_mask": decoder_head_mask,
	    "cross_attn_head_mask": cross_attn_head_mask,
	}


@require_tf
class        __UpperCamelCase    (     _lowerCAmelCase   ,			_lowerCAmelCase   ,			unittest.TestCase   ):
	__snake_case	:Any   =       (TFPegasusForConditionalGeneration, TFPegasusModel) if is_tf_available() else ()
	__snake_case	:Tuple   =       (TFPegasusForConditionalGeneration,) if is_tf_available() else ()
	__snake_case	:Tuple   =       (
	    {
	        'conversational': TFPegasusForConditionalGeneration,
	        'feature-extraction': TFPegasusModel,
	        'summarization': TFPegasusForConditionalGeneration,
	        'text2text-generation': TFPegasusForConditionalGeneration,
	        'translation': TFPegasusForConditionalGeneration,
	    }
	    if is_tf_available()
	    else {}
	)
	__snake_case	:int   =       True
	__snake_case	:Dict   =       False
	__snake_case	:Dict   =       False







	def  _a   (  self      :							List[str]			)		-> List[str]:
		"""simple docstring"""







		__lowercase             =  TFPegasusModelTester(self			)
		__lowercase             =  ConfigTester(self       ,				config_class=_lowerCAmelCase			)







	def  _a   (  self      :							Dict			)		-> Dict:
		"""simple docstring"""







		self.config_tester.run_common_tests()







	def  _a   (  self      :							Union[str, Any]			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.model_tester.prepare_config_and_inputs_for_common()
		self.model_tester.check_decoder_model_past_large_inputs(*_lowerCAmelCase			)


@require_sentencepiece
@require_tokenizers
@require_tf
class        __UpperCamelCase    (     unittest.TestCase   ):
	__snake_case	:Any   =       [
	    ' PG&E stated it scheduled the blackouts in response to forecasts for high winds amid dry conditions. The aim is to reduce the risk of wildfires. Nearly 800 thousand customers were scheduled to be affected by the shutoffs which were expected to last through at least midday tomorrow.',
	    ' The London trio are up for best UK act and best album, as well as getting two nominations in the best song category."We got told like this morning \'Oh I think you\'re nominated\'", said Dappy."And I was like \'Oh yeah, which one?\' And now we\'ve got nominated for four awards. I mean, wow!"Bandmate Fazer added: "We thought it\'s best of us to come down and mingle with everyone and say hello to the cameras. And now we find we\'ve got four nominations."The band have two shots at the best song prize, getting the nod for their Tynchy Stryder collaboration Number One, and single Strong Again.Their album Uncle B will also go up against records by the likes of Beyonce and Kanye West.N-Dubz picked up the best newcomer Mobo in 2007, but female member Tulisa said they wouldn\'t be too disappointed if they didn\'t win this time around."At the end of the day we\'re grateful to be where we are in our careers."If it don\'t happen then it don\'t happen - live to fight another day and keep on making albums and hits for the fans."Dappy also revealed they could be performing live several times on the night.The group will be doing Number One and also a possible rendition of the War Child single, I Got Soul.The charity song is a  re-working of The Killers\' All These Things That I\'ve Done and is set to feature artists like Chipmunk, Ironik and Pixie Lott.This year\'s Mobos will be held outside of London for the first time, in Glasgow on 30 September.N-Dubz said they were looking forward to performing for their Scottish fans and boasted about their recent shows north of the border."We just done Edinburgh the other day," said Dappy."We smashed up an N-Dubz show over there. We done Aberdeen about three or four months ago - we smashed up that show over there! Everywhere we go we smash it up!" ',
	]
	__snake_case	:List[str]   =       [
	    'California\'s largest electricity provider has cut power to hundreds of thousands of customers in an effort to'
	    ' reduce the risk of wildfires.',
	    'N-Dubz have revealed they\'re "grateful" to have been nominated for four Mobo Awards.',
	]  # differs slightly from pytorch, likely due to numerical differences in linear layers
	__snake_case	:Union[str, Any]   =       'google/pegasus-xsum'







	@cached_property
	def  _a   (  self      :							Optional[Any]			)		-> Tuple:
		"""simple docstring"""







		return AutoTokenizer.from_pretrained(self.model_name			)







	@cached_property
	def  _a   (  self      :							Union[str, Any]			)		-> Any:
		"""simple docstring"""







		__lowercase             =  TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name			)
		return model







	def  _a   (  self      :							Tuple       ,				**_lowerCAmelCase      :							Optional[Any]			)		-> Union[str, Any]:
		"""simple docstring"""







		__lowercase             =  self.translate_src_text(**_lowerCAmelCase			)
		assert self.expected_text == generated_words







	def  _a   (  self      :							str       ,				**_lowerCAmelCase      :							Tuple			)		-> int:
		"""simple docstring"""







		__lowercase             =  self.tokenizer(self.src_text       ,				**_lowerCAmelCase       ,				padding=_lowerCAmelCase       ,				return_tensors="""tf"""			)
		__lowercase             =  self.model.generate(
		    model_inputs.input_ids       ,				attention_mask=model_inputs.attention_mask       ,				num_beams=2       ,				use_cache=_lowerCAmelCase       ,				)
		__lowercase             =  self.tokenizer.batch_decode(generated_ids.numpy()       ,				skip_special_tokens=_lowerCAmelCase			)
		return generated_words







	@slow
	def  _a   (  self      :							Tuple			)		-> Tuple:
		"""simple docstring"""







		self._assert_generated_batch_equal_expected()









import os
import time
import warnings
from dataclasses import dataclass, field
from enum import Enum
from typing import List, Optional, Union

import torch
from filelock import FileLock
from torch.utils.data import Dataset

from ...tokenization_utils_base import PreTrainedTokenizerBase
from ...utils import logging
from ..processors.glue import glue_convert_examples_to_features, glue_output_modes, glue_processors
from ..processors.utils import InputFeatures


__UpperCamelCase      :      Any     						=						logging.get_logger(__name__)


@dataclass
class        __UpperCamelCase    :
	__snake_case	:str   =       field(metadata={'help': 'The name of the task to train on: ' + ', '.join(glue_processors.keys()   )}   )
	__snake_case	:str   =       field(
	    metadata={'help': 'The input data dir. Should contain the .tsv files (or other data files) for the task.'}   )
	__snake_case	:int   =       field(
	    default=1_2_8   ,			metadata={
	        'help': (
	            'The maximum total input sequence length after tokenization. Sequences longer '
	            'than this will be truncated, sequences shorter will be padded.'
	        )
	    }   ,			)
	__snake_case	:bool   =       field(
	    default=_lowerCAmelCase   ,			metadata={'help': 'Overwrite the cached training and evaluation sets'}   )







	def  _a   (  self      :							Dict			)		-> List[Any]:
		"""simple docstring"""







		__lowercase             =  self.task_name.lower()


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:Optional[int]   =       'train'
	__snake_case	:int   =       'dev'
	__snake_case	:Any   =       'test'


class        __UpperCamelCase    (     _lowerCAmelCase   ):
	__snake_case	:GlueDataTrainingArguments
	__snake_case	:str
	__snake_case	:List[InputFeatures]







	def __init__(  self      :							Dict       ,				_lowerCAmelCase      :							GlueDataTrainingArguments       ,				_lowerCAmelCase      :							PreTrainedTokenizerBase       ,				_lowerCAmelCase      :							Optional[int] = None       ,				_lowerCAmelCase      :							Union[str, Split] = Split.train       ,				_lowerCAmelCase      :							Optional[str] = None       ,				)		-> List[Any]:
		"""simple docstring"""







		warnings.warn(
		    """This dataset will be removed from the library soon, preprocessing should be handled with the 🤗 Datasets """
		    """library. You can have a look at this example script for pointers: """
		    """https://github.com/huggingface/transformers/blob/main/examples/pytorch/text-classification/run_glue.py"""       ,				_lowerCAmelCase       ,				)
		__lowercase             =  args
		__lowercase             =  glue_processors[args.task_name]()
		__lowercase             =  glue_output_modes[args.task_name]
		if isinstance(_lowerCAmelCase       ,				_lowerCAmelCase			):
			try:
				__lowercase             =  Split[mode]
			except KeyError:
				raise KeyError("""mode is not a valid split name"""			)
        # Load data features from cache or dataset file
		__lowercase             =  os.path.join(
		    cache_dir if cache_dir is not None else args.data_dir       ,				F'cached_{mode.value}_{tokenizer.__class__.__name__}_{args.max_seq_length}_{args.task_name}'       ,				)
		__lowercase             =  self.processor.get_labels()
		if args.task_name in ["mnli", "mnli-mm"] and tokenizer.__class__.__name__ in (
		    "RobertaTokenizer",
		    "RobertaTokenizerFast",
		    "XLMRobertaTokenizer",
		    "BartTokenizer",
		    "BartTokenizerFast",
		):
			# HACK(label indices are swapped in RoBERTa pretrained model)
			__lowercase       ,						__lowercase             =  label_list[2], label_list[1]
		__lowercase             =  label_list

		# Make sure only the first process in distributed training processes the dataset,
		# and the others will use the cache.
		__lowercase             =  cached_features_file + """.lock"""
		with FileLock(_lowerCAmelCase			):
			if os.path.exists(_lowerCAmelCase			) and not args.overwrite_cache:
				__lowercase             =  time.time()
				__lowercase             =  torch.load(_lowerCAmelCase			)
				logger.info(
				    F'Loading features from cached file {cached_features_file} [took %.3f s]'       ,				time.time() - start			)
			else:
				logger.info(F'Creating features from dataset file at {args.data_dir}'			)

				if mode == Split.dev:
					__lowercase             =  self.processor.get_dev_examples(args.data_dir			)
				elif mode == Split.test:
					__lowercase             =  self.processor.get_test_examples(args.data_dir			)
				else:
					__lowercase             =  self.processor.get_train_examples(args.data_dir			)
				if limit_length is not None:
					__lowercase             =  examples[:limit_length]
				__lowercase             =  glue_convert_examples_to_features(
				    _lowerCAmelCase       ,				_lowerCAmelCase       ,				max_length=args.max_seq_length       ,				label_list=_lowerCAmelCase       ,				output_mode=self.output_mode       ,				)
				__lowercase             =  time.time()
				torch.save(self.features       ,				_lowerCAmelCase			)
				# ^ This seems to take a lot of time so I want to investigate why and how we can improve.
				logger.info(
				    F'Saving features into cached file {cached_features_file} [took {time.time() - start:.3f} s]'			)







	def __len__(  self      :							Dict			)		-> Optional[int]:
		"""simple docstring"""







		return len(self.features			)







	def __getitem__(  self      :							Tuple       ,				_lowerCAmelCase      :							Optional[int]			)		-> InputFeatures:
		"""simple docstring"""







		return self.features[i]







	def  _a   (  self      :							str			)		-> int:
		"""simple docstring"""







		return self.label_list

