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'''):
   __lowerCamelCase      :			Any							       =		True
   from torch.cuda.amp import autocast

__lowerCamelCase      :			Tuple							       =		logging.getLogger(__name__)



def      __SCREAMING_SNAKE_CASE  ( __UpperCamelCase   :	Optional[int]=None			,					__UpperCamelCase   :	str=None     )							-> Dict:







  """simple docstring"""





  return field(default_factory=lambda: default			,					metadata=__UpperCamelCase     )







@dataclass
class __snake_case    :
   lowerCAmelCase_														=							field(
       metadata={"help": "Path to pretrained model or model identifier from huggingface.co/models"}		)
   lowerCAmelCase_														=							field(
       default=lowerCamelCase_       ,		metadata={"help": "Where do you want to store the pretrained models downloaded from huggingface.co"}       ,		)
   lowerCAmelCase_														=							field(
       default=lowerCamelCase_       ,		metadata={"help": "Whether to freeze the feature extractor layers of the model."}		)
   lowerCAmelCase_														=							field(
       default=0.1       ,		metadata={"help": "The dropout ratio for the attention probabilities."}		)
   lowerCAmelCase_														=							field(
       default=0.1       ,		metadata={"help": "The dropout ratio for activations inside the fully connected layer."}		)
   lowerCAmelCase_														=							field(
       default=0.1       ,		metadata={
           "help": "The dropout probabilitiy for all fully connected layers in the embeddings, encoder, and pooler."
       }       ,		)
   lowerCAmelCase_														=							field(
       default=0.1       ,		metadata={"help": "The dropout probabilitiy for all 1D convolutional layers in feature extractor."}       ,		)
   lowerCAmelCase_														=							field(
       default=0.05       ,		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``."
           )
       }       ,		)
   lowerCAmelCase_														=							field(default=0.0       ,		metadata={"help": "The LayerDrop probability."}		)







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







@dataclass
class __snake_case    :
   lowerCAmelCase_														=							42
   lowerCAmelCase_														=							True
   lowerCAmelCase_														=							None
   lowerCAmelCase_														=							None
   lowerCAmelCase_														=							None
   lowerCAmelCase_														=							None




   def __call__(   self      :    str	,     _lowercase      :    List[Dict[str, Union[List[int], torch.Tensor]]]				):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__      							=				[{"""input_values""": feature["""input_values"""]} for feature in features]
     SCREAMING_SNAKE_CASE__      							=				[{"""input_ids""": feature["""labels"""]} for feature in features]

     SCREAMING_SNAKE_CASE__      							=				self.processor.pad(
         _lowercase	,     padding=self.padding	,     max_length=self.max_length	,     pad_to_multiple_of=self.pad_to_multiple_of	,     return_tensors="""pt"""	,     )
     SCREAMING_SNAKE_CASE__      							=				self.processor.pad(
         labels=_lowercase	,     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
     SCREAMING_SNAKE_CASE__      							=				labels_batch["""input_ids"""].masked_fill(labels_batch.attention_mask.ne(1				)	,     -1_00				)

     SCREAMING_SNAKE_CASE__      							=				labels

     return batch







class __snake_case    (						lowerCamelCase_		):




   def      __a						(   self      :    Tuple	,     _lowercase      :    nn.Module	,     _lowercase      :    Dict[str, Union[torch.Tensor, Any]]				):



     """simple docstring"""






     model.train()
     SCREAMING_SNAKE_CASE__      							=				self._prepare_inputs(_lowercase				)

     if self.use_amp:
       with autocast():
         SCREAMING_SNAKE_CASE__      							=				self.compute_loss(_lowercase	,     _lowercase				)
     else:
       SCREAMING_SNAKE_CASE__      							=				self.compute_loss(_lowercase	,     _lowercase				)

     if self.args.n_gpu > 1:
       if model.module.config.ctc_loss_reduction == "mean":
         SCREAMING_SNAKE_CASE__      							=				loss.mean()
       elif model.module.config.ctc_loss_reduction == "sum":
         SCREAMING_SNAKE_CASE__      							=				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:
       SCREAMING_SNAKE_CASE__      							=				loss / self.args.gradient_accumulation_steps

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

     return loss.detach()



def      __SCREAMING_SNAKE_CASE  ( )							-> str:







  """simple docstring"""





  SCREAMING_SNAKE_CASE__      							=				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.
    SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__      							=				parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]     )     )
  else:
    SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__      							=				parser.parse_args_into_dataclasses()

  # Detecting last checkpoint.
  SCREAMING_SNAKE_CASE__      							=				None
  if os.path.isdir(training_args.output_dir     ) and training_args.do_train and not training_args.overwrite_output_dir:
    SCREAMING_SNAKE_CASE__      							=				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"""			,					__UpperCamelCase     )

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

  # Get the datasets:
  SCREAMING_SNAKE_CASE__      							=				datasets.load_dataset(
      """common_voice"""			,					data_args.dataset_config_name			,					split=data_args.train_split_name     )
  SCREAMING_SNAKE_CASE__      							=				datasets.load_dataset("""common_voice"""			,					data_args.dataset_config_name			,					split="""test"""     )

  # Create and save tokenizer
  SCREAMING_SNAKE_CASE__      							=				f"""[{''.join(data_args.chars_to_ignore     )}]"""

  def remove_special_characters(__UpperCamelCase   :	Optional[Any]     ):
    SCREAMING_SNAKE_CASE__      							=				re.sub(__UpperCamelCase			,					""""""			,					batch["""sentence"""]     ).lower() + """ """
    return batch

  SCREAMING_SNAKE_CASE__      							=				train_dataset.map(__UpperCamelCase			,					remove_columns=["""sentence"""]     )
  SCREAMING_SNAKE_CASE__      							=				eval_dataset.map(__UpperCamelCase			,					remove_columns=["""sentence"""]     )

  def extract_all_chars(__UpperCamelCase   :	Dict     ):
    SCREAMING_SNAKE_CASE__      							=				""" """.join(batch["""text"""]     )
    SCREAMING_SNAKE_CASE__      							=				list(set(__UpperCamelCase     )     )
    return {"vocab": [vocab], "all_text": [all_text]}

  SCREAMING_SNAKE_CASE__      							=				train_dataset.map(
      __UpperCamelCase			,					batched=__UpperCamelCase			,					batch_size=-1			,					keep_in_memory=__UpperCamelCase			,					remove_columns=train_dataset.column_names			,					)
  SCREAMING_SNAKE_CASE__      							=				train_dataset.map(
      __UpperCamelCase			,					batched=__UpperCamelCase			,					batch_size=-1			,					keep_in_memory=__UpperCamelCase			,					remove_columns=eval_dataset.column_names			,					)

  SCREAMING_SNAKE_CASE__      							=				list(set(vocab_train["""vocab"""][0]     ) | set(vocab_test["""vocab"""][0]     )     )
  SCREAMING_SNAKE_CASE__      							=				{v: k for k, v in enumerate(__UpperCamelCase     )}
  SCREAMING_SNAKE_CASE__      							=				vocab_dict[""" """]
  del vocab_dict[" "]
  SCREAMING_SNAKE_CASE__      							=				len(__UpperCamelCase     )
  SCREAMING_SNAKE_CASE__      							=				len(__UpperCamelCase     )

  with open("""vocab.json"""			,					"""w"""     ) as vocab_file:
    json.dump(__UpperCamelCase			,					__UpperCamelCase     )

  # Load pretrained model and tokenizer
  #
  # Distributed training:
  # The .from_pretrained methods guarantee that only one local process can concurrently
  # download model & vocab.
  SCREAMING_SNAKE_CASE__      							=				WavaVecaCTCTokenizer(
      """vocab.json"""			,					unk_token="""[UNK]"""			,					pad_token="""[PAD]"""			,					word_delimiter_token="""|"""			,					)
  SCREAMING_SNAKE_CASE__      							=				WavaVecaFeatureExtractor(
      feature_size=1			,					sampling_rate=1_60_00			,					padding_value=0.0			,					do_normalize=__UpperCamelCase			,					return_attention_mask=__UpperCamelCase     )
  SCREAMING_SNAKE_CASE__      							=				WavaVecaProcessor(feature_extractor=__UpperCamelCase			,					tokenizer=__UpperCamelCase     )
  SCREAMING_SNAKE_CASE__      							=				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:
    SCREAMING_SNAKE_CASE__      							=				min(len(__UpperCamelCase     )			,					data_args.max_train_samples     )
    SCREAMING_SNAKE_CASE__      							=				train_dataset.select(range(__UpperCamelCase     )     )

  if data_args.max_val_samples is not None:
    SCREAMING_SNAKE_CASE__      							=				eval_dataset.select(range(data_args.max_val_samples     )     )

  SCREAMING_SNAKE_CASE__      							=				torchaudio.transforms.Resample(4_80_00			,					1_60_00     )

  # Preprocessing the datasets.
  # We need to read the aduio files as arrays and tokenize the targets.
  def speech_file_to_array_fn(__UpperCamelCase   :	Optional[Any]     ):
    SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__      							=				torchaudio.load(batch["""path"""]     )
    SCREAMING_SNAKE_CASE__      							=				resampler(__UpperCamelCase     ).squeeze().numpy()
    SCREAMING_SNAKE_CASE__      							=				1_60_00
    SCREAMING_SNAKE_CASE__      							=				batch["""text"""]
    return batch

  SCREAMING_SNAKE_CASE__      							=				train_dataset.map(
      __UpperCamelCase			,					remove_columns=train_dataset.column_names			,					num_proc=data_args.preprocessing_num_workers			,					)
  SCREAMING_SNAKE_CASE__      							=				eval_dataset.map(
      __UpperCamelCase			,					remove_columns=eval_dataset.column_names			,					num_proc=data_args.preprocessing_num_workers			,					)

  def prepare_dataset(__UpperCamelCase   :	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}."""

    SCREAMING_SNAKE_CASE__      							=				processor(
        audio=batch["""speech"""]			,					text=batch["""target_text"""]			,					sampling_rate=batch["""sampling_rate"""][0]     )
    batch.update(__UpperCamelCase     )
    return batch

  SCREAMING_SNAKE_CASE__      							=				train_dataset.map(
      __UpperCamelCase			,					remove_columns=train_dataset.column_names			,					batch_size=training_args.per_device_train_batch_size			,					batched=__UpperCamelCase			,					num_proc=data_args.preprocessing_num_workers			,					)
  SCREAMING_SNAKE_CASE__      							=				eval_dataset.map(
      __UpperCamelCase			,					remove_columns=eval_dataset.column_names			,					batch_size=training_args.per_device_train_batch_size			,					batched=__UpperCamelCase			,					num_proc=data_args.preprocessing_num_workers			,					)

  # Metric
  SCREAMING_SNAKE_CASE__      							=				datasets.load_metric("""wer"""     )

  def compute_metrics(__UpperCamelCase   :	Any     ):
    SCREAMING_SNAKE_CASE__      							=				pred.predictions
    SCREAMING_SNAKE_CASE__      							=				np.argmax(__UpperCamelCase			,					axis=-1     )

    SCREAMING_SNAKE_CASE__      							=				processor.tokenizer.pad_token_id

    SCREAMING_SNAKE_CASE__      							=				processor.batch_decode(__UpperCamelCase     )
    # we do not want to group tokens when computing the metrics
    SCREAMING_SNAKE_CASE__      							=				processor.batch_decode(pred.label_ids			,					group_tokens=__UpperCamelCase     )

    SCREAMING_SNAKE_CASE__      							=				wer_metric.compute(predictions=__UpperCamelCase			,					references=__UpperCamelCase     )

    return {"wer": wer}

  if model_args.freeze_feature_extractor:
    model.freeze_feature_extractor()

  # Data collator
  SCREAMING_SNAKE_CASE__      							=				DataCollatorCTCWithPadding(processor=__UpperCamelCase			,					padding=__UpperCamelCase     )

  # Initialize our Trainer
  SCREAMING_SNAKE_CASE__      							=				CTCTrainer(
      model=__UpperCamelCase			,					data_collator=__UpperCamelCase			,					args=__UpperCamelCase			,					compute_metrics=__UpperCamelCase			,					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:
      SCREAMING_SNAKE_CASE__      							=				last_checkpoint
    elif os.path.isdir(model_args.model_name_or_path     ):
      SCREAMING_SNAKE_CASE__      							=				model_args.model_name_or_path
    else:
      SCREAMING_SNAKE_CASE__      							=				None

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

    SCREAMING_SNAKE_CASE__      							=				trainer.train(resume_from_checkpoint=__UpperCamelCase     )
    trainer.save_model()

    SCREAMING_SNAKE_CASE__      							=				train_result.metrics
    SCREAMING_SNAKE_CASE__      							=				(
        data_args.max_train_samples if data_args.max_train_samples is not None else len(__UpperCamelCase     )
    )
    SCREAMING_SNAKE_CASE__      							=				min(__UpperCamelCase			,					len(__UpperCamelCase     )     )

    trainer.log_metrics("""train"""			,					__UpperCamelCase     )
    trainer.save_metrics("""train"""			,					__UpperCamelCase     )
    trainer.save_state()

  # Evaluation
  SCREAMING_SNAKE_CASE__      							=				{}
  if training_args.do_eval:
    logger.info("""*** Evaluate ***"""     )
    SCREAMING_SNAKE_CASE__      							=				trainer.evaluate()
    SCREAMING_SNAKE_CASE__      							=				data_args.max_val_samples if data_args.max_val_samples is not None else len(__UpperCamelCase     )
    SCREAMING_SNAKE_CASE__      							=				min(__UpperCamelCase			,					len(__UpperCamelCase     )     )

    trainer.log_metrics("""eval"""			,					__UpperCamelCase     )
    trainer.save_metrics("""eval"""			,					__UpperCamelCase     )

  return results


if __name__ == "__main__":
   main()

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 __snake_case    :
   lowerCAmelCase_														=							LEDConfig
   lowerCAmelCase_														=							{}
   lowerCAmelCase_														=							"gelu"




   def __init__(   self      :    Any	,     _lowercase      :    Tuple	,     _lowercase      :    str=13	,     _lowercase      :    Optional[int]=7	,     _lowercase      :    Optional[Any]=True	,     _lowercase      :    Dict=False	,     _lowercase      :    Union[str, Any]=99	,     _lowercase      :    Any=32	,     _lowercase      :    int=2	,     _lowercase      :    List[str]=4	,     _lowercase      :    Optional[int]=37	,     _lowercase      :    Union[str, Any]=0.1	,     _lowercase      :    str=0.1	,     _lowercase      :    Union[str, Any]=20	,     _lowercase      :    List[str]=2	,     _lowercase      :    Optional[int]=1	,     _lowercase      :    Dict=0	,     _lowercase      :    List[str]=4	,     ):



     """simple docstring"""






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

     SCREAMING_SNAKE_CASE__      							=				hidden_dropout_prob
     SCREAMING_SNAKE_CASE__      							=				attention_probs_dropout_prob
     SCREAMING_SNAKE_CASE__      							=				max_position_embeddings
     SCREAMING_SNAKE_CASE__      							=				eos_token_id
     SCREAMING_SNAKE_CASE__      							=				pad_token_id
     SCREAMING_SNAKE_CASE__      							=				bos_token_id
     SCREAMING_SNAKE_CASE__      							=				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
     SCREAMING_SNAKE_CASE__      							=				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
     SCREAMING_SNAKE_CASE__      							=				(
         self.seq_length + (self.attention_window - self.seq_length % self.attention_window) % self.attention_window
     )




   def      __a						(   self      :    Optional[int]				):



     """simple docstring"""






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

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

     SCREAMING_SNAKE_CASE__      							=				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	,     )
     SCREAMING_SNAKE_CASE__      							=				prepare_led_inputs_dict(_lowercase	,     _lowercase	,     _lowercase				)
     SCREAMING_SNAKE_CASE__      							=				tf.concat(
         [tf.zeros_like(_lowercase				)[:, :-1], tf.ones_like(_lowercase				)[:, -1:]]	,     axis=-1	,     )
     SCREAMING_SNAKE_CASE__      							=				global_attention_mask
     return config, inputs_dict




   def      __a						(   self      :    Tuple	,     _lowercase      :    int	,     _lowercase      :    int				):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__      							=				TFLEDModel(config=_lowercase				).get_decoder()
     SCREAMING_SNAKE_CASE__      							=				inputs_dict["""input_ids"""]

     SCREAMING_SNAKE_CASE__      							=				input_ids[:1, :]
     SCREAMING_SNAKE_CASE__      							=				inputs_dict["""attention_mask"""][:1, :]
     SCREAMING_SNAKE_CASE__      							=				1

     # first forward pass
     SCREAMING_SNAKE_CASE__      							=				model(_lowercase	,     attention_mask=_lowercase	,     use_cache=_lowercase				)

     SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__      							=				outputs.to_tuple()

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

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

     SCREAMING_SNAKE_CASE__      							=				model(_lowercase	,     attention_mask=_lowercase				)[0]
     SCREAMING_SNAKE_CASE__      							=				model(_lowercase	,     attention_mask=_lowercase	,     past_key_values=_lowercase				)[0]

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

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

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





def      __SCREAMING_SNAKE_CASE  ( __UpperCamelCase   :	Optional[Any]			,					__UpperCamelCase   :	Dict			,					__UpperCamelCase   :	int			,					__UpperCamelCase   :	List[str]=None			,					__UpperCamelCase   :	Union[str, Any]=None			,					__UpperCamelCase   :	Dict=None			,					__UpperCamelCase   :	Optional[Any]=None			,					)							-> int:







  """simple docstring"""





  if attention_mask is None:
    SCREAMING_SNAKE_CASE__      							=				tf.cast(tf.math.not_equal(__UpperCamelCase			,					config.pad_token_id     )			,					tf.inta     )
  if decoder_attention_mask is None:
    SCREAMING_SNAKE_CASE__      							=				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:
    SCREAMING_SNAKE_CASE__      							=				tf.ones((config.encoder_layers, config.encoder_attention_heads)     )
  if decoder_head_mask is None:
    SCREAMING_SNAKE_CASE__      							=				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 __snake_case    (						lowerCamelCase_       ,		lowerCamelCase_       ,		unittest.TestCase		):
   lowerCAmelCase_														=							(TFLEDForConditionalGeneration, TFLEDModel) if is_tf_available() else ()
   lowerCAmelCase_														=							(TFLEDForConditionalGeneration,) if is_tf_available() else ()
   lowerCAmelCase_														=							(
       {
           "conversational": TFLEDForConditionalGeneration,
           "feature-extraction": TFLEDModel,
           "summarization": TFLEDForConditionalGeneration,
           "text2text-generation": TFLEDForConditionalGeneration,
           "translation": TFLEDForConditionalGeneration,
       }
       if is_tf_available()
       else {}
   )
   lowerCAmelCase_														=							True
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False
   lowerCAmelCase_														=							False




   def      __a						(   self      :    Dict				):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__      							=				TFLEDModelTester(self				)
     SCREAMING_SNAKE_CASE__      							=				ConfigTester(self	,     config_class=_lowercase				)




   def      __a						(   self      :    str				):



     """simple docstring"""






     self.config_tester.run_common_tests()




   def      __a						(   self      :    Optional[Any]				):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__      							=				self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_decoder_model_past_large_inputs(*_lowercase				)




   def      __a						(   self      :    Tuple				):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__							,					SCREAMING_SNAKE_CASE__      							=				self.model_tester.prepare_config_and_inputs_for_common()
     SCREAMING_SNAKE_CASE__      							=				tf.zeros_like(inputs_dict["""attention_mask"""]				)
     SCREAMING_SNAKE_CASE__      							=				2
     SCREAMING_SNAKE_CASE__      							=				tf.where(
         tf.range(self.model_tester.seq_length				)[None, :] < num_global_attn_indices	,     1	,     inputs_dict["""global_attention_mask"""]	,     )

     SCREAMING_SNAKE_CASE__      							=				True
     SCREAMING_SNAKE_CASE__      							=				self.model_tester.seq_length
     SCREAMING_SNAKE_CASE__      							=				self.model_tester.encoder_seq_length

     def check_decoder_attentions_output(_lowercase      :    List[str]				):
       SCREAMING_SNAKE_CASE__      							=				outputs.decoder_attentions
       self.assertEqual(len(_lowercase				)	,     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(_lowercase      :    List[str]				):
       SCREAMING_SNAKE_CASE__      							=				[t.numpy() for t in outputs.encoder_attentions]
       SCREAMING_SNAKE_CASE__      							=				[t.numpy() for t in outputs.encoder_global_attentions]
       self.assertEqual(len(_lowercase				)	,     self.model_tester.num_hidden_layers				)
       self.assertEqual(len(_lowercase				)	,     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:
       SCREAMING_SNAKE_CASE__      							=				True
       SCREAMING_SNAKE_CASE__      							=				False
       SCREAMING_SNAKE_CASE__      							=				False
       SCREAMING_SNAKE_CASE__      							=				model_class(_lowercase				)
       SCREAMING_SNAKE_CASE__      							=				model(self._prepare_for_class(_lowercase	,     _lowercase				)				)
       SCREAMING_SNAKE_CASE__      							=				len(_lowercase				)
       self.assertEqual(config.output_hidden_states	,     _lowercase				)
       check_encoder_attentions_output(_lowercase				)

       if self.is_encoder_decoder:
         SCREAMING_SNAKE_CASE__      							=				model_class(_lowercase				)
         SCREAMING_SNAKE_CASE__      							=				model(self._prepare_for_class(_lowercase	,     _lowercase				)				)
         self.assertEqual(config.output_hidden_states	,     _lowercase				)
         check_decoder_attentions_output(_lowercase				)

       # Check that output attentions can also be changed via the config
       del inputs_dict["output_attentions"]
       SCREAMING_SNAKE_CASE__      							=				True
       SCREAMING_SNAKE_CASE__      							=				model_class(_lowercase				)
       SCREAMING_SNAKE_CASE__      							=				model(self._prepare_for_class(_lowercase	,     _lowercase				)				)
       self.assertEqual(config.output_hidden_states	,     _lowercase				)
       check_encoder_attentions_output(_lowercase				)

       # Check attention is always last and order is fine
       SCREAMING_SNAKE_CASE__      							=				True
       SCREAMING_SNAKE_CASE__      							=				True
       SCREAMING_SNAKE_CASE__      							=				model_class(_lowercase				)
       SCREAMING_SNAKE_CASE__      							=				model(self._prepare_for_class(_lowercase	,     _lowercase				)				)

       self.assertEqual(out_len + (2 if self.is_encoder_decoder else 1)	,     len(_lowercase				)				)
       self.assertEqual(model.config.output_hidden_states	,     _lowercase				)
       check_encoder_attentions_output(_lowercase				)




   @unittest.skip("""LED keeps using potentially symbolic tensors in conditionals and breaks tracing."""				)
   def      __a						(   self      :    List[Any]				):



     """simple docstring"""






     pass




   def      __a						(   self      :    List[str]				):



     """simple docstring"""






     pass





def      __SCREAMING_SNAKE_CASE  ( __UpperCamelCase   :	List[str]     )							-> Dict:







  """simple docstring"""





  return tf.constant(__UpperCamelCase			,					dtype=tf.intaa     )


__lowerCamelCase      :			List[str]							       =		1e-4







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




   def      __a						(   self      :    Tuple				):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__      							=				TFLEDForConditionalGeneration.from_pretrained("""allenai/led-base-16384"""				).led

     # change to intended input here
     SCREAMING_SNAKE_CASE__      							=				_long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]]				)
     SCREAMING_SNAKE_CASE__      							=				_long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]]				)
     SCREAMING_SNAKE_CASE__      							=				prepare_led_inputs_dict(model.config	,     _lowercase	,     _lowercase				)
     SCREAMING_SNAKE_CASE__      							=				model(**_lowercase				)[0]
     SCREAMING_SNAKE_CASE__      							=				(1, 10_24, 7_68)
     self.assertEqual(output.shape	,     _lowercase				)
     # change to expected output here
     SCREAMING_SNAKE_CASE__      							=				tf.convert_to_tensor(
         [[2.30_50, 2.82_79, 0.65_31], [-1.84_57, -0.14_55, -3.56_61], [-1.01_86, 0.45_86, -2.20_43]]	,     )
     tf.debugging.assert_near(output[:, :3, :3]	,     _lowercase	,     atol=1E-3				)




   def      __a						(   self      :    Optional[Any]				):



     """simple docstring"""






     SCREAMING_SNAKE_CASE__      							=				TFLEDForConditionalGeneration.from_pretrained("""allenai/led-base-16384"""				)

     # change to intended input here
     SCREAMING_SNAKE_CASE__      							=				_long_tensor([5_12 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]]				)
     SCREAMING_SNAKE_CASE__      							=				_long_tensor([1_28 * [0, 3_14_14, 2_32, 3_28, 7_40, 11_40, 1_26_95, 69]]				)
     SCREAMING_SNAKE_CASE__      							=				prepare_led_inputs_dict(model.config	,     _lowercase	,     _lowercase				)
     SCREAMING_SNAKE_CASE__      							=				model(**_lowercase				)[0]
     SCREAMING_SNAKE_CASE__      							=				(1, 10_24, model.config.vocab_size)
     self.assertEqual(output.shape	,     _lowercase				)
     # change to expected output here
     SCREAMING_SNAKE_CASE__      							=				tf.convert_to_tensor(
         [[33.65_07, 6.45_72, 16.80_89], [5.87_39, -2.42_38, 11.29_02], [-3.21_39, -4.31_49, 4.27_83]]	,     )
     tf.debugging.assert_near(output[:, :3, :3]	,     _lowercase	,     atol=1E-3	,     rtol=1E-3				)
