

'''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 	lowerCAmelCase  :
       lowerCAmelCase_												=			BlenderbotSmallConfig
       lowerCAmelCase_												=			{}
       lowerCAmelCase_												=			"gelu"







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







            """simple docstring"""







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

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







       def       snake_case (				self      :			List[str]   ):







            """simple docstring"""







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

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

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







       def       snake_case (				self      :			Dict    ,   __lowercase      :			str    ,   __lowercase      :			Optional[int]   ):







            """simple docstring"""







            __lowercase      		=TFBlenderbotSmallModel(config=__lowercase   ).get_decoder()
            __lowercase      		=inputs_dict['input_ids']

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

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

            __lowercase		,  __lowercase      		=outputs.to_tuple()

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

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

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

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






def 					__UpperCamelCase				(						lowercase__    :	List[str],       lowercase__    :	Union[str, Any],       lowercase__    :	str,       lowercase__    :	Any=None,       lowercase__    :	Dict=None,       lowercase__    :	Optional[Any]=None,       lowercase__    :	Tuple=None,       lowercase__    :	Any=None,       ):






     '''simple docstring'''





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


@require_tf
class 	lowerCAmelCase  (   A ,      A ,      unittest.TestCase ):
       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       snake_case (				self      :			Optional[int]   ):







            """simple docstring"""







            __lowercase      		=TFBlenderbotSmallModelTester(self   )
            __lowercase      		=ConfigTester(self    ,   config_class=__lowercase   )







       def       snake_case (				self      :			Optional[Any]   ):







            """simple docstring"""







            self.config_tester.run_common_tests()







       def       snake_case (				self      :			Optional[Any]   ):







            """simple docstring"""







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






@require_tokenizers
@require_tf
class 	lowerCAmelCase  (   unittest.TestCase ):
       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       snake_case (				self      :			Dict   ):







            """simple docstring"""







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







       @cached_property
       def       snake_case (				self      :			Any   ):







            """simple docstring"""







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







       @slow
       def       snake_case (				self      :			Dict   ):







            """simple docstring"""







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





'''simple docstring'''

def 					__UpperCamelCase				(						lowercase__    :	int			):






     '''simple docstring'''





     if upper_limit < 0:
          raise ValueError('Limit for the Catalan sequence must be ≥ 0'			)

     __lowercase      		=[0] * (upper_limit + 1)

     # Base case: C(0) = C(1) = 1
     __lowercase      		=1
     if upper_limit > 0:
          __lowercase      		=1

     # Recurrence relation: C(i) = sum(C(j).C(i-j-1)), from j = 0 to i
     for i in range(2,       upper_limit + 1			):
          for j in range(lowercase__			):
               catalan_list[i] += catalan_list[j] * catalan_list[i - j - 1]

     return catalan_list


if __name__ == "__main__":
       print('''\n********* Catalan Numbers Using Dynamic Programming ************\n''')
       print('''\n*** Enter -1 at any time to quit ***''')
       print('''\nEnter the upper limit (≥ 0) for the Catalan number sequence: ''', end='''''')
       try:
              while True:
                     UpperCAmelCase					 =	int(input().strip())
                     if N < 0:
                            print('''\n********* Goodbye!! ************''')
                            break
                     else:
                            print(F'''The Catalan numbers from 0 through {N} are:''')
                            print(catalan_numbers(N))
                            print('''Try another upper limit for the sequence: ''', end='''''')
       except (NameError, ValueError):
              print('''\n********* Invalid input, goodbye! ************\n''')

       import doctest

       doctest.testmod()


