






"""simple docstring"""






from ...configuration_utils import PretrainedConfig
from ...utils import logging


UpperCAmelCase_   : Union[str, Any]   			= logging.get_logger(__name__)

UpperCAmelCase_   : Tuple   			= {
    """facebook/s2t-small-librispeech-asr""": (
        """https://huggingface.co/facebook/s2t-small-librispeech-asr/resolve/main/config.json"""
    ),
    # See all Speech2Text models at https://huggingface.co/models?filter=speech_to_text
}




class 							lowerCAmelCase__				(			UpperCAmelCase__ ):






      '''simple docstring'''

      __UpperCamelCase	 =  "speech_to_text"
      __UpperCamelCase	 =  ["past_key_values"]
      __UpperCamelCase	 =  {"num_attention_heads": "encoder_attention_heads", "hidden_size": "d_model"}
      def __init__(						self     :  Any						,	lowercase_     :  Optional[Any]=10000						,	lowercase_     :  Any=12						,	lowercase_     :  List[str]=2048						,	lowercase_     :  str=4						,	lowercase_     :  List[str]=6						,	lowercase_     :  Optional[int]=2048						,	lowercase_     :  Any=4						,	lowercase_     :  List[str]=0.0						,	lowercase_     :  Union[str, Any]=0.0						,	lowercase_     :  Optional[Any]=True						,	lowercase_     :  List[str]=True						,	lowercase_     :  str="relu"						,	lowercase_     :  List[str]=256						,	lowercase_     :  Any=0.1						,	lowercase_     :  str=0.0						,	lowercase_     :  Optional[int]=0.0						,	lowercase_     :  List[Any]=0.02						,	lowercase_     :  Tuple=2						,	lowercase_     :  List[Any]=True						,	lowercase_     :  Dict=1						,	lowercase_     :  Union[str, Any]=0						,	lowercase_     :  Union[str, Any]=2						,	lowercase_     :  List[str]=6000						,	lowercase_     :  List[Any]=1024						,	lowercase_     :  Optional[int]=2						,	lowercase_     :  Union[str, Any]=(5, 5)						,	lowercase_     :  Any=1024						,	lowercase_     :  int=80						,	lowercase_     :  str=1						,	**lowercase_     :  str						,	):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		vocab_size
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		d_model
          SCREAMING_SNAKE_CASE_      :  Any    						=		encoder_ffn_dim
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		encoder_layers
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		encoder_attention_heads
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		decoder_ffn_dim
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		decoder_layers
          SCREAMING_SNAKE_CASE_      :  str    						=		decoder_attention_heads
          SCREAMING_SNAKE_CASE_      :  Any    						=		dropout
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		attention_dropout
          SCREAMING_SNAKE_CASE_      :  Dict    						=		activation_dropout
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		activation_function
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		init_std
          SCREAMING_SNAKE_CASE_      :  Any    						=		encoder_layerdrop
          SCREAMING_SNAKE_CASE_      :  List[Any]    						=		decoder_layerdrop
          SCREAMING_SNAKE_CASE_      :  Any    						=		use_cache
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		encoder_layers
          SCREAMING_SNAKE_CASE_      :  Any    						=		scale_embedding  # scale factor will be sqrt(d_model) if True
          SCREAMING_SNAKE_CASE_      :  Any    						=		max_source_positions
          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		max_target_positions
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		num_conv_layers
          SCREAMING_SNAKE_CASE_      :  Union[str, Any]    						=		list(lowercase_)
          SCREAMING_SNAKE_CASE_      :  str    						=		conv_channels
          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		input_feat_per_channel
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		input_channels

          if len(self.conv_kernel_sizes) != self.num_conv_layers:
              raise ValueError(
                  '''Configuration for convolutional module is incorrect. '''
                  '''It is required that `len(config.conv_kernel_sizes)` == `config.num_conv_layers` '''
                  F'but is `len(config.conv_kernel_sizes) = {len(self.conv_kernel_sizes)}`, '
                  F'`config.num_conv_layers = {self.num_conv_layers}`.')

          super().__init__(
              pad_token_id=lowercase_						,	bos_token_id=lowercase_						,	eos_token_id=lowercase_						,	is_encoder_decoder=lowercase_						,	decoder_start_token_id=lowercase_						,	**lowercase_						,	)










"""simple docstring"""






import copy
import tempfile
import unittest

from huggingface_hub import HfFolder, delete_repo
from parameterized import parameterized
from requests.exceptions import HTTPError

from transformers import AutoConfig, GenerationConfig
from transformers.testing_utils import TOKEN, USER, is_staging_test




class 							lowerCAmelCase__				(			unittest.TestCase ):






      '''simple docstring'''

      @parameterized.expand([(None,), ('''foo.json''',)])
      def _SCREAMING_SNAKE_CASE (						self     :  Dict						,	lowercase_     :  Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  List[str]    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	bad_words_ids=[[1, 2, 3], [4, 5]]						,	)
          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(lowercase_						,	config_name=lowercase_)
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig.from_pretrained(lowercase_						,	config_name=lowercase_)

          # Checks parameters that were specified
          self.assertEqual(loaded_config.do_sample						,	lowercase_)
          self.assertEqual(loaded_config.temperature						,	0.7)
          self.assertEqual(loaded_config.length_penalty						,	1.0)
          self.assertEqual(loaded_config.bad_words_ids						,	[[1, 2, 3], [4, 5]])

          # Checks parameters that were not specified (defaults)
          self.assertEqual(loaded_config.top_k						,	50)
          self.assertEqual(loaded_config.max_length						,	20)
          self.assertEqual(loaded_config.max_time						,	lowercase_)
      def _SCREAMING_SNAKE_CASE (						self     :  Optional[Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		AutoConfig.from_pretrained('''gpt2''')
          SCREAMING_SNAKE_CASE_      :  int    						=		GenerationConfig.from_model_config(lowercase_)
          SCREAMING_SNAKE_CASE_      :  int    						=		GenerationConfig()

          # The generation config has loaded a few non-default parameters from the model config
          self.assertNotEqual(lowercase_						,	lowercase_)

          # One of those parameters is eos_token_id -- check if it matches
          self.assertNotEqual(generation_config_from_model.eos_token_id						,	default_generation_config.eos_token_id)
          self.assertEqual(generation_config_from_model.eos_token_id						,	model_config.eos_token_id)
      def _SCREAMING_SNAKE_CASE (						self     :  Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  str    						=		GenerationConfig()
          SCREAMING_SNAKE_CASE_      :  Any    						=		{
              '''max_new_tokens''': 1024,
              '''foo''': '''bar''',
          }
          SCREAMING_SNAKE_CASE_      :  str    						=		copy.deepcopy(lowercase_)
          SCREAMING_SNAKE_CASE_      :  Tuple    						=		generation_config.update(**lowercase_)

          # update_kwargs was not modified (no side effects)
          self.assertEqual(lowercase_						,	lowercase_)

          # update_kwargs was used to update the config on valid attributes
          self.assertEqual(generation_config.max_new_tokens						,	1024)

          # `.update()` returns a dictionary of unused kwargs
          self.assertEqual(lowercase_						,	{'''foo''': '''bar'''})
      def _SCREAMING_SNAKE_CASE (						self     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		GenerationConfig()
          SCREAMING_SNAKE_CASE_      :  List[str]    						=		'''bar'''

          with tempfile.TemporaryDirectory('''test-generation-config''') as tmp_dir:
              generation_config.save_pretrained(lowercase_)

              SCREAMING_SNAKE_CASE_      :  List[Any]    						=		GenerationConfig.from_pretrained(lowercase_)
          # update_kwargs was used to update the config on valid attributes
          self.assertEqual(new_config.foo						,	'''bar''')

          SCREAMING_SNAKE_CASE_      :  Optional[Any]    						=		GenerationConfig.from_model_config(lowercase_)
          assert not hasattr(lowercase_						,	'''foo''')  # no new kwargs should be initialized if from config



      def _SCREAMING_SNAKE_CASE (						self     :  Tuple):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig()
          self.assertEqual(default_config.temperature						,	1.0)
          self.assertEqual(default_config.do_sample						,	lowercase_)
          self.assertEqual(default_config.num_beams						,	1)

          SCREAMING_SNAKE_CASE_      :  Dict    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	bad_words_ids=[[1, 2, 3], [4, 5]]						,	)
          self.assertEqual(config.temperature						,	0.7)
          self.assertEqual(config.do_sample						,	lowercase_)
          self.assertEqual(config.num_beams						,	1)

          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(lowercase_)
              SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig.from_pretrained(lowercase_						,	temperature=1.0)

          self.assertEqual(loaded_config.temperature						,	1.0)
          self.assertEqual(loaded_config.do_sample						,	lowercase_)
          self.assertEqual(loaded_config.num_beams						,	1)  # default value




@is_staging_test
class 							lowerCAmelCase__				(			unittest.TestCase ):






      '''simple docstring'''

      @classmethod
      def _SCREAMING_SNAKE_CASE (						cls     :  Any):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  str    						=		TOKEN
          HfFolder.save_token(lowercase_)
      @classmethod
      def _SCREAMING_SNAKE_CASE (						cls     :  List[str]):




          '''simple docstring'''


          try:
              delete_repo(token=cls._token						,	repo_id='''test-generation-config''')
          except HTTPError:
              pass

          try:
              delete_repo(token=cls._token						,	repo_id='''valid_org/test-generation-config-org''')
          except HTTPError:
              pass
      def _SCREAMING_SNAKE_CASE (						self     :  Dict):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Tuple    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	)
          config.push_to_hub('''test-generation-config'''						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  int    						=		GenerationConfig.from_pretrained(F'{USER}/test-generation-config')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))

        # Reset repo
          delete_repo(token=self._token						,	repo_id='''test-generation-config''')

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(
                  lowercase_						,	repo_id='''test-generation-config'''						,	push_to_hub=lowercase_						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  Optional[int]    						=		GenerationConfig.from_pretrained(F'{USER}/test-generation-config')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))



      def _SCREAMING_SNAKE_CASE (						self     :  Union[str, Any]):




          '''simple docstring'''


          SCREAMING_SNAKE_CASE_      :  Dict    						=		GenerationConfig(
              do_sample=lowercase_						,	temperature=0.7						,	length_penalty=1.0						,	)
          config.push_to_hub('''valid_org/test-generation-config-org'''						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  Any    						=		GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))

        # Reset repo
          delete_repo(token=self._token						,	repo_id='''valid_org/test-generation-config-org''')

          # Push to hub via save_pretrained
          with tempfile.TemporaryDirectory() as tmp_dir:
              config.save_pretrained(
                  lowercase_						,	repo_id='''valid_org/test-generation-config-org'''						,	push_to_hub=lowercase_						,	use_auth_token=self._token)

          SCREAMING_SNAKE_CASE_      :  Any    						=		GenerationConfig.from_pretrained('''valid_org/test-generation-config-org''')
          for k, v in config.to_dict().items():
              if k != "transformers_version":
                  self.assertEqual(lowercase_						,	getattr(lowercase_						,	lowercase_))


