




"""simple docstring"""
import json
import logging
import os
import re
import sys
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional, Union

import datasets
import numpy as np
import torch
import torchaudio
from packaging import version
from torch import nn

import transformers
from transformers import (
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    WavaVecaCTCTokenizer,
    WavaVecaFeatureExtractor,
    WavaVecaForCTC,
    WavaVecaProcessor,
    is_apex_available,
    set_seed,
)
from transformers.trainer_utils import get_last_checkpoint, is_main_process


if is_apex_available():
					from apex import amp


if version.parse(version.parse(torch.__version__).base_version) >= version.parse('''1.6'''):
					a_				:    List[str]										=     True
					from torch.cuda.amp import autocast

a_				:    int										=     logging.getLogger(__name__)





def 						UpperCAmelCase				(			A__:    Any=None							,				A__:    List[Any]=None     )  ->     List[Any]:
			return field(default_factory=lambda: default							,				metadata=A__     )

@dataclass
class __lowercase:




					'''simple docstring'''


					__a						:						str     		= field(
					    metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}				)
					__a						:						Optional[str]     		= field(
					    default=lowercase__	,	metadata={'help': 'Where do you want to store the pretrained models downloaded from huggingface.co'}	,	)
					__a						:						Optional[bool]     		= field(
					    default=lowercase__	,	metadata={'help': 'Whether to freeze the feature extractor layers of the model.'}				)
					__a						:						Optional[float]     		= field(
					    default=0.1	,	metadata={'help': 'The dropout ratio for the attention probabilities.'}				)
					__a						:						Optional[float]     		= field(
					    default=0.1	,	metadata={'help': 'The dropout ratio for activations inside the fully connected layer.'}				)
					__a						:						Optional[float]     		= field(
					    default=0.1	,	metadata={
					        'help': 'The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler.'
					    }	,	)
					__a						:						Optional[float]     		= field(
					    default=0.1	,	metadata={'help': 'The dropout probabilitiy for all 1D convolutional layers in feature extractor.'}	,	)
					__a						:						Optional[float]     		= field(
					    default=0.0_5	,	metadata={
					        'help': (
					            'Propability of each feature vector along the time axis to be chosen as the start of the vector'
					            'span to be masked. Approximately ``mask_time_prob * sequence_length // mask_time_length`` feature'
					            'vectors will be masked along the time axis. This is only relevant if ``apply_spec_augment is True``.'
					        )
					    }	,	)
					__a						:						Optional[float]     		= field(default=0.0	,	metadata={'help': 'The LayerDrop probability.'}				)



@dataclass
class __lowercase:




					'''simple docstring'''


					__a						:						Optional[str]     		= field(
					    default=lowercase__	,	metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'}				)
					__a						:						Optional[str]     		= field(
					    default='train+validation'	,	metadata={
					        'help': 'The name of the training data set split to use (via the datasets library). Defaults to \'train\''
					    }	,	)
					__a						:						bool     		= field(
					    default=lowercase__	,	metadata={'help': 'Overwrite the cached preprocessed datasets or not.'}				)
					__a						:						Optional[int]     		= field(
					    default=lowercase__	,	metadata={'help': 'The number of processes to use for the preprocessing.'}	,	)
					__a						:						Optional[int]     		= field(
					    default=lowercase__	,	metadata={
					        'help': (
					            'For debugging purposes or quicker training, truncate the number of training examples to this '
					            'value if set.'
					        )
					    }	,	)
					__a						:						Optional[int]     		= field(
					    default=lowercase__	,	metadata={
					        'help': (
					            'For debugging purposes or quicker training, truncate the number of validation examples to this '
					            'value if set.'
					        )
					    }	,	)
					__a						:						List[str]     		= list_field(
					    default=[',', '?', '.', '!', '-', ';', ':', '""', '%', '\'', '"', '�']	,	metadata={'help': 'A list of characters to remove from the transcripts.'}	,	)



@dataclass
class __lowercase:




					'''simple docstring'''


					__a						:						WavaVecaProcessor
					__a						:						Union[bool, str]     		= True
					__a						:						Optional[int]     		= None
					__a						:						Optional[int]     		= None
					__a						:						Optional[int]     		= None
					__a						:						Optional[int]     		= None
					def __call__(    self						,	__a     ):
								# split inputs and labels since they have to be of different lenghts and need
								# different padding methods
								__lowerCamelCase					:	Union[str, Any]	       =				[{'input_values': feature['input_values']} for feature in features]
								__lowerCamelCase					:	Dict	       =				[{'input_ids': feature['labels']} for feature in features]

								__lowerCamelCase					:	Tuple	       =				self.processor.pad(
								    __a						,	padding=self.padding						,	max_length=self.max_length						,	pad_to_multiple_of=self.pad_to_multiple_of						,	return_tensors='pt'						,	)
								__lowerCamelCase					:	Union[str, Any]	       =				self.processor.pad(
								    labels=__a						,	padding=self.padding						,	max_length=self.max_length_labels						,	pad_to_multiple_of=self.pad_to_multiple_of_labels						,	return_tensors='pt'						,	)

								# replace padding with -100 to ignore loss correctly
								__lowerCamelCase					:	List[str]	       =				labels_batch['input_ids'].masked_fill(labels_batch.attention_mask.ne(1     )						,	-100     )

								__lowerCamelCase					:	Any	       =				labels

								return batch



class __lowercase(      lowercase__				):




					'''simple docstring'''


					def     snake_case_				(    self						,	__a						,	__a     ):
								model.train()
								__lowerCamelCase					:	Union[str, Any]	       =				self._prepare_inputs(__a     )

								if self.use_amp:
											with autocast():
														__lowerCamelCase					:	Union[str, Any]	       =				self.compute_loss(__a						,	__a     )
								else:
											__lowerCamelCase					:	int	       =				self.compute_loss(__a						,	__a     )

								if self.args.n_gpu > 1:
											if model.module.config.ctc_loss_reduction == "mean":
														__lowerCamelCase					:	Optional[int]	       =				loss.mean()
											elif model.module.config.ctc_loss_reduction == "sum":
														__lowerCamelCase					:	List[Any]	       =				loss.sum() / (inputs['labels'] >= 0).sum()
											else:
														raise ValueError(f'''{model.config.ctc_loss_reduction} is not valid. Choose one of [\'mean\', \'sum\']'''     )

								if self.args.gradient_accumulation_steps > 1:
											__lowerCamelCase					:	Optional[int]	       =				loss / self.args.gradient_accumulation_steps

								if self.use_amp:
											self.scaler.scale(__a     ).backward()
								elif self.use_apex:
											with amp.scale_loss(__a						,	self.optimizer     ) as scaled_loss:
														scaled_loss.backward()
								elif self.deepspeed:
											self.deepspeed.backward(__a     )
								else:
											loss.backward()

								return loss.detach()





def 						UpperCAmelCase				(			)  ->     Dict:
			# See all possible arguments in src/transformers/training_args.py
			# or by passing the --help flag to this script.
			# We now keep distinct sets of args, for a cleaner separation of concerns.

			__lowerCamelCase					:	List[str]	       =				HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)     )
			if len(sys.argv     ) == 2 and sys.argv[1].endswith('.json'     ):
						# If we pass only one argument to the script and it's the path to a json file,
						# let's parse it to get our arguments.
						__lowerCamelCase       ,      __lowerCamelCase       ,      __lowerCamelCase					:	Tuple	       =				parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
			else:
						__lowerCamelCase       ,      __lowerCamelCase       ,      __lowerCamelCase					:	Optional[int]	       =				parser.parse_args_into_dataclasses()

			# Detecting last checkpoint.
			__lowerCamelCase					:	Optional[int]	       =				None
			if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
						__lowerCamelCase					:	Optional[int]	       =				get_last_checkpoint(training_args.output_dir     )
						if last_checkpoint is None and len(os.listdir(training_args.output_dir     )     ) > 0:
									raise ValueError(
									    f'''Output directory ({training_args.output_dir}) already exists and is not empty. '''
									    'Use --overwrite_output_dir to overcome.'     )
						elif last_checkpoint is not None:
									logger.info(
									    f'''Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '''
									    'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'     )

    # Setup logging
			logging.basicConfig(
			    format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'							,				datefmt='%m/%d/%Y %H:%M:%S'							,				handlers=[logging.StreamHandler(sys.stdout     )]							,				)
			logger.setLevel(logging.INFO if is_main_process(training_args.local_rank     ) else logging.WARN     )

			# Log on each process the small summary:
			logger.warning(
			    f'''Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'''
			    + f'''distributed training: {bool(training_args.local_rank != -1     )}, 16-bits training: {training_args.fpaa}'''     )
			# Set the verbosity to info of the Transformers logger (on main process only):
			if is_main_process(training_args.local_rank     ):
						transformers.utils.logging.set_verbosity_info()
			logger.info('Training/evaluation parameters %s'							,				A__     )

			# Set seed before initializing model.
			set_seed(training_args.seed     )

			# Get the datasets:
			__lowerCamelCase					:	List[Any]	       =				datasets.load_dataset(
			    'common_voice'							,				data_args.dataset_config_name							,				split=data_args.train_split_name     )
			__lowerCamelCase					:	Any	       =				datasets.load_dataset('common_voice'							,				data_args.dataset_config_name							,				split='test'     )

			# Create and save tokenizer
			__lowerCamelCase					:	List[Any]	       =				f'''[{"".join(data_args.chars_to_ignore     )}]'''

			def remove_special_characters(A__:    Union[str, Any]     ):
						__lowerCamelCase					:	str	       =				re.sub(A__							,				''							,				batch['sentence']     ).lower() + ' '
						return batch

			__lowerCamelCase					:	Optional[int]	       =				train_dataset.map(A__							,				remove_columns=['sentence']     )
			__lowerCamelCase					:	Tuple	       =				eval_dataset.map(A__							,				remove_columns=['sentence']     )

			def extract_all_chars(A__:    str     ):
						__lowerCamelCase					:	Optional[int]	       =				' '.join(batch['text']     )
						__lowerCamelCase					:	Optional[int]	       =				list(set(A__     )     )
						return {"vocab": [vocab], "all_text": [all_text]}

			__lowerCamelCase					:	Optional[int]	       =				train_dataset.map(
			    A__							,				batched=A__							,				batch_size=-1							,				keep_in_memory=A__							,				remove_columns=train_dataset.column_names							,				)
			__lowerCamelCase					:	List[Any]	       =				train_dataset.map(
			    A__							,				batched=A__							,				batch_size=-1							,				keep_in_memory=A__							,				remove_columns=eval_dataset.column_names							,				)

			__lowerCamelCase					:	List[str]	       =				list(set(vocab_train['vocab'][0]     ) | set(vocab_test['vocab'][0]     )     )
			__lowerCamelCase					:	List[Any]	       =				{v: k for k, v in enumerate(A__     )}
			__lowerCamelCase					:	Optional[Any]	       =				vocab_dict[' ']
			del vocab_dict[" "]
			__lowerCamelCase					:	List[str]	       =				len(A__     )
			__lowerCamelCase					:	int	       =				len(A__     )

			with open('vocab.json'							,				'w'     ) as vocab_file:
						json.dump(A__							,				A__     )

			# Load pretrained model and tokenizer
			#
			# Distributed training:
			# The .from_pretrained methods guarantee that only one local process can concurrently
			# download model & vocab.
			__lowerCamelCase					:	Optional[Any]	       =				WavaVecaCTCTokenizer(
			    'vocab.json'							,				unk_token='[UNK]'							,				pad_token='[PAD]'							,				word_delimiter_token='|'							,				)
			__lowerCamelCase					:	Any	       =				WavaVecaFeatureExtractor(
			    feature_size=1							,				sampling_rate=16000							,				padding_value=0.0							,				do_normalize=A__							,				return_attention_mask=A__     )
			__lowerCamelCase					:	List[Any]	       =				WavaVecaProcessor(feature_extractor=A__							,				tokenizer=A__     )
			__lowerCamelCase					:	Union[str, Any]	       =				WavaVecaForCTC.from_pretrained(
			    model_args.model_name_or_path							,				cache_dir=model_args.cache_dir							,				activation_dropout=model_args.activation_dropout							,				attention_dropout=model_args.attention_dropout							,				hidden_dropout=model_args.hidden_dropout							,				feat_proj_dropout=model_args.feat_proj_dropout							,				mask_time_prob=model_args.mask_time_prob							,				gradient_checkpointing=training_args.gradient_checkpointing							,				layerdrop=model_args.layerdrop							,				ctc_loss_reduction='mean'							,				pad_token_id=processor.tokenizer.pad_token_id							,				vocab_size=len(processor.tokenizer     )							,				)

			if data_args.max_train_samples is not None:
						__lowerCamelCase					:	str	       =				min(len(A__     )							,				data_args.max_train_samples     )
						__lowerCamelCase					:	str	       =				train_dataset.select(range(A__     )     )

			if data_args.max_val_samples is not None:
						__lowerCamelCase					:	List[str]	       =				eval_dataset.select(range(data_args.max_val_samples     )     )

			__lowerCamelCase					:	int	       =				torchaudio.transforms.Resample(48000							,				16000     )

			# Preprocessing the datasets.
			# We need to read the aduio files as arrays and tokenize the targets.
			def speech_file_to_array_fn(A__:    Optional[int]     ):
						__lowerCamelCase       ,      __lowerCamelCase					:	int	       =				torchaudio.load(batch['path']     )
						__lowerCamelCase					:	Any	       =				resampler(A__     ).squeeze().numpy()
						__lowerCamelCase					:	List[str]	       =				16000
						__lowerCamelCase					:	Union[str, Any]	       =				batch['text']
						return batch

			__lowerCamelCase					:	Union[str, Any]	       =				train_dataset.map(
			    A__							,				remove_columns=train_dataset.column_names							,				num_proc=data_args.preprocessing_num_workers							,				)
			__lowerCamelCase					:	List[str]	       =				eval_dataset.map(
			    A__							,				remove_columns=eval_dataset.column_names							,				num_proc=data_args.preprocessing_num_workers							,				)

			def prepare_dataset(A__:    Dict     ):
						# check that all files have the correct sampling rate
						assert (
						    len(set(batch['sampling_rate']     )     ) == 1
						), f'''Make sure all inputs have the same sampling rate of {processor.feature_extractor.sampling_rate}.'''

						__lowerCamelCase					:	Optional[Any]	       =				processor(
						    audio=batch['speech']							,				text=batch['target_text']							,				sampling_rate=batch['sampling_rate'][0]     )
						batch.update(A__     )
						return batch

			__lowerCamelCase					:	str	       =				train_dataset.map(
			    A__							,				remove_columns=train_dataset.column_names							,				batch_size=training_args.per_device_train_batch_size							,				batched=A__							,				num_proc=data_args.preprocessing_num_workers							,				)
			__lowerCamelCase					:	Optional[int]	       =				eval_dataset.map(
			    A__							,				remove_columns=eval_dataset.column_names							,				batch_size=training_args.per_device_train_batch_size							,				batched=A__							,				num_proc=data_args.preprocessing_num_workers							,				)

			# Metric
			__lowerCamelCase					:	Optional[Any]	       =				datasets.load_metric('wer'     )

			def compute_metrics(A__:    Tuple     ):
						__lowerCamelCase					:	int	       =				pred.predictions
						__lowerCamelCase					:	Optional[Any]	       =				np.argmax(A__							,				axis=-1     )

						__lowerCamelCase					:	int	       =				processor.tokenizer.pad_token_id

						__lowerCamelCase					:	Optional[int]	       =				processor.batch_decode(A__     )
						# we do not want to group tokens when computing the metrics
						__lowerCamelCase					:	Tuple	       =				processor.batch_decode(pred.label_ids							,				group_tokens=A__     )

						__lowerCamelCase					:	Dict	       =				wer_metric.compute(predictions=A__							,				references=A__     )

						return {"wer": wer}

			if model_args.freeze_feature_extractor:
						model.freeze_feature_extractor()

			# Data collator
			__lowerCamelCase					:	Union[str, Any]	       =				DataCollatorCTCWithPadding(processor=A__							,				padding=A__     )

			# Initialize our Trainer
			__lowerCamelCase					:	int	       =				CTCTrainer(
			    model=A__							,				data_collator=A__							,				args=A__							,				compute_metrics=A__							,				train_dataset=train_dataset if training_args.do_train else None							,				eval_dataset=eval_dataset if training_args.do_eval else None							,				tokenizer=processor.feature_extractor							,				)

			# Training
			if training_args.do_train:
						if last_checkpoint is not None:
									__lowerCamelCase					:	Any	       =				last_checkpoint
						elif os.path.isdir(model_args.model_name_or_path     ):
									__lowerCamelCase					:	Optional[Any]	       =				model_args.model_name_or_path
						else:
									__lowerCamelCase					:	Any	       =				None

						# Save the feature_extractor and the tokenizer
						if is_main_process(training_args.local_rank     ):
									processor.save_pretrained(training_args.output_dir     )

						__lowerCamelCase					:	str	       =				trainer.train(resume_from_checkpoint=A__     )
						trainer.save_model()

						__lowerCamelCase					:	Dict	       =				train_result.metrics
						__lowerCamelCase					:	Optional[int]	       =				(
						    data_args.max_train_samples if data_args.max_train_samples is not None else len(A__     )
						)
						__lowerCamelCase					:	Optional[Any]	       =				min(A__							,				len(A__     )     )

						trainer.log_metrics('train'							,				A__     )
						trainer.save_metrics('train'							,				A__     )
						trainer.save_state()

			# Evaluation
			__lowerCamelCase					:	str	       =				{}
			if training_args.do_eval:
						logger.info('*** Evaluate ***'     )
						__lowerCamelCase					:	Dict	       =				trainer.evaluate()
						__lowerCamelCase					:	Optional[int]	       =				data_args.max_val_samples if data_args.max_val_samples is not None else len(A__     )
						__lowerCamelCase					:	Union[str, Any]	       =				min(A__							,				len(A__     )     )

						trainer.log_metrics('eval'							,				A__     )
						trainer.save_metrics('eval'							,				A__     )

			return results


if __name__ == "__main__":
					main()









"""simple docstring"""
from __future__ import annotations

import unittest

from transformers import LEDConfig, is_tf_available
from transformers.testing_utils import require_tf, slow

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 TFLEDForConditionalGeneration, TFLEDModel

@require_tf
class __lowercase:




					'''simple docstring'''


					__a						:						Optional[Any]     		= LEDConfig
					__a						:						Dict     		= {}
					__a						:						int     		= 'gelu'
					def __init__(    self						,	__a						,	__a=13						,	__a=7						,	__a=True						,	__a=False						,	__a=99						,	__a=32						,	__a=2						,	__a=4						,	__a=37						,	__a=0.1						,	__a=0.1						,	__a=20						,	__a=2						,	__a=1						,	__a=0						,	__a=4						,	):
								__lowerCamelCase					:	str	       =				parent
								__lowerCamelCase					:	Optional[int]	       =				batch_size
								__lowerCamelCase					:	List[str]	       =				seq_length
								__lowerCamelCase					:	Optional[Any]	       =				is_training
								__lowerCamelCase					:	Dict	       =				use_labels
								__lowerCamelCase					:	Any	       =				vocab_size
								__lowerCamelCase					:	int	       =				hidden_size
								__lowerCamelCase					:	Any	       =				num_hidden_layers
								__lowerCamelCase					:	Union[str, Any]	       =				num_attention_heads
								__lowerCamelCase					:	List[str]	       =				intermediate_size

								__lowerCamelCase					:	str	       =				hidden_dropout_prob
								__lowerCamelCase					:	Union[str, Any]	       =				attention_probs_dropout_prob
								__lowerCamelCase					:	Any	       =				max_position_embeddings
								__lowerCamelCase					:	str	       =				eos_token_id
								__lowerCamelCase					:	str	       =				pad_token_id
								__lowerCamelCase					:	str	       =				bos_token_id
								__lowerCamelCase					:	int	       =				attention_window

								# `ModelTesterMixin.test_attention_outputs` is expecting attention tensors to be of size
								# [num_attention_heads, encoder_seq_length, encoder_key_length], but TFLongformerSelfAttention
								# returns attention of shape [num_attention_heads, encoder_seq_length, self.attention_window + 1]
								# because its local attention only attends to `self.attention_window` and one before and one after
								__lowerCamelCase					:	Dict	       =				self.attention_window + 2

								# because of padding `encoder_seq_length`, is different from `seq_length`. Relevant for
								# the `test_attention_outputs` and `test_hidden_states_output` tests
								__lowerCamelCase					:	int	       =				(
								    self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window
								)
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	Tuple	       =				ids_tensor([self.batch_size, self.seq_length - 1]						,	self.vocab_size     )
								__lowerCamelCase					:	Optional[int]	       =				tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size     )						,	1     )
								__lowerCamelCase					:	Union[str, Any]	       =				tf.concat([input_ids, eos_tensor]						,	axis=1     )

								__lowerCamelCase					:	Any	       =				ids_tensor([self.batch_size, self.seq_length]						,	self.vocab_size     )

								__lowerCamelCase					:	Dict	       =				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						,	attention_window=self.attention_window						,	**self.config_updates						,	)
								__lowerCamelCase					:	int	       =				prepare_led_inputs_dict(__a						,	__a						,	__a     )
								__lowerCamelCase					:	Union[str, Any]	       =				tf.concat(
								    [tf.zeros_like(__a     )[:, :-1], tf.ones_like(__a     )[:, -1:]]						,	axis=-1						,	)
								__lowerCamelCase					:	Union[str, Any]	       =				global_attention_mask
								return config, inputs_dict





					def     snake_case_				(    self						,	__a						,	__a     ):
								__lowerCamelCase					:	Optional[int]	       =				TFLEDModel(config=__a     ).get_decoder()
								__lowerCamelCase					:	List[str]	       =				inputs_dict['input_ids']

								__lowerCamelCase					:	Dict	       =				input_ids[:1, :]
								__lowerCamelCase					:	Any	       =				inputs_dict['attention_mask'][:1, :]
								__lowerCamelCase					:	Tuple	       =				1

								# first forward pass
								__lowerCamelCase					:	List[str]	       =				model(__a						,	attention_mask=__a						,	use_cache=__a     )

								__lowerCamelCase       ,      __lowerCamelCase					:	int	       =				outputs.to_tuple()

								# create hypothetical next token and extent to next_input_ids
								__lowerCamelCase					:	Optional[int]	       =				ids_tensor((self.batch_size, 3)						,	config.vocab_size     )
								__lowerCamelCase					:	List[str]	       =				tf.cast(ids_tensor((self.batch_size, 3)						,	2     )						,	tf.inta     )

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

								__lowerCamelCase					:	Dict	       =				model(__a						,	attention_mask=__a     )[0]
								__lowerCamelCase					:	Optional[int]	       =				model(__a						,	attention_mask=__a						,	past_key_values=__a     )[0]

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

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

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





def 						UpperCAmelCase				(			A__:    Any							,				A__:    Union[str, Any]							,				A__:    Dict							,				A__:    int=None							,				A__:    str=None							,				A__:    Tuple=None							,				A__:    List[Any]=None							,				)  ->     Optional[Any]:
			if attention_mask is None:
						__lowerCamelCase					:	Optional[int]	       =				tf.cast(tf.math.not_equal(A__							,				config.pad_token_id     )							,				tf.inta     )
			if decoder_attention_mask is None:
						__lowerCamelCase					:	Dict	       =				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:
						__lowerCamelCase					:	Dict	       =				tf.ones((config.encoder_layers, config.encoder_attention_heads)     )
			if decoder_head_mask is None:
						__lowerCamelCase					:	Tuple	       =				tf.ones((config.decoder_layers, config.decoder_attention_heads)     )
			return {
			    "input_ids": input_ids,
			    "attention_mask": attention_mask,
			    "decoder_input_ids": decoder_input_ids,
			    "decoder_attention_mask": decoder_attention_mask,
			    "head_mask": head_mask,
			    "decoder_head_mask": decoder_head_mask,
			}

@require_tf
class __lowercase(      lowercase__	,	lowercase__	,	unittest.TestCase				):




					'''simple docstring'''


					__a						:						Union[str, Any]     		= (TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else ()
					__a						:						Any     		= (TFLEDForConditionalGeneration,) if is_tf_available() else ()
					__a						:						str     		= (
					    {
					        'conversational': TFLEDForConditionalGeneration,
					        'feature-extraction': TFLEDModel,
					        'summarization': TFLEDForConditionalGeneration,
					        'text2text-generation': TFLEDForConditionalGeneration,
					        'translation': TFLEDForConditionalGeneration,
					    }
					    if is_tf_available()
					    else {}
					)
					__a						:						Union[str, Any]     		= True
					__a						:						str     		= False
					__a						:						Dict     		= False
					__a						:						List[Any]     		= False
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	int	       =				TFLEDModelTester(self     )
								__lowerCamelCase					:	List[str]	       =				ConfigTester(self						,	config_class=__a     )
					def     snake_case_				(    self     ):
								self.config_tester.run_common_tests()
					def     snake_case_				(    self     ):
								__lowerCamelCase					:	Optional[int]	       =				self.model_tester.prepare_config_and_inputs_for_common()
								self.model_tester.check_decoder_model_past_large_inputs(*__a     )
					def     snake_case_				(    self     ):
								__lowerCamelCase       ,      __lowerCamelCase					:	Optional[Any]	       =				self.model_tester.prepare_config_and_inputs_for_common()
								__lowerCamelCase					:	Optional[Any]	       =				tf.zeros_like(inputs_dict['attention_mask']     )
								__lowerCamelCase					:	Any	       =				2
								__lowerCamelCase					:	Dict	       =				tf.where(
								    tf.range(self.model_tester.seq_length     )[None, :] < num_global_attn_indices						,	1						,	inputs_dict['global_attention_mask']						,	)

								__lowerCamelCase					:	List[Any]	       =				True
								__lowerCamelCase					:	Tuple	       =				self.model_tester.seq_length
								__lowerCamelCase					:	Dict	       =				self.model_tester.encoder_seq_length

								def check_decoder_attentions_output(__a     ):
											__lowerCamelCase					:	List[Any]	       =				outputs.decoder_attentions
											self.assertEqual(len(__a     )						,	self.model_tester.num_hidden_layers     )
											self.assertListEqual(
											    list(decoder_attentions[0].shape[-3:]     )						,	[self.model_tester.num_attention_heads, seq_length, seq_length]						,	)

								def check_encoder_attentions_output(__a     ):
											__lowerCamelCase					:	List[str]	       =				[t.numpy() for t in outputs.encoder_attentions]
											__lowerCamelCase					:	Optional[Any]	       =				[t.numpy() for t in outputs.encoder_global_attentions]
											self.assertEqual(len(__a     )						,	self.model_tester.num_hidden_layers     )
											self.assertEqual(len(__a     )						,	self.model_tester.num_hidden_layers     )
											self.assertListEqual(
											    list(attentions[0].shape[-3:]     )						,	[self.model_tester.num_attention_heads, seq_length, seq_length]						,	)
											self.assertListEqual(
											    list(global_attentions[0].shape[-3:]     )						,	[self.model_tester.num_attention_heads, encoder_seq_length, num_global_attn_indices]						,	)

								for model_class in self.all_model_classes:
											__lowerCamelCase					:	int	       =				True
											__lowerCamelCase					:	int	       =				False
											__lowerCamelCase					:	Tuple	       =				False
											__lowerCamelCase					:	List[Any]	       =				model_class(__a     )
											__lowerCamelCase					:	Optional[Any]	       =				model(self._prepare_for_class(__a						,	__a     )     )
											__lowerCamelCase					:	Tuple	       =				len(__a     )
											self.assertEqual(config.output_hidden_states						,	__a     )
											check_encoder_attentions_output(__a     )

											if self.is_encoder_decoder:
														__lowerCamelCase					:	Any	       =				model_class(__a     )
														__lowerCamelCase					:	List[str]	       =				model(self._prepare_for_class(__a						,	__a     )     )
														self.assertEqual(config.output_hidden_states						,	__a     )
														check_decoder_attentions_output(__a     )

											# Check that output attentions can also be changed via the config
											del inputs_dict["output_attentions"]
											__lowerCamelCase					:	Tuple	       =				True
											__lowerCamelCase					:	Dict	       =				model_class(__a     )
											__lowerCamelCase					:	List[Any]	       =				model(self._prepare_for_class(__a						,	__a     )     )
											self.assertEqual(config.output_hidden_states						,	__a     )
											check_encoder_attentions_output(__a     )

											# Check attention is always last and order is fine
											__lowerCamelCase					:	List[Any]	       =				True
											__lowerCamelCase					:	int	       =				True
											__lowerCamelCase					:	List[str]	       =				model_class(__a     )
											__lowerCamelCase					:	Dict	       =				model(self._prepare_for_class(__a						,	__a     )     )

											self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1)						,	len(__a     )     )
											self.assertEqual(model.config.output_hidden_states						,	__a     )
											check_encoder_attentions_output(__a     )
					@unittest.skip('LED keeps using potentially symbolic tensors in conditionals and breaks tracing.'     )
					def     snake_case_				(    self     ):
								pass





					def     snake_case_				(    self     ):
								# TODO: Head-masking not yet implement
								pass





def 						UpperCAmelCase				(			A__:    Union[str, Any]     )  ->     List[Any]:
			return tf.constant(A__							,				dtype=tf.intaa     )


a_				:    Tuple										=     1e-4






@slow
@require_tf
class __lowercase(      unittest.TestCase				):




					'''simple docstring'''


					def     snake_case_				(    self     ):
								__lowerCamelCase					:	Tuple	       =				TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384'     ).led

								# change to intended input here
								__lowerCamelCase					:	Union[str, Any]	       =				_long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]]     )
								__lowerCamelCase					:	Dict	       =				_long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]]     )
								__lowerCamelCase					:	Optional[int]	       =				prepare_led_inputs_dict(model.config						,	__a						,	__a     )
								__lowerCamelCase					:	str	       =				model(**__a     )[0]
								__lowerCamelCase					:	Optional[int]	       =				(1, 1024, 768)
								self.assertEqual(output.shape						,	__a     )
								# change to expected output here
								__lowerCamelCase					:	int	       =				tf.convert_to_tensor(
								    [[2.3_050, 2.8_279, 0.6_531], [-1.8_457, -0.1_455, -3.5_661], [-1.0_186, 0.4_586, -2.2_043]]						,	)
								tf.debugging.assert_near(output[:, :3, :3]						,	__a						,	atol=1E-3     )





					def     snake_case_				(    self     ):
								__lowerCamelCase					:	List[str]	       =				TFLEDForConditionalGeneration.from_pretrained('allenai/led-base-16384'     )

								# change to intended input here
								__lowerCamelCase					:	Union[str, Any]	       =				_long_tensor([512 * [0, 31414, 232, 328, 740, 1140, 12695, 69]]     )
								__lowerCamelCase					:	Dict	       =				_long_tensor([128 * [0, 31414, 232, 328, 740, 1140, 12695, 69]]     )
								__lowerCamelCase					:	Optional[Any]	       =				prepare_led_inputs_dict(model.config						,	__a						,	__a     )
								__lowerCamelCase					:	Dict	       =				model(**__a     )[0]
								__lowerCamelCase					:	List[Any]	       =				(1, 1024, model.config.vocab_size)
								self.assertEqual(output.shape						,	__a     )
								# change to expected output here
								__lowerCamelCase					:	Optional[Any]	       =				tf.convert_to_tensor(
								    [[33.6_507, 6.4_572, 16.8_089], [5.8_739, -2.4_238, 11.2_902], [-3.2_139, -4.3_149, 4.2_783]]						,	)
								tf.debugging.assert_near(output[:, :3, :3]						,	__a						,	atol=1E-3						,	rtol=1E-3     )



