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 UpperCAmelCase		(   unittest.TestCase    ):


				'''simple docstring'''






				@parameterized.expand([(None,), ('foo.json',)]   )
				def     lowerCAmelCase_  (		self						,      lowercase   ):



						"""simple docstring"""





						A_						:							Optional[int]      = 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   )
								A_						:							Optional[int]      = 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						,      5_0   )
						self.assertEqual(loaded_config.max_length						,      2_0   )
						self.assertEqual(loaded_config.max_time						,      lowercase   )
				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Optional[int]      = AutoConfig.from_pretrained('gpt2'   )
						A_						:							Dict      = GenerationConfig.from_model_config(lowercase   )
						A_						:							Any      = 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     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Dict      = GenerationConfig()
						A_						:							List[Any]      = {
						    'max_new_tokens': 1_0_2_4,
						    'foo': 'bar',
						}
						A_						:							List[str]      = copy.deepcopy(lowercase   )
						A_						:							Any      = 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						,      1_0_2_4   )

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



						"""simple docstring"""





						A_						:							Tuple      = GenerationConfig()
						A_						:							Optional[Any]      = 'bar'

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

								A_						:							str      = GenerationConfig.from_pretrained(lowercase   )
						# update_kwargs was used to update the config on valid attributes
						self.assertEqual(new_config.foo						,      'bar'   )

						A_						:							Tuple      = GenerationConfig.from_model_config(lowercase   )
						assert not hasattr(lowercase						,      'foo'   )  # no new kwargs should be initialized if from config







				def     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							str      = GenerationConfig()
						self.assertEqual(default_config.temperature						,      1.0   )
						self.assertEqual(default_config.do_sample						,      lowercase   )
						self.assertEqual(default_config.num_beams						,      1   )

						A_						:							Tuple      = 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   )
								A_						:							str      = 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 UpperCAmelCase		(   unittest.TestCase    ):


				'''simple docstring'''






				@classmethod
				def     lowerCAmelCase_  (		cls   ):



						"""simple docstring"""





						A_						:							Tuple      = TOKEN
						HfFolder.save_token(lowercase   )
				@classmethod
				def     lowerCAmelCase_  (		cls   ):



						"""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     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Optional[int]      = GenerationConfig(
						    do_sample=lowercase						,      temperature=0.7						,      length_penalty=1.0						,      )
						config.push_to_hub('test-generation-config'						,      use_auth_token=self._token   )

						A_						:							Optional[Any]      = 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   )

						A_						:							Any      = 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     lowerCAmelCase_  (		self   ):



						"""simple docstring"""





						A_						:							Optional[int]      = 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   )

						A_						:							Optional[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   )

						A_						:							Tuple      = 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   )   )







from ...configuration_utils import PretrainedConfig
from ...utils import logging
from ...utils.backbone_utils import BackboneConfigMixin, get_aligned_output_features_output_indices


_UpperCAmelCase          =						logging.get_logger(__name__)

_UpperCAmelCase          =						{
    """google/bit-50""": """https://huggingface.co/google/bit-50/resolve/main/config.json""",
}





class UpperCAmelCase		(   __A   ,			__A    ):


				'''simple docstring'''






				lowerCamelCase_        =   '''bit'''
				lowerCamelCase_        =   ['''preactivation''', '''bottleneck''']
				lowerCamelCase_        =   ['''SAME''', '''VALID''']
				def __init__(		self						,      lowercase=3						,      lowercase=6_4						,      lowercase=[2_5_6, 5_1_2, 1_0_2_4, 2_0_4_8]						,      lowercase=[3, 4, 6, 3]						,      lowercase="preactivation"						,      lowercase="relu"						,      lowercase=None						,      lowercase=3_2						,      lowercase=0.0						,      lowercase=False						,      lowercase=3_2						,      lowercase=1						,      lowercase=None						,      lowercase=None						,      **lowercase						,      ):



						"""simple docstring"""





						super().__init__(**lowercase   )
						if layer_type not in self.layer_types:
								raise ValueError(F'''layer_type={layer_type} is not one of {','.join(self.layer_types   )}'''   )
						if global_padding is not None:
								if global_padding.upper() in self.supported_padding:
										A_						:							Tuple      = global_padding.upper()
								else:
										raise ValueError(F'''Padding strategy {global_padding} not supported'''   )
						A_						:							Any      = num_channels
						A_						:							Any      = embedding_size
						A_						:							List[Any]      = hidden_sizes
						A_						:							int      = depths
						A_						:							Union[str, Any]      = layer_type
						A_						:							List[Any]      = hidden_act
						A_						:							Tuple      = global_padding
						A_						:							List[str]      = num_groups
						A_						:							int      = drop_path_rate
						A_						:							str      = embedding_dynamic_padding
						A_						:							Dict      = output_stride
						A_						:							Any      = width_factor

						A_						:							int      = ['stem'] + [F'''stage{idx}''' for idx in range(1						,      len(lowercase   ) + 1   )]
						A_  ,     A_						:							List[Any]      = get_aligned_output_features_output_indices(
						    out_features=lowercase						,      out_indices=lowercase						,      stage_names=self.stage_names   )






