






'''simple docstring'''





# HF Trainer benchmarking tool
#
# This tool can be used to run and compare multiple dimensions of the HF Trainers args.
#
# It then prints a report once in github format with all the information that needs to be shared
# with others and second time in a console-friendly format, so it's easier to use for tuning things up.
#
# The main idea is:
#
#     ./trainer-benchmark.py --base-cmd '<cmd args that don't change>' \
#     --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1' \
#     --target-metric-key train_samples_per_second
#
# The variations can be any command line argument that you want to compare and not just dtype as in
# the example.
#
# --variations allows you to compare variations in multiple dimensions.
#
# as the first dimention has 2 options and the second 3 in our example, this will run the trainer 6
# times adding one of:
#
#    1. --tf32 0 --fp16 0
#    2. --tf32 0 --fp16 1
#    3. --tf32 0 --bf16 1
#    4. --tf32 1 --fp16 0
#    5. --tf32 1 --fp16 1
#    6. --tf32 1 --bf16 1
#
# and print the results. This is just a cartesian product - and more than 2 dimensions can be used.
#
# If you want to rely on defaults, this:
#    --variations '--tf32 0|--tf32 1' '--fp16 0|--fp16 1|--bf16 1'
# is identical to this:
#    --variations '--tf32 0|--tf32 1' '|--fp16|--bf16'
#
# the leading empty variation in the 2nd dimension is a valid variation.
#
# So here we get the following 6 variations:
#
#    1. --tf32 0
#    2. --tf32 0 --fp16
#    3. --tf32 0 --bf16
#    4. --tf32 1
#    5. --tf32 1 --fp16
#    6. --tf32 1 --bf16
#
# In this particular case we don't know what the default tf32 setting is as it's normally
# pytorch-version dependent). That's why it's best to do an explicit setting of each variation:
#    `--tf32 0|--tf32 1`
#
# Here is a full example of a train:
#
# CUDA_VISIBLE_DEVICES=0 python ./scripts/benchmark/trainer-benchmark.py \
# --base-cmd \
# ' examples/pytorch/translation/run_translation.py --model_name_or_path t5-small \
# --output_dir output_dir --do_train --label_smoothing 0.1 --logging_strategy no \
# --save_strategy no --per_device_train_batch_size 32 --max_source_length 512 \
# --max_target_length 512 --num_train_epochs 1 --overwrite_output_dir \
# --source_lang en --target_lang ro --dataset_name wmt16 --dataset_config "ro-en" \
# --source_prefix "translate English to Romanian: " --warmup_steps 50 \
# --max_train_samples 20000 --dataloader_num_workers 2 ' \
# --target-metric-key train_samples_per_second --repeat-times 1 --variations \
# '|--fp16|--bf16' '--tf32 0|--tf32 1' --report-metric-keys train_loss \
# --repeat-times 1 --base-variation '--tf32 0'
#
# and here is a possible output:
#
#
# | Variation       |     Train |   Diff |   Train |
# |                 |   samples |      % |    loss |
# |                 |       per |        |         |
# |                 |    second |        |         |
# |:----------------|----------:|-------:|--------:|
# | --tf32 0        |    285.11 |      0 |    2.51 |
# | --tf32 1        |    342.09 |     20 |    2.51 |
# | --fp16 --tf32 0 |    423.49 |     49 |    2.51 |
# | --fp16 --tf32 1 |    423.13 |     48 |    2.51 |
# | --bf16 --tf32 0 |    416.80 |     46 |    2.52 |
# | --bf16 --tf32 1 |    415.87 |     46 |    2.52 |
#
#
# So you can quickly compare the different outcomes.
#
# Typically running each experiment once is enough, but if the environment is unstable you can
# re-run each multiple times, e.g., 3 using --repeat-times 3 and it will report the averaged results.
#
# By default it'll use the lowest result as the base line to use as 100% and then compare the rest to
# it as can be seen from the table above, but you can also specify which combination is the one to use as
# the baseline, e.g., to change to another entry use: --base-variation '--tf32 1 --fp16 0'
#
# --target-metric-key is there to tell the program which metrics to compare - the different metric keys are
# inside output_dir/all_results.json. e.g., to measure eval performance instead of train use:
#    --target-metric-key eval_samples_per_second
# but of course you will need to adjust the --base-cmd value in the example to perform evaluation as
# well (as currently it doesn't)
#

import argparse
import datetime
import io
import itertools
import json
import math
import os
import platform
import re
import shlex
import subprocess
import sys
from pathlib import Path
from statistics import fmean

import pandas as pd
import torch
from tqdm import tqdm

import transformers


__A							:							Optional[Any]  							=		float("""nan""")
class 				lowercase       :


    '''simple docstring'''

    def __init__(					self     :     Any				,     __lowerCamelCase     :     Union[str, Any]     )							->							Optional[int]:

     '''simple docstring'''




     lowerCamelCase__  =     sys.stdout
     lowerCamelCase__  =     open(__lowerCamelCase				,     "a"     )

    def __getattr__(					self     :     Optional[Any]				,     __lowerCamelCase     :     str     )							->							Any:

     '''simple docstring'''




     return getattr(self.stdout				,     __lowerCamelCase     )




    def    a__				(					self     :     List[str]				,     __lowerCamelCase     :     Optional[int]     )							->							str:

     '''simple docstring'''




     self.stdout.write(__lowerCamelCase     )
     # strip tqdm codes
     self.file.write(re.sub(r"^.*\r"				,     ""				,     __lowerCamelCase				,     0				,     re.M     )     )






def    lowerCamelCase_     (    lowercase__=80				,     lowercase__=False):
 lowerCamelCase__  =     []

 # deal with critical env vars
 lowerCamelCase__  =     ["CUDA_VISIBLE_DEVICES"]
 for key in env_keys:
  lowerCamelCase__  =     os.environ.get(lowercase__				,     lowercase__)
  if val is not None:
   cmd.append(F'''{key}={val}''')

    # python executable (not always needed if the script is executable)
 lowerCamelCase__  =     sys.executable if full_python_path else sys.executable.split("/")[-1]
 cmd.append(lowercase__)

 # now the normal args
 cmd += list(map(shlex.quote				,     sys.argv))

 # split up into up to MAX_WIDTH lines with shell multi-line escapes
 lowerCamelCase__  =     []
 lowerCamelCase__  =     ""
 while len(lowercase__) > 0:
  current_line += F'''{cmd.pop(0)} '''
  if len(lowercase__) == 0 or len(lowercase__) + len(cmd[0]) + 1 > max_width - 1:
   lines.append(lowercase__)
   lowerCamelCase__  =     ""
 return "\\\n".join(lowercase__)






def    lowerCamelCase_     (    lowercase__				,     lowercase__):
 # unwrap multi-line input
 lowerCamelCase__  =     re.sub(r"[\\\n]+"				,     " "				,     args.base_cmd)

 # remove --output_dir if any and set our own
 lowerCamelCase__  =     re.sub("--output_dir\s+[^\s]+"				,     ""				,     args.base_cmd)
 args.base_cmd += F''' --output_dir {output_dir}'''

 # ensure we have --overwrite_output_dir
 lowerCamelCase__  =     re.sub("--overwrite_output_dir\s+"				,     ""				,     args.base_cmd)
 args.base_cmd += " --overwrite_output_dir"

 return [sys.executable] + shlex.split(args.base_cmd)






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__):
 # Enable to debug everything but the run itself, to do it fast and see the progress.
 # This is useful for debugging the output formatting quickly - we can remove it later once
 # everybody is happy with the output
 if 0:
  import random
  from time import sleep

  sleep(0)
  return dict(
      {k: random.uniform(0				,     100) for k in metric_keys}				,     **{target_metric_key: random.choice([nan, 10.31, 100.2, 55.6_666, 222.22_222_222])}				,     )

 lowerCamelCase__  =     subprocess.run(lowercase__				,     capture_output=lowercase__				,     text=lowercase__)

 if verbose:
  print("STDOUT"				,     result.stdout)
  print("STDERR"				,     result.stderr)

 # save the streams
 lowerCamelCase__  =     variation.replace(" "				,     "-")
 with open(Path(lowercase__) / F'''log.{prefix}.stdout.txt'''				,     "w") as f:
  f.write(result.stdout)
 with open(Path(lowercase__) / F'''log.{prefix}.stderr.txt'''				,     "w") as f:
  f.write(result.stderr)

 if result.returncode != 0:
  if verbose:
   print("failed")
  return {target_metric_key: nan}

 with io.open(F'''{output_dir}/all_results.json'''				,     "r"				,     encoding="utf-8") as f:
  lowerCamelCase__  =     json.load(lowercase__)

 # filter out just the keys we want
 return {k: v for k, v in metrics.items() if k in metric_keys}






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     ):
 lowerCamelCase__  =     []
 lowerCamelCase__  =     []
 lowerCamelCase__  =     F'''{id}: {variation:<{longest_variation_len}}'''
 lowerCamelCase__  =     F'''{preamble}: '''
 lowerCamelCase__  =     set(report_metric_keys + [target_metric_key])
 for i in tqdm(range(lowercase__)				,     desc=lowercase__				,     leave=lowercase__):
  lowerCamelCase__  =     process_run_single(
      lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__)
  lowerCamelCase__  =     single_run_metrics[target_metric_key]
  if not math.isnan(lowercase__):
   metrics.append(lowercase__)
   results.append(lowercase__)
   outcome += "✓"
  else:
   outcome += "✘"
 lowerCamelCase__  =     F'''\33[2K\r{outcome}'''
 if len(lowercase__) > 0:
  lowerCamelCase__  =     {k: fmean([x[k] for x in metrics]) for k in metrics[0].keys()}
  lowerCamelCase__  =     round(mean_metrics[target_metric_key]				,     2)
  lowerCamelCase__  =     F'''{outcome} {mean_target}'''
  if len(lowercase__) > 1:
   results_str += F''' {tuple(round(lowercase__				,     2) for x in results)}'''
  print(lowercase__)
  lowerCamelCase__  =     variation
  return mean_metrics
 else:
  print(lowercase__)
  return {variation_key: variation, target_metric_key: nan}






def    lowerCamelCase_     (    ):
 lowerCamelCase__  =     torch.cuda.get_device_properties(torch.device("cuda"))
 return F'''
Datetime    : {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}

Software:
transformers: {transformers.__version__}
torch       : {torch.__version__}
cuda        : {torch.version.cuda}
python      : {platform.python_version()}

Hardware:
{torch.cuda.device_count()} GPUs      : {properties.name}, {properties.total_memory/2**30:0.2f}GB
'''






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__):
 lowerCamelCase__  =     pd.DataFrame(lowercase__)
 lowerCamelCase__  =     "variation"
 lowerCamelCase__  =     "diff_%"

 lowerCamelCase__  =     nan
 if base_variation is not None and len(df[df[variation_key] == base_variation]):
  # this may still return nan
  lowerCamelCase__  =     df.loc[df[variation_key] == base_variation][target_metric_key].item()
 if math.isnan(lowercase__):
  # as a fallback, use the minimal value as the sentinel
  lowerCamelCase__  =     df.loc[df[target_metric_key] != nan][target_metric_key].min()

 # create diff column if possible
 if not math.isnan(lowercase__):
  lowerCamelCase__  =     df.apply(
      lambda lowercase__: round(100 * (r[target_metric_key] - sentinel_value) / sentinel_value)
      if not math.isnan(r[target_metric_key])
      else 0				,     axis="columns"				,     )

 # re-order columns
 lowerCamelCase__  =     [variation_key, target_metric_key, diff_key, *report_metric_keys]
 lowerCamelCase__  =     df.reindex(lowercase__				,     axis="columns")  # reorder cols

 # capitalize
 lowerCamelCase__  =     df.rename(str.capitalize				,     axis="columns")

 # make the cols as narrow as possible
 lowerCamelCase__  =     df.rename(lambda lowercase__: c.replace("_"				,     "<br>")				,     axis="columns")
 lowerCamelCase__  =     df.rename(lambda lowercase__: c.replace("_"				,     "\n")				,     axis="columns")

 lowerCamelCase__  =     ["", "Copy between the cut-here-lines and paste as is to github or a forum"]
 report += ["----------8<-----------------8<--------"]
 report += ["*** Results:", df_github.to_markdown(index=lowercase__				,     floatfmt=".2f")]
 report += ["```"]
 report += ["*** Setup:", get_versions()]
 report += ["*** The benchmark command line was:", get_original_command()]
 report += ["```"]
 report += ["----------8<-----------------8<--------"]
 report += ["*** Results (console):", df_console.to_markdown(index=lowercase__				,     floatfmt=".2f")]

 print("\n\n".join(lowercase__))






def    lowerCamelCase_     (    ):
 lowerCamelCase__  =     argparse.ArgumentParser()
 parser.add_argument(
     "--base-cmd"				,     default=lowercase__				,     type=lowercase__				,     required=lowercase__				,     help="Base cmd"				,     )
 parser.add_argument(
     "--variations"				,     default=lowercase__				,     type=lowercase__				,     nargs="+"				,     required=lowercase__				,     help="Multi-dimensional variations, example: '|--fp16|--bf16' '|--tf32'"				,     )
 parser.add_argument(
     "--base-variation"				,     default=lowercase__				,     type=lowercase__				,     help="Baseline variation to compare to. if None the minimal target value will be used to compare against"				,     )
 parser.add_argument(
     "--target-metric-key"				,     default=lowercase__				,     type=lowercase__				,     required=lowercase__				,     help="Target metric key in output_dir/all_results.json, e.g., train_samples_per_second"				,     )
 parser.add_argument(
     "--report-metric-keys"				,     default=""				,     type=lowercase__				,     help="Report metric keys - other metric keys from output_dir/all_results.json to report, e.g., train_loss. Use a single argument e.g., 'train_loss train_samples"				,     )
 parser.add_argument(
     "--repeat-times"				,     default=1				,     type=lowercase__				,     help="How many times to re-run each variation - an average will be reported"				,     )
 parser.add_argument(
     "--output_dir"				,     default="output_benchmark"				,     type=lowercase__				,     help="The output directory where all the benchmark reports will go to and additionally this directory will be used to override --output_dir in the script that is being benchmarked"				,     )
 parser.add_argument(
     "--verbose"				,     default=lowercase__				,     action="store_true"				,     help="Whether to show the outputs of each run or just the benchmark progress"				,     )
 lowerCamelCase__  =     parser.parse_args()

 lowerCamelCase__  =     args.output_dir
 Path(lowercase__).mkdir(exist_ok=lowercase__)
 lowerCamelCase__  =     get_base_command(lowercase__				,     lowercase__)

 # split each dimension into its --foo variations
 lowerCamelCase__  =     [list(map(str.strip				,     re.split(r"\|"				,     lowercase__))) for x in args.variations]
 # build a cartesian product of dimensions and convert those back into cmd-line arg strings,
 # while stripping white space for inputs that were empty
 lowerCamelCase__  =     list(map(str.strip				,     map(" ".join				,     itertools.product(*lowercase__))))
 lowerCamelCase__  =     max(len(lowercase__) for x in variations)

 # split wanted keys
 lowerCamelCase__  =     args.report_metric_keys.split()

 # capture prints into a log file for convenience
 lowerCamelCase__  =     F'''benchmark-report-{datetime.datetime.now().strftime("%Y-%m-%d-%H-%M-%S")}.txt'''
 print(F'''\nNote: each run\'s output is also logged under {output_dir}/log.*.std*.txt''')
 print(F'''and this script\'s output is also piped into {report_fn}''')

 lowerCamelCase__  =     Tee(lowercase__)

 print(F'''\n*** Running {len(lowercase__)} benchmarks:''')
 print(F'''Base command: {" ".join(lowercase__)}''')

 lowerCamelCase__  =     "variation"
 lowerCamelCase__  =     []
 for id, variation in enumerate(tqdm(lowercase__				,     desc="Total completion: "				,     leave=lowercase__)):
  lowerCamelCase__  =     base_cmd + variation.split()
  results.append(
      process_run(
          id + 1				,     lowercase__				,     lowercase__				,     lowercase__				,     lowercase__				,     args.target_metric_key				,     lowercase__				,     args.repeat_times				,     lowercase__				,     args.verbose				,     ))

 process_results(lowercase__				,     args.target_metric_key				,     lowercase__				,     args.base_variation				,     lowercase__)


if __name__ == "__main__":
 main()









'''simple docstring'''





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 				lowercase       :


    '''simple docstring'''

    lowerCAmelCase__      				=							BlenderbotSmallConfig
    lowerCAmelCase__      				=							{}
    lowerCAmelCase__      				=							"gelu"

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

     '''simple docstring'''




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

     lowerCamelCase__  =     hidden_dropout_prob
     lowerCamelCase__  =     attention_probs_dropout_prob
     lowerCamelCase__  =     max_position_embeddings
     lowerCamelCase__  =     eos_token_id
     lowerCamelCase__  =     pad_token_id
     lowerCamelCase__  =     bos_token_id

    def    a__				(					self     :     str     )							->							List[str]:

     '''simple docstring'''




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

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

     lowerCamelCase__  =     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__  =     prepare_blenderbot_small_inputs_dict(__lowerCamelCase				,     __lowerCamelCase				,     __lowerCamelCase     )
     return config, inputs_dict




    def    a__				(					self     :     int				,     __lowerCamelCase     :     Optional[int]				,     __lowerCamelCase     :     Optional[Any]     )							->							Tuple:

     '''simple docstring'''




     lowerCamelCase__  =     TFBlenderbotSmallModel(config=__lowerCamelCase     ).get_decoder()
     lowerCamelCase__  =     inputs_dict["input_ids"]

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

     # first forward pass
     lowerCamelCase__  =     model(__lowerCamelCase				,     attention_mask=__lowerCamelCase				,     head_mask=__lowerCamelCase				,     use_cache=__lowerCamelCase     )

     lowerCamelCase__  ,	lowerCamelCase__  =     outputs.to_tuple()

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

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

     lowerCamelCase__  =     model(__lowerCamelCase				,     attention_mask=__lowerCamelCase     )[0]
     lowerCamelCase__  =     model(__lowerCamelCase				,     attention_mask=__lowerCamelCase				,     past_key_values=__lowerCamelCase     )[0]

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

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

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






def    lowerCamelCase_     (    lowercase__				,     lowercase__				,     lowercase__				,     lowercase__=None				,     lowercase__=None				,     lowercase__=None				,     lowercase__=None				,     lowercase__=None				,     ):
 if attention_mask is None:
  lowerCamelCase__  =     tf.cast(tf.math.not_equal(lowercase__				,     config.pad_token_id)				,     tf.inta)
 if decoder_attention_mask is None:
  lowerCamelCase__  =     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__  =     tf.ones((config.encoder_layers, config.encoder_attention_heads))
 if decoder_head_mask is None:
  lowerCamelCase__  =     tf.ones((config.decoder_layers, config.decoder_attention_heads))
 if cross_attn_head_mask is None:
  lowerCamelCase__  =     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 				lowercase       (							_lowerCamelCase ,       _lowerCamelCase ,       unittest.TestCase      ):


    '''simple docstring'''

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

    def    a__				(					self     :     List[Any]     )							->							Optional[Any]:

     '''simple docstring'''




     lowerCamelCase__  =     TFBlenderbotSmallModelTester(self     )
     lowerCamelCase__  =     ConfigTester(self				,     config_class=__lowerCamelCase     )

    def    a__				(					self     :     Any     )							->							Tuple:

     '''simple docstring'''




     self.config_tester.run_common_tests()




    def    a__				(					self     :     List[Any]     )							->							List[str]:

     '''simple docstring'''




     lowerCamelCase__  =     self.model_tester.prepare_config_and_inputs_for_common()
     self.model_tester.check_decoder_model_past_large_inputs(*__lowerCamelCase     )
@require_tokenizers
@require_tf
class 				lowercase       (							unittest.TestCase      ):


    '''simple docstring'''

    lowerCAmelCase__      				=							[
        "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?"
    ]
    lowerCAmelCase__      				=							"facebook/blenderbot_small-90M"

    @cached_property
    def    a__				(					self     :     Optional[Any]     )							->							Tuple:

     '''simple docstring'''




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

    @cached_property
    def    a__				(					self     :     int     )							->							int:

     '''simple docstring'''




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




    @slow
    def    a__				(					self     :     Any     )							->							Union[str, Any]:

     '''simple docstring'''




     lowerCamelCase__  =     self.tokenizer(self.src_text				,     return_tensors="tf"     )
     lowerCamelCase__  =     self.model.generate(
         model_inputs.input_ids				,     attention_mask=model_inputs.attention_mask				,     num_beams=2				,     use_cache=__lowerCamelCase				,     )
     lowerCamelCase__  =     self.tokenizer.batch_decode(generated_ids.numpy()				,     skip_special_tokens=__lowerCamelCase     )[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.",
     )

