




'''simple docstring'''


import subprocess
import sys

from transformers import BertConfig, BertModel, BertTokenizer, pipeline
from transformers.testing_utils import TestCasePlus, require_torch





class  __lowercase    (	__magic_name__			):







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     Any:
     # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
     # `transformers` is loaded, and it's too late for inside pytest - so we are changing it
     # while running an external program

     # python one-liner segments

     # this must be loaded before socket.socket is monkey-patched
     __a								=       '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

     __a								=       '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

     __a								=       '\nimport socket\ndef offline_socket(*args, **kwargs): raise RuntimeError("Offline mode is enabled, we shouldn\'t access internet")\nsocket.socket = offline_socket\n        '

     # Force fetching the files so that we can use the cache
     __a								=       'hf-internal-testing/tiny-random-bert'
     BertConfig.from_pretrained(UpperCamelCase   )
     BertModel.from_pretrained(UpperCamelCase   )
     BertTokenizer.from_pretrained(UpperCamelCase   )
     pipeline(task='fill-mask'   ,				model=UpperCamelCase   )

     # baseline - just load from_pretrained with normal network
     __a								=       [sys.executable, '-c', '\n'.join([load, run, mock]   )]

     # should succeed
     __a								=       self.get_env()
     # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
     __a								=       '1'
     __a								=       subprocess.run(UpperCamelCase   ,				env=UpperCamelCase   ,				check=UpperCamelCase   ,				capture_output=UpperCamelCase   )
     self.assertEqual(result.returncode   ,				0   ,				result.stderr   )
     self.assertIn('success'   ,				result.stdout.decode()   )







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     Tuple:
     # python one-liner segments
     # this must be loaded before socket.socket is monkey-patched
     __a								=       '\nfrom transformers import BertConfig, BertModel, BertTokenizer, pipeline\n        '

     __a								=       '\nmname = "hf-internal-testing/tiny-random-bert"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nBertTokenizer.from_pretrained(mname)\npipe = pipeline(task="fill-mask", model=mname)\nprint("success")\n        '

     __a								=       '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Faking flaky internet")\nsocket.socket = offline_socket\n        '

     # Force fetching the files so that we can use the cache
     __a								=       'hf-internal-testing/tiny-random-bert'
     BertConfig.from_pretrained(UpperCamelCase   )
     BertModel.from_pretrained(UpperCamelCase   )
     BertTokenizer.from_pretrained(UpperCamelCase   )
     pipeline(task='fill-mask'   ,				model=UpperCamelCase   )

     # baseline - just load from_pretrained with normal network
     __a								=       [sys.executable, '-c', '\n'.join([load, run, mock]   )]

     # should succeed
     __a								=       self.get_env()
     __a								=       subprocess.run(UpperCamelCase   ,				env=UpperCamelCase   ,				check=UpperCamelCase   ,				capture_output=UpperCamelCase   )
     self.assertEqual(result.returncode   ,				0   ,				result.stderr   )
     self.assertIn('success'   ,				result.stdout.decode()   )







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     Union[str, Any]:
     # this test is a bit tricky since TRANSFORMERS_OFFLINE can only be changed before
     # `transformers` is loaded, and it's too late for inside pytest - so we are changing it
     # while running an external program

     # python one-liner segments

     # this must be loaded before socket.socket is monkey-patched
     __a								=       '\nfrom transformers import BertConfig, BertModel, BertTokenizer\n        '

     __a								=       '\nmname = "hf-internal-testing/tiny-random-bert-sharded"\nBertConfig.from_pretrained(mname)\nBertModel.from_pretrained(mname)\nprint("success")\n        '

     __a								=       '\nimport socket\ndef offline_socket(*args, **kwargs): raise ValueError("Offline mode is enabled")\nsocket.socket = offline_socket\n        '

     # baseline - just load from_pretrained with normal network
     __a								=       [sys.executable, '-c', '\n'.join([load, run]   )]

     # should succeed
     __a								=       self.get_env()
     __a								=       subprocess.run(UpperCamelCase   ,				env=UpperCamelCase   ,				check=UpperCamelCase   ,				capture_output=UpperCamelCase   )
     self.assertEqual(result.returncode   ,				0   ,				result.stderr   )
     self.assertIn('success'   ,				result.stdout.decode()   )

     # next emulate no network
     __a								=       [sys.executable, '-c', '\n'.join([load, mock, run]   )]

     # Doesn't fail anymore since the model is in the cache due to other tests, so commenting this.
     # env["TRANSFORMERS_OFFLINE"] = "0"
     # result = subprocess.run(cmd, env=env, check=False, capture_output=True)
     # self.assertEqual(result.returncode, 1, result.stderr)

     # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
     __a								=       '1'
     __a								=       subprocess.run(UpperCamelCase   ,				env=UpperCamelCase   ,				check=UpperCamelCase   ,				capture_output=UpperCamelCase   )
     self.assertEqual(result.returncode   ,				0   ,				result.stderr   )
     self.assertIn('success'   ,				result.stdout.decode()   )







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     List[Any]:
     __a								=       '\nfrom transformers import pipeline\n        '
     __a								=       '\nmname = "hf-internal-testing/tiny-random-bert"\npipe = pipeline(model=mname)\n        '

     __a								=       '\nimport socket\ndef offline_socket(*args, **kwargs): raise socket.error("Offline mode is enabled")\nsocket.socket = offline_socket\n        '
     __a								=       self.get_env()
     __a								=       '1'
     __a								=       [sys.executable, '-c', '\n'.join([load, mock, run]   )]
     __a								=       subprocess.run(UpperCamelCase   ,				env=UpperCamelCase   ,				check=UpperCamelCase   ,				capture_output=UpperCamelCase   )
     self.assertEqual(result.returncode   ,				1   ,				result.stderr   )
     self.assertIn(
         'You cannot infer task automatically within `pipeline` when using offline mode'   ,				result.stderr.decode().replace('\n'   ,				''   )   ,				)







   @require_torch
   def 		UpperCamelCase__      (						self   )					->     List[str]:
     __a								=       '\nfrom transformers import AutoModel\n        '
     __a								=       '\nmname = "hf-internal-testing/test_dynamic_model"\nAutoModel.from_pretrained(mname, trust_remote_code=True)\nprint("success")\n        '

     # baseline - just load from_pretrained with normal network
     __a								=       [sys.executable, '-c', '\n'.join([load, run]   )]

     # should succeed
     __a								=       self.get_env()
     __a								=       subprocess.run(UpperCamelCase   ,				env=UpperCamelCase   ,				check=UpperCamelCase   ,				capture_output=UpperCamelCase   )
     self.assertEqual(result.returncode   ,				0   ,				result.stderr   )
     self.assertIn('success'   ,				result.stdout.decode()   )

     # should succeed as TRANSFORMERS_OFFLINE=1 tells it to use local files
     __a								=       '1'
     __a								=       subprocess.run(UpperCamelCase   ,				env=UpperCamelCase   ,				check=UpperCamelCase   ,				capture_output=UpperCamelCase   )
     self.assertEqual(result.returncode   ,				0   ,				result.stderr   )
     self.assertIn('success'   ,				result.stdout.decode()   )









'''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



