





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      							=   True
       from torch.cuda.amp import autocast

_lowerCamelCase      							=   logging.getLogger(__name__)




def  __UpperCAmelCase(   lowercase_=None			,     lowercase_=None   ):
       return field(default_factory=lambda: default			,     metadata=lowercase_   )







@dataclass
class       __A							:




      """simple docstring"""







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







@dataclass
class       __A							:




      """simple docstring"""







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







@dataclass
class       __A							:




      """simple docstring"""







      UpperCAmelCase__							=   42
      UpperCAmelCase__							=   True
      UpperCAmelCase__							=   None
      UpperCAmelCase__							=   None
      UpperCAmelCase__							=   None
      UpperCAmelCase__							=   None


      def __call__(		self   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		[{'''input_values''': feature['''input_values''']} for feature in features]
             _lowerCamelCase				:  Tuple						=		[{'''input_ids''': feature['''labels''']} for feature in features]

             _lowerCamelCase				:  List[str]						=		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				:  str						=		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				:  Union[str, Any]						=		labels_batch['''input_ids'''].masked_fill(labels_batch.attention_mask.ne(1)   ,				-100)

             _lowerCamelCase				:  List[Any]						=		labels

             return batch







class       __A							(   lowerCamelCase__	):




      """simple docstring"""







      def 					__snake_case      (		self   ,				a__   ,				a__):



             """simple docstring"""





             model.train()
             _lowerCamelCase				:  int						=		self._prepare_inputs(a__)

             if self.use_amp:
                    with autocast():
                           _lowerCamelCase				:  Optional[Any]						=		self.compute_loss(a__   ,				a__)
             else:
                    _lowerCamelCase				:  List[Any]						=		self.compute_loss(a__   ,				a__)

             if self.args.n_gpu > 1:
                    if model.module.config.ctc_loss_reduction == "mean":
                           _lowerCamelCase				:  Tuple						=		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				:  Tuple						=		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(   ):
       # 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				:  Optional[Any]						=		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				:  Optional[Any]						=		parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]   )   )
       else:
              _lowerCamelCase,	_lowerCamelCase,	_lowerCamelCase				:  Any						=		parser.parse_args_into_dataclasses()

       # Detecting last checkpoint.
       _lowerCamelCase				:  List[Any]						=		None
       if os.path.isdir(training_args.output_dir   ) and training_args.do_train and not training_args.overwrite_output_dir:
              _lowerCamelCase				:  Union[str, Any]						=		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'''			,     lowercase_   )

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

       # Get the datasets:
       _lowerCamelCase				:  Dict						=		datasets.load_dataset(
           '''common_voice'''			,     data_args.dataset_config_name			,     split=data_args.train_split_name   )
       _lowerCamelCase				:  Dict						=		datasets.load_dataset('''common_voice'''			,     data_args.dataset_config_name			,     split='''test'''   )

       # Create and save tokenizer
       _lowerCamelCase				:  Optional[int]						=		F"""[{''.join(data_args.chars_to_ignore   )}]"""

       def remove_special_characters(lowercase_   ):
              _lowerCamelCase				:  int						=		re.sub(lowercase_			,     ''''''			,     batch['''sentence''']   ).lower() + ''' '''
              return batch

       _lowerCamelCase				:  Optional[int]						=		train_dataset.map(lowercase_			,     remove_columns=['''sentence''']   )
       _lowerCamelCase				:  Optional[Any]						=		eval_dataset.map(lowercase_			,     remove_columns=['''sentence''']   )

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

       _lowerCamelCase				:  List[Any]						=		train_dataset.map(
           lowercase_			,     batched=lowercase_			,     batch_size=-1			,     keep_in_memory=lowercase_			,     remove_columns=train_dataset.column_names			,     )
       _lowerCamelCase				:  List[str]						=		train_dataset.map(
           lowercase_			,     batched=lowercase_			,     batch_size=-1			,     keep_in_memory=lowercase_			,     remove_columns=eval_dataset.column_names			,     )

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

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

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

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

       _lowerCamelCase				:  List[Any]						=		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(lowercase_   ):
              _lowerCamelCase,	_lowerCamelCase				:  List[str]						=		torchaudio.load(batch['''path''']   )
              _lowerCamelCase				:  List[Any]						=		resampler(lowercase_   ).squeeze().numpy()
              _lowerCamelCase				:  Optional[Any]						=		1_60_00
              _lowerCamelCase				:  Optional[Any]						=		batch['''text''']
              return batch

       _lowerCamelCase				:  Tuple						=		train_dataset.map(
           lowercase_			,     remove_columns=train_dataset.column_names			,     num_proc=data_args.preprocessing_num_workers			,     )
       _lowerCamelCase				:  Any						=		eval_dataset.map(
           lowercase_			,     remove_columns=eval_dataset.column_names			,     num_proc=data_args.preprocessing_num_workers			,     )

       def prepare_dataset(lowercase_   ):
              # 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				:  Union[str, Any]						=		processor(
                  audio=batch['''speech''']			,     text=batch['''target_text''']			,     sampling_rate=batch['''sampling_rate'''][0]   )
              batch.update(lowercase_   )
              return batch

       _lowerCamelCase				:  Dict						=		train_dataset.map(
           lowercase_			,     remove_columns=train_dataset.column_names			,     batch_size=training_args.per_device_train_batch_size			,     batched=lowercase_			,     num_proc=data_args.preprocessing_num_workers			,     )
       _lowerCamelCase				:  int						=		eval_dataset.map(
           lowercase_			,     remove_columns=eval_dataset.column_names			,     batch_size=training_args.per_device_train_batch_size			,     batched=lowercase_			,     num_proc=data_args.preprocessing_num_workers			,     )

       # Metric
       _lowerCamelCase				:  List[Any]						=		datasets.load_metric('''wer'''   )

       def compute_metrics(lowercase_   ):
              _lowerCamelCase				:  Tuple						=		pred.predictions
              _lowerCamelCase				:  str						=		np.argmax(lowercase_			,     axis=-1   )

              _lowerCamelCase				:  Tuple						=		processor.tokenizer.pad_token_id

              _lowerCamelCase				:  str						=		processor.batch_decode(lowercase_   )
              # we do not want to group tokens when computing the metrics
              _lowerCamelCase				:  int						=		processor.batch_decode(pred.label_ids			,     group_tokens=lowercase_   )

              _lowerCamelCase				:  List[Any]						=		wer_metric.compute(predictions=lowercase_			,     references=lowercase_   )

              return {"wer": wer}

       if model_args.freeze_feature_extractor:
              model.freeze_feature_extractor()

       # Data collator
       _lowerCamelCase				:  List[str]						=		DataCollatorCTCWithPadding(processor=lowercase_			,     padding=lowercase_   )

       # Initialize our Trainer
       _lowerCamelCase				:  str						=		CTCTrainer(
           model=lowercase_			,     data_collator=lowercase_			,     args=lowercase_			,     compute_metrics=lowercase_			,     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				:  List[str]						=		last_checkpoint
              elif os.path.isdir(model_args.model_name_or_path   ):
                     _lowerCamelCase				:  Optional[int]						=		model_args.model_name_or_path
              else:
                     _lowerCamelCase				:  Optional[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=lowercase_   )
              trainer.save_model()

              _lowerCamelCase				:  List[Any]						=		train_result.metrics
              _lowerCamelCase				:  Tuple						=		(
                  data_args.max_train_samples if data_args.max_train_samples is not None else len(lowercase_   )
              )
              _lowerCamelCase				:  List[Any]						=		min(lowercase_			,     len(lowercase_   )   )

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

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

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

       return results


if __name__ == "__main__":
       main()








from __future__ import annotations

import unittest

from transformers import BlenderbotSmallConfig, BlenderbotSmallTokenizer, is_tf_available
from transformers.testing_utils import 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, TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel







@require_tf
class       __A							:




      """simple docstring"""







      UpperCAmelCase__							=   BlenderbotSmallConfig
      UpperCAmelCase__							=   {}
      UpperCAmelCase__							=   """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   ,				):



             """simple docstring"""





             _lowerCamelCase				:  str						=		parent
             _lowerCamelCase				:  Any						=		batch_size
             _lowerCamelCase				:  str						=		seq_length
             _lowerCamelCase				:  Optional[int]						=		is_training
             _lowerCamelCase				:  int						=		use_labels
             _lowerCamelCase				:  List[str]						=		vocab_size
             _lowerCamelCase				:  List[Any]						=		hidden_size
             _lowerCamelCase				:  Tuple						=		num_hidden_layers
             _lowerCamelCase				:  List[Any]						=		num_attention_heads
             _lowerCamelCase				:  int						=		intermediate_size

             _lowerCamelCase				:  int						=		hidden_dropout_prob
             _lowerCamelCase				:  Tuple						=		attention_probs_dropout_prob
             _lowerCamelCase				:  Dict						=		max_position_embeddings
             _lowerCamelCase				:  str						=		eos_token_id
             _lowerCamelCase				:  Any						=		pad_token_id
             _lowerCamelCase				:  str						=		bos_token_id


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		ids_tensor([self.batch_size, self.seq_length - 1]   ,				self.vocab_size)
             _lowerCamelCase				:  Any						=		tf.expand_dims(tf.constant([self.eos_token_id] * self.batch_size)   ,				1)
             _lowerCamelCase				:  Optional[Any]						=		tf.concat([input_ids, eos_tensor]   ,				axis=1)

             _lowerCamelCase				:  List[str]						=		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   ,				**self.config_updates   ,				)
             _lowerCamelCase				:  Optional[int]						=		prepare_blenderbot_small_inputs_dict(a__   ,				a__   ,				a__)
             return config, inputs_dict



      def 					__snake_case      (		self   ,				a__   ,				a__):



             """simple docstring"""





             _lowerCamelCase				:  Optional[int]						=		TFBlenderbotSmallModel(config=a__).get_decoder()
             _lowerCamelCase				:  Dict						=		inputs_dict['''input_ids''']

             _lowerCamelCase				:  int						=		input_ids[:1, :]
             _lowerCamelCase				:  Union[str, Any]						=		inputs_dict['''attention_mask'''][:1, :]
             _lowerCamelCase				:  List[str]						=		inputs_dict['''head_mask''']
             _lowerCamelCase				:  Optional[int]						=		1

             # first forward pass
             _lowerCamelCase				:  Union[str, Any]						=		model(a__   ,				attention_mask=a__   ,				head_mask=a__   ,				use_cache=a__)

             _lowerCamelCase,	_lowerCamelCase				:  str						=		outputs.to_tuple()

             # create hypothetical next token and extent to next_input_ids
             _lowerCamelCase				:  Any						=		ids_tensor((self.batch_size, 3)   ,				config.vocab_size)
             _lowerCamelCase				:  Optional[Any]						=		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				:  Optional[Any]						=		tf.concat([attention_mask, next_attn_mask]   ,				axis=-1)

             _lowerCamelCase				:  List[str]						=		model(a__   ,				attention_mask=a__)[0]
             _lowerCamelCase				:  str						=		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				:  int						=		int(ids_tensor((1,)   ,				output_from_past.shape[-1]))
             _lowerCamelCase				:  Any						=		output_from_no_past[:, -3:, random_slice_idx]
             _lowerCamelCase				:  int						=		output_from_past[:, :, random_slice_idx]

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




def  __UpperCAmelCase(   lowercase_			,     lowercase_			,     lowercase_			,     lowercase_=None			,     lowercase_=None			,     lowercase_=None			,     lowercase_=None			,     lowercase_=None			,     ):
       if attention_mask is None:
              _lowerCamelCase				:  List[Any]						=		tf.cast(tf.math.not_equal(lowercase_			,     config.pad_token_id   )			,     tf.inta   )
       if decoder_attention_mask is None:
              _lowerCamelCase				:  Union[str, Any]						=		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				:  List[str]						=		tf.ones((config.encoder_layers, config.encoder_attention_heads)   )
       if decoder_head_mask is None:
              _lowerCamelCase				:  Optional[int]						=		tf.ones((config.decoder_layers, config.decoder_attention_heads)   )
       if cross_attn_head_mask is None:
              _lowerCamelCase				:  Union[str, Any]						=		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       __A							(   lowerCamelCase__			,lowerCamelCase__			,unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   (
          (TFBlenderbotSmallForConditionalGeneration, TFBlenderbotSmallModel) if is_tf_available() else ()
      )
      UpperCAmelCase__							=   (TFBlenderbotSmallForConditionalGeneration,) if is_tf_available() else ()
      UpperCAmelCase__							=   (
          {
              """conversational""": TFBlenderbotSmallForConditionalGeneration,
              """feature-extraction""": TFBlenderbotSmallModel,
              """summarization""": TFBlenderbotSmallForConditionalGeneration,
              """text2text-generation""": TFBlenderbotSmallForConditionalGeneration,
              """translation""": TFBlenderbotSmallForConditionalGeneration,
          }
          if is_tf_available()
          else {}
      )
      UpperCAmelCase__							=   True
      UpperCAmelCase__							=   False
      UpperCAmelCase__							=   False


      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[str]						=		TFBlenderbotSmallModelTester(self)
             _lowerCamelCase				:  Optional[int]						=		ConfigTester(self   ,				config_class=a__)


      def 					__snake_case      (		self):



             """simple docstring"""





             self.config_tester.run_common_tests()



      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Any						=		self.model_tester.prepare_config_and_inputs_for_common()
             self.model_tester.check_decoder_model_past_large_inputs(*a__)







@require_tokenizers
@require_tf
class       __A							(   unittest.TestCase	):




      """simple docstring"""







      UpperCAmelCase__							=   [
          """Social anxiety\nWow, I am never shy. Do you have anxiety?\nYes. I end up sweating and blushing and feel like """
          """  i'm going to throw up.\nand why is that?"""
      ]
      UpperCAmelCase__							=   """facebook/blenderbot_small-90M"""


      @cached_property
      def 					__snake_case      (		self):



             """simple docstring"""





             return BlenderbotSmallTokenizer.from_pretrained('''facebook/blenderbot-90M''')


      @cached_property
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  List[Any]						=		TFAutoModelForSeqaSeqLM.from_pretrained(self.model_name)
             return model



      @slow
      def 					__snake_case      (		self):



             """simple docstring"""





             _lowerCamelCase				:  Union[str, Any]						=		self.tokenizer(self.src_text   ,				return_tensors='''tf''')
             _lowerCamelCase				:  str						=		self.model.generate(
                 model_inputs.input_ids   ,				attention_mask=model_inputs.attention_mask   ,				num_beams=2   ,				use_cache=a__   ,				)
             _lowerCamelCase				:  Tuple						=		self.tokenizer.batch_decode(generated_ids.numpy()   ,				skip_special_tokens=a__)[0]
             assert generated_words in (
                 "i don't know. i just feel like i'm going to throw up. it's not fun.",
                 "i'm not sure. i just feel like i've been feeling like i have to be in a certain place",
                 "i'm not sure. i just feel like i've been in a bad situation.",
             )

