




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







   @parameterized.expand([(None,), ('foo.json',)]   )
   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   )					->     Dict:
     __a								=       GenerationConfig(
         do_sample=UpperCamelCase   ,				temperature=0.7   ,				length_penalty=1.0   ,				bad_words_ids=[[1, 2, 3], [4, 5]]   ,				)
     with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(UpperCamelCase   ,				config_name=UpperCamelCase   )
       __a								=       GenerationConfig.from_pretrained(UpperCamelCase   ,				config_name=UpperCamelCase   )

     # Checks parameters that were specified
     self.assertEqual(loaded_config.do_sample   ,				UpperCamelCase   )
     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   ,				UpperCamelCase   )







   def 		UpperCamelCase__      (						self   )					->     str:
     __a								=       AutoConfig.from_pretrained('gpt2'   )
     __a								=       GenerationConfig.from_model_config(UpperCamelCase   )
     __a								=       GenerationConfig()

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

     # 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 		UpperCamelCase__      (						self   )					->     Any:
     __a								=       GenerationConfig()
     __a								=       {
         'max_new_tokens': 1024,
         'foo': 'bar',
     }
     __a								=       copy.deepcopy(UpperCamelCase   )
     __a								=       generation_config.update(**UpperCamelCase   )

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

     # 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(UpperCamelCase   ,				{'foo': 'bar'}   )







   def 		UpperCamelCase__      (						self   )					->     int:
     __a								=       GenerationConfig()
     __a								=       'bar'

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

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

     __a								=       GenerationConfig.from_model_config(UpperCamelCase   )
     assert not hasattr(UpperCamelCase   ,				'foo'   )  # no new kwargs should be initialized if from config







   def 		UpperCamelCase__      (						self   )					->     Optional[Any]:
     __a								=       GenerationConfig()
     self.assertEqual(default_config.temperature   ,				1.0   )
     self.assertEqual(default_config.do_sample   ,				UpperCamelCase   )
     self.assertEqual(default_config.num_beams   ,				1   )

     __a								=       GenerationConfig(
         do_sample=UpperCamelCase   ,				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   ,				UpperCamelCase   )
     self.assertEqual(config.num_beams   ,				1   )

     with tempfile.TemporaryDirectory() as tmp_dir:
       config.save_pretrained(UpperCamelCase   )
       __a								=       GenerationConfig.from_pretrained(UpperCamelCase   ,				temperature=1.0   )

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





@is_staging_test
class  __lowercase    (	unittest.TestCase			):







   @classmethod
   def 		UpperCamelCase__      (						cls   )					->     Optional[Any]:
     __a								=       TOKEN
     HfFolder.save_token(UpperCamelCase   )







   @classmethod
   def 		UpperCamelCase__      (						cls   )					->     List[str]:
     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 		UpperCamelCase__      (						self   )					->     List[str]:
     __a								=       GenerationConfig(
         do_sample=UpperCamelCase   ,				temperature=0.7   ,				length_penalty=1.0   ,				)
     config.push_to_hub('test-generation-config'   ,				use_auth_token=self._token   )

     __a								=       GenerationConfig.from_pretrained(f"{USER}/test-generation-config"   )
     for k, v in config.to_dict().items():
       if k != "transformers_version":
         self.assertEqual(UpperCamelCase   ,				getattr(UpperCamelCase   ,				UpperCamelCase   )   )

        # 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(
           UpperCamelCase   ,				repo_id='test-generation-config'   ,				push_to_hub=UpperCamelCase   ,				use_auth_token=self._token   )

     __a								=       GenerationConfig.from_pretrained(f"{USER}/test-generation-config"   )
     for k, v in config.to_dict().items():
       if k != "transformers_version":
         self.assertEqual(UpperCamelCase   ,				getattr(UpperCamelCase   ,				UpperCamelCase   )   )







   def 		UpperCamelCase__      (						self   )					->     Dict:
     __a								=       GenerationConfig(
         do_sample=UpperCamelCase   ,				temperature=0.7   ,				length_penalty=1.0   ,				)
     config.push_to_hub('valid_org/test-generation-config-org'   ,				use_auth_token=self._token   )

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

        # 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(
           UpperCamelCase   ,				repo_id='valid_org/test-generation-config-org'   ,				push_to_hub=UpperCamelCase   ,				use_auth_token=self._token   )

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









'''simple docstring'''


from collections import OrderedDict
from typing import TYPE_CHECKING, Any, Mapping, Optional

from ...configuration_utils import PretrainedConfig
from ...onnx import OnnxConfig
from ...utils import logging


if TYPE_CHECKING:
  from ... import FeatureExtractionMixin, TensorType

UpperCAmelCase_					=   logging.get_logger(__name__)

UpperCAmelCase_					=   {
    "openai/imagegpt-small": "",
    "openai/imagegpt-medium": "",
    "openai/imagegpt-large": "",
}





class  __lowercase    (	__magic_name__			):
   _a    						=   """imagegpt"""
   _a    						=   ["""past_key_values"""]
   _a    						=   {
       """hidden_size""": """n_embd""",
       """max_position_embeddings""": """n_positions""",
       """num_attention_heads""": """n_head""",
       """num_hidden_layers""": """n_layer""",
   }







   def __init__(						self   ,				UpperCamelCase=512 + 1   ,				UpperCamelCase=32 * 32   ,				UpperCamelCase=512   ,				UpperCamelCase=24   ,				UpperCamelCase=8   ,				UpperCamelCase=None   ,				UpperCamelCase="quick_gelu"   ,				UpperCamelCase=0.1   ,				UpperCamelCase=0.1   ,				UpperCamelCase=0.1   ,				UpperCamelCase=1e-5   ,				UpperCamelCase=0.02   ,				UpperCamelCase=True   ,				UpperCamelCase=True   ,				UpperCamelCase=False   ,				UpperCamelCase=False   ,				UpperCamelCase=False   ,				**UpperCamelCase   ,				)					->     int:
     __a								=       vocab_size
     __a								=       n_positions
     __a								=       n_embd
     __a								=       n_layer
     __a								=       n_head
     __a								=       n_inner
     __a								=       activation_function
     __a								=       resid_pdrop
     __a								=       embd_pdrop
     __a								=       attn_pdrop
     __a								=       layer_norm_epsilon
     __a								=       initializer_range
     __a								=       scale_attn_weights
     __a								=       use_cache
     __a								=       scale_attn_by_inverse_layer_idx
     __a								=       reorder_and_upcast_attn
     __a								=       tie_word_embeddings

     super().__init__(tie_word_embeddings=UpperCamelCase   ,				**UpperCamelCase   )





class  __lowercase    (	__magic_name__			):







   @property
   def 		UpperCamelCase__      (						self   )					->     Mapping[str, Mapping[int, str]]:
     return OrderedDict(
         [
             ('input_ids', {0: 'batch', 1: 'sequence'}),
         ]   )







   def 		UpperCamelCase__      (						self   ,				UpperCamelCase   ,				UpperCamelCase = 1   ,				UpperCamelCase = -1   ,				UpperCamelCase = False   ,				UpperCamelCase = None   ,				UpperCamelCase = 3   ,				UpperCamelCase = 32   ,				UpperCamelCase = 32   ,				)					->     Mapping[str, Any]:
     __a								=       self._generate_dummy_images(UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   ,				UpperCamelCase   )
     __a								=       dict(preprocessor(images=UpperCamelCase   ,				return_tensors=UpperCamelCase   )   )

     return inputs



