





"""simple docstring"""





SCREAMING_SNAKE_CASE__					=   "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						bytes			):







      '''simple docstring'''




      if not isinstance(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			):
            lowerCAmelCase  						=       F'a bytes-like object is required, not \'{data.__class__.__name__}\''
            raise TypeError(SCREAMING_SNAKE_CASE			)

      lowerCAmelCase  						=       """""".join(bin(SCREAMING_SNAKE_CASE			)[2:].zfill(8			) for byte in data			)

      lowerCAmelCase  						=       len(SCREAMING_SNAKE_CASE			) % 6 != 0

      if padding_needed:
            # The padding that will be added later
            lowerCAmelCase  						=       B"""=""" * ((6 - len(SCREAMING_SNAKE_CASE			) % 6) // 2)

            # Append binary_stream with arbitrary binary digits (0's by default) to make its
            # length a multiple of 6.
            binary_stream += "0" * (6 - len(SCREAMING_SNAKE_CASE			) % 6)
      else:
            lowerCAmelCase  						=       B""""""

      # Encode every 6 binary digits to their corresponding Base64 character
      return (
          "".join(
              B64_CHARSET[int(binary_stream[index : index + 6]							,						2			)]
              for index in range(0							,						len(SCREAMING_SNAKE_CASE			)							,						6			)			).encode()
          + padding
      )


def 			UpperCAmelCase__							(  SCREAMING_SNAKE_CASE     :						str			):







      '''simple docstring'''




      if not isinstance(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			) and not isinstance(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			):
            lowerCAmelCase  						=       (
                """argument should be a bytes-like object or ASCII string, """
                F'not \'{encoded_data.__class__.__name__}\''
            )
            raise TypeError(SCREAMING_SNAKE_CASE			)

      # In case encoded_data is a bytes-like object, make sure it contains only
      # ASCII characters so we convert it to a string object
      if isinstance(SCREAMING_SNAKE_CASE							,						SCREAMING_SNAKE_CASE			):
            try:
                  lowerCAmelCase  						=       encoded_data.decode("""utf-8"""			)
            except UnicodeDecodeError:
                  raise ValueError("""base64 encoded data should only contain ASCII characters"""			)

      lowerCAmelCase  						=       encoded_data.count("""="""			)

      # Check if the encoded string contains non base64 characters
      if padding:
            assert all(
                char in B64_CHARSET for char in encoded_data[:-padding]			), "Invalid base64 character(s) found."
      else:
            assert all(
                char in B64_CHARSET for char in encoded_data			), "Invalid base64 character(s) found."

      # Check the padding
      assert len(SCREAMING_SNAKE_CASE			) % 4 == 0 and padding < 3, "Incorrect padding"

      if padding:
            # Remove padding if there is one
            lowerCAmelCase  						=       encoded_data[:-padding]

            lowerCAmelCase  						=       """""".join(
                bin(B64_CHARSET.index(SCREAMING_SNAKE_CASE			)			)[2:].zfill(6			) for char in encoded_data			)[: -padding * 2]
      else:
            lowerCAmelCase  						=       """""".join(
                bin(B64_CHARSET.index(SCREAMING_SNAKE_CASE			)			)[2:].zfill(6			) for char in encoded_data			)

      lowerCAmelCase  						=       [
          int(binary_stream[index : index + 8]							,						2			)
          for index in range(0							,						len(SCREAMING_SNAKE_CASE			)							,						8			)
      ]

      return bytes(SCREAMING_SNAKE_CASE			)


if __name__ == "__main__":
       import doctest

       doctest.testmod()








import unittest

from transformers import is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device

from ...generation.test_utils import GenerationTesterMixin
from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, ids_tensor
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
			import torch

			from transformers import (
			    OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST,
			    OpenAIGPTConfig,
			    OpenAIGPTDoubleHeadsModel,
			    OpenAIGPTForSequenceClassification,
			    OpenAIGPTLMHeadModel,
			    OpenAIGPTModel,
			)




class     _SCREAMING_SNAKE_CASE     :



	def __init__(    self						,  lowercase						,  lowercase=13						,  lowercase=7						,  lowercase=True						,  lowercase=True						,  lowercase=True						,  lowercase=99						,  lowercase=32						,  lowercase=5						,  lowercase=4						,  lowercase=37						,  lowercase="gelu"						,  lowercase=0.1						,  lowercase=0.1						,  lowercase=512						,  lowercase=16						,  lowercase=2						,  lowercase=0.0_2						,  lowercase=3						,  lowercase=4						,  lowercase=None						,  )				->       List[str]:
					lowerCamelCase_						=			parent
					lowerCamelCase_						=			batch_size
					lowerCamelCase_						=			seq_length
					lowerCamelCase_						=			is_training
					lowerCamelCase_						=			use_token_type_ids
					lowerCamelCase_						=			use_labels
					lowerCamelCase_						=			vocab_size
					lowerCamelCase_						=			hidden_size
					lowerCamelCase_						=			num_hidden_layers
					lowerCamelCase_						=			num_attention_heads
					lowerCamelCase_						=			intermediate_size
					lowerCamelCase_						=			hidden_act
					lowerCamelCase_						=			hidden_dropout_prob
					lowerCamelCase_						=			attention_probs_dropout_prob
					lowerCamelCase_						=			max_position_embeddings
					lowerCamelCase_						=			type_vocab_size
					lowerCamelCase_						=			type_sequence_label_size
					lowerCamelCase_						=			initializer_range
					lowerCamelCase_						=			num_labels
					lowerCamelCase_						=			num_choices
					lowerCamelCase_						=			scope
					lowerCamelCase_						=			self.vocab_size - 1



	def     SCREAMING_SNAKE_CASE_(    self )				->       Any:
					lowerCamelCase_						=			ids_tensor([self.batch_size, self.seq_length]						,  self.vocab_size )

					lowerCamelCase_						=			None
					if self.use_token_type_ids:
									lowerCamelCase_						=			ids_tensor([self.batch_size, self.seq_length]						,  self.type_vocab_size )

					lowerCamelCase_						=			None
					lowerCamelCase_						=			None
					lowerCamelCase_						=			None
					if self.use_labels:
									lowerCamelCase_						=			ids_tensor([self.batch_size]						,  self.type_sequence_label_size )
									lowerCamelCase_						=			ids_tensor([self.batch_size, self.seq_length]						,  self.num_labels )
									lowerCamelCase_						=			ids_tensor([self.batch_size]						,  self.num_choices )

					lowerCamelCase_						=			OpenAIGPTConfig(
					    vocab_size=self.vocab_size						,  n_embd=self.hidden_size						,  n_layer=self.num_hidden_layers						,  n_head=self.num_attention_heads						,  n_positions=self.max_position_embeddings						,  pad_token_id=self.pad_token_id						,  )

					lowerCamelCase_						=			ids_tensor([self.num_hidden_layers, self.num_attention_heads]						,  2 )

					return (
					    config,
					    input_ids,
					    head_mask,
					    token_type_ids,
					    sequence_labels,
					    token_labels,
					    choice_labels,
					)



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       Dict:
					lowerCamelCase_						=			OpenAIGPTModel(config=lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  head_mask=lowercase )
					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase )
					lowerCamelCase_						=			model(lowercase )

					self.parent.assertEqual(result.last_hidden_state.shape						,  (self.batch_size, self.seq_length, self.hidden_size) )



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       int:
					lowerCamelCase_						=			OpenAIGPTLMHeadModel(lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  labels=lowercase )
					self.parent.assertEqual(result.loss.shape						,  () )
					self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.seq_length, self.vocab_size) )



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       Dict:
					lowerCamelCase_						=			OpenAIGPTDoubleHeadsModel(lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  labels=lowercase )
					self.parent.assertEqual(result.loss.shape						,  () )
					self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.seq_length, self.vocab_size) )



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  *lowercase )				->       int:
					lowerCamelCase_						=			self.num_labels
					lowerCamelCase_						=			OpenAIGPTForSequenceClassification(lowercase )
					model.to(lowercase )
					model.eval()

					lowerCamelCase_						=			ids_tensor([self.batch_size]						,  self.type_sequence_label_size )
					lowerCamelCase_						=			model(lowercase						,  token_type_ids=lowercase						,  labels=lowercase )
					self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels) )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Union[str, Any]:
					lowerCamelCase_						=			self.prepare_config_and_inputs()
					(
					    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    (
					    lowerCamelCase_
					)	,    
					)						=			config_and_inputs
					lowerCamelCase_						=			{
					    "input_ids": input_ids,
					    "token_type_ids": token_type_ids,
					    "head_mask": head_mask,
					}

					return config, inputs_dict




@require_torch
class     _SCREAMING_SNAKE_CASE     (      snake_case_			,       snake_case_			,       snake_case_			,       unittest.TestCase						):
	lowerCAmelCase__         = (
	    (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
	    if is_torch_available()
	    else ()
	)
	lowerCAmelCase__         = (
	    (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
	)  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
	lowerCAmelCase__         = (
	    {
	        'feature-extraction': OpenAIGPTModel,
	        'text-classification': OpenAIGPTForSequenceClassification,
	        'text-generation': OpenAIGPTLMHeadModel,
	        'zero-shot': OpenAIGPTForSequenceClassification,
	    }
	    if is_torch_available()
	    else {}
	)



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase						,  lowercase						,  lowercase )				->       int:
					if pipeline_test_casse_name == "ZeroShotClassificationPipelineTests":
									# Get `tokenizer does not have a padding token` error for both fast/slow tokenizers.
									# `OpenAIGPTConfig` was never used in pipeline tests, either because of a missing checkpoint or because a
									# tiny config could not be created.
									return True

					return False



	def     SCREAMING_SNAKE_CASE_(    self						,  lowercase						,  lowercase						,  lowercase=False )				->       Any:
					lowerCamelCase_						=			super()._prepare_for_class(lowercase						,  lowercase						,  return_labels=lowercase )

					if return_labels:
									if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
													lowerCamelCase_						=			torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)						,  dtype=torch.long						,  device=lowercase						,  )
													lowerCamelCase_						=			inputs_dict["labels"]
													lowerCamelCase_						=			inputs_dict["labels"]
													lowerCamelCase_						=			torch.zeros(
													    (self.model_tester.batch_size, self.model_tester.num_choices)						,  dtype=torch.long						,  device=lowercase						,  )
													lowerCamelCase_						=			torch.zeros(
													    self.model_tester.batch_size						,  dtype=torch.long						,  device=lowercase )
					return inputs_dict



	def     SCREAMING_SNAKE_CASE_(    self )				->       Dict:
					lowerCamelCase_						=			OpenAIGPTModelTester(self )
					lowerCamelCase_						=			ConfigTester(self						,  config_class=lowercase						,  n_embd=37 )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Any:
					self.config_tester.run_common_tests()



	def     SCREAMING_SNAKE_CASE_(    self )				->       Union[str, Any]:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_openai_gpt_model(*lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       str:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_lm_head_model(*lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Tuple:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_double_lm_head_model(*lowercase )



	def     SCREAMING_SNAKE_CASE_(    self )				->       Optional[Any]:
					lowerCamelCase_						=			self.model_tester.prepare_config_and_inputs()
					self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*lowercase )



	@slow
	def     SCREAMING_SNAKE_CASE_(    self )				->       Any:
					for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
									lowerCamelCase_						=			OpenAIGPTModel.from_pretrained(lowercase )
									self.assertIsNotNone(lowercase )




@require_torch
class     _SCREAMING_SNAKE_CASE     (      unittest.TestCase						):



	@slow
	def     SCREAMING_SNAKE_CASE_(    self )				->       str:
					lowerCamelCase_						=			OpenAIGPTLMHeadModel.from_pretrained("openai-gpt" )
					model.to(lowercase )
					lowerCamelCase_						=			torch.tensor([[481, 4735, 544]]						,  dtype=torch.long						,  device=lowercase )  # the president is
					lowerCamelCase_						=			[
					    481,
					    4735,
					    544,
					    246,
					    963,
					    870,
					    762,
					    239,
					    244,
					    40477,
					    244,
					    249,
					    719,
					    881,
					    487,
					    544,
					    240,
					    244,
					    603,
					    481,
					]  # the president is a very good man. " \n " i\'m sure he is, " said the

					lowerCamelCase_						=			model.generate(lowercase						,  do_sample=lowercase )
					self.assertListEqual(output_ids[0].tolist()						,  lowercase )


