


import json
import os
import re
import unicodedata
from json.encoder import INFINITY
from typing import Any, Dict, List, Optional, Tuple, Union

import numpy as np
import regex

from ...tokenization_utils import AddedToken, PreTrainedTokenizer
from ...tokenization_utils_base import BatchEncoding
from ...utils import TensorType, is_flax_available, is_tf_available, is_torch_available, logging
from ...utils.generic import _is_jax, _is_numpy


A			:						Tuple        =  logging.get_logger(__name__)

A			:						Any        =  {
    'artists_file': 'artists.json',
    'lyrics_file': 'lyrics.json',
    'genres_file': 'genres.json',
}

A			:						Dict        =  {
    'artists_file': {
        'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/artists.json',
    },
    'genres_file': {
        'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/genres.json',
    },
    'lyrics_file': {
        'jukebox': 'https://huggingface.co/ArthurZ/jukebox/blob/main/lyrics.json',
    },
}

A			:						Optional[Any]        =  {
    'jukebox': 5_1_2,
}



class 				A       (			UpperCamelCase_				):
					'''simple docstring'''






					A__     =					VOCAB_FILES_NAMES
					A__     =					PRETRAINED_VOCAB_FILES_MAP
					A__     =					PRETRAINED_LYRIC_TOKENS_SIZES
					A__     =					["""input_ids""", """attention_mask"""]

					def __init__(self       :		Any ,   _UpperCAmelCase       :		Any ,   _UpperCAmelCase       :		Optional[Any] ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		str=["v3", "v2", "v2"] ,   _UpperCAmelCase       :		str=512 ,   _UpperCAmelCase       :		str=5 ,   _UpperCAmelCase       :		Dict="<|endoftext|>" ,   **_UpperCAmelCase       :		List[str] ,   )		->  int:




							"""simple docstring"""


							lowercase__	     =						AddedToken(a__ ,   lstrip=a__ ,   rstrip=a__						) if isinstance(a__ ,   a__						) else unk_token
							super().__init__(
							    unk_token=a__ ,   n_genres=a__ ,   version=a__ ,   max_n_lyric_tokens=a__ ,   **a__ ,   )
							lowercase__	     =						version
							lowercase__	     =						max_n_lyric_tokens
							lowercase__	     =						n_genres

							with open(a__ ,   encoding="""utf-8"""						) as vocab_handle:
									lowercase__	     =						json.load(a__						)

							with open(a__ ,   encoding="""utf-8"""						) as vocab_handle:
									lowercase__	     =						json.load(a__						)

							with open(a__ ,   encoding="""utf-8"""						) as vocab_handle:
									lowercase__	     =						json.load(a__						)

							lowercase__	     =						r"[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+"
							# In v2, we had a n_vocab=80 and in v3 we missed + and so n_vocab=79 of characters.
							if len(self.lyrics_encoder						) == 79:
									lowercase__	     =						oov.replace(r"""\-'""" ,   r"""\-+'"""						)

							lowercase__	     =						regex.compile(a__						)
							lowercase__	     =						{v: k for k, v in self.artists_encoder.items()}
							lowercase__	     =						{v: k for k, v in self.genres_encoder.items()}
							lowercase__	     =						{v: k for k, v in self.lyrics_encoder.items()}

					@property
					def     lowerCamelCase__	(self       :		Optional[Any]						)		->  List[Any]:




							"""simple docstring"""


							return len(self.artists_encoder						) + len(self.genres_encoder						) + len(self.lyrics_encoder						)

					def     lowerCamelCase__	(self       :		Any						)		->  Tuple:




							"""simple docstring"""


							return dict(self.artists_encoder ,   self.genres_encoder ,   self.lyrics_encoder						)

					def     lowerCamelCase__	(self       :		int ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		int ,   _UpperCAmelCase       :		int						)		->  Optional[int]:




							"""simple docstring"""


							lowercase__	     =						[self.artists_encoder.get(a__ ,   0						) for artist in list_artists]
							for genres in range(len(a__						)						):
									lowercase__	     =						[self.genres_encoder.get(a__ ,   0						) for genre in list_genres[genres]]
									lowercase__	     =						list_genres[genres] + [-1] * (self.n_genres - len(list_genres[genres]						))

							lowercase__	     =						[[self.lyrics_encoder.get(a__ ,   0						) for character in list_lyrics[0]], [], []]
							return artists_id, list_genres, lyric_ids

					def     lowerCamelCase__	(self       :		Dict ,   _UpperCAmelCase       :		Any						)		->  Dict:




							"""simple docstring"""


							return list(a__						)

					def     lowerCamelCase__	(self       :		Optional[Any] ,   _UpperCAmelCase       :		List[str] ,   _UpperCAmelCase       :		Union[str, Any] ,   _UpperCAmelCase       :		List[str] ,   **_UpperCAmelCase       :		Optional[Any]						)		->  List[Any]:




							"""simple docstring"""


							lowercase__	     =						self.prepare_for_tokenization(a__ ,   a__ ,   a__						)
							lowercase__	     =						self._tokenize(a__						)
							return artist, genre, lyrics

					def     lowerCamelCase__	(self       :		List[Any] ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		bool = False						)		->  List[Any]:




							"""simple docstring"""


							for idx in range(len(self.version						)						):
									if self.version[idx] == "v3":
											lowercase__	     =						artists[idx].lower()
											lowercase__	     =						[genres[idx].lower()]
									else:
											lowercase__	     =						self._normalize(artists[idx]						) + ".v2"
											lowercase__	     =						[
											    self._normalize(a__						) + ".v2" for genre in genres[idx].split("""_"""						)
											]  # split is for the full dictionary with combined genres

							if self.version[0] == "v2":
									lowercase__	     =						regex.compile(r"""[^A-Za-z0-9.,:;!?\-'\"()\[\] \t\n]+"""						)
									lowercase__	     =						"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789.,:;!?-+'\"()[] \t\n"
									lowercase__	     =						{vocab[index]: index + 1 for index in range(len(a__						)						)}
									lowercase__	     =						0
									lowercase__	     =						len(a__						) + 1
									lowercase__	     =						self.vocab
									lowercase__	     =						{v: k for k, v in self.vocab.items()}
									lowercase__	     =						""
							else:
									lowercase__	     =						regex.compile(r"""[^A-Za-z0-9.,:;!?\-+'\"()\[\] \t\n]+"""						)

							lowercase__	     =						self._run_strip_accents(a__						)
							lowercase__	     =						lyrics.replace("""\\""" ,   """\n"""						)
							lowercase__	     =						self.out_of_vocab.sub("""""" ,   a__						), [], []
							return artists, genres, lyrics

					def     lowerCamelCase__	(self       :		Optional[Any] ,   _UpperCAmelCase       :		Dict						)		->  Any:




							"""simple docstring"""


							lowercase__	     =						unicodedata.normalize("""NFD""" ,   a__						)
							lowercase__	     =						[]
							for char in text:
									lowercase__	     =						unicodedata.category(a__						)
									if cat == "Mn":
											continue
									output.append(a__						)
							return "".join(a__						)

					def     lowerCamelCase__	(self       :		int ,   _UpperCAmelCase       :		str						)		->  str:




							"""simple docstring"""


							lowercase__	     =						(
							    [chr(a__						) for i in range(ord("""a"""						) ,   ord("""z"""						) + 1						)]
							    + [chr(a__						) for i in range(ord("""A"""						) ,   ord("""Z"""						) + 1						)]
							    + [chr(a__						) for i in range(ord("""0"""						) ,   ord("""9"""						) + 1						)]
							    + ["."]
							)
							lowercase__	     =						frozenset(a__						)
							lowercase__	     =						re.compile(r"""_+"""						)
							lowercase__	     =						"".join([c if c in accepted else """_""" for c in text.lower()]						)
							lowercase__	     =						pattern.sub("""_""" ,   a__						).strip("""_"""						)
							return text

					def     lowerCamelCase__	(self       :		Any ,   _UpperCAmelCase       :		List[str]						)		->  Optional[Any]:




							"""simple docstring"""


							return " ".join(a__						)

					def     lowerCamelCase__	(self       :		Any ,   _UpperCAmelCase       :		Optional[Any] ,   _UpperCAmelCase       :		Optional[Union[str, TensorType]] = None ,   _UpperCAmelCase       :		bool = False						)		->  Optional[Any]:




							"""simple docstring"""


							if not isinstance(a__ ,   a__						):
									lowercase__	     =						TensorType(a__						)

							# Get a function reference for the correct framework
							if tensor_type == TensorType.TENSORFLOW:
									if not is_tf_available():
											raise ImportError(
											    """Unable to convert output to TensorFlow tensors format, TensorFlow is not installed."""						)
									import tensorflow as tf

									lowercase__	     =						tf.constant
									lowercase__	     =						tf.is_tensor
							elif tensor_type == TensorType.PYTORCH:
									if not is_torch_available():
											raise ImportError("""Unable to convert output to PyTorch tensors format, PyTorch is not installed."""						)
									import torch

									lowercase__	     =						torch.tensor
									lowercase__	     =						torch.is_tensor
							elif tensor_type == TensorType.JAX:
									if not is_flax_available():
											raise ImportError("""Unable to convert output to JAX tensors format, JAX is not installed."""						)
									import jax.numpy as jnp  # noqa: F811

									lowercase__	     =						jnp.array
									lowercase__	     =						_is_jax
							else:
									lowercase__	     =						np.asarray
									lowercase__	     =						_is_numpy

							# Do the tensor conversion in batch

							try:
									if prepend_batch_axis:
											lowercase__	     =						[inputs]

									if not is_tensor(a__						):
											lowercase__	     =						as_tensor(a__						)
							except:  # noqa E722
									raise ValueError(
									    """Unable to create tensor, you should probably activate truncation and/or padding """
									    """with 'padding=True' 'truncation=True' to have batched tensors with the same length."""						)

							return inputs

					def __call__(self       :		Union[str, Any] ,   _UpperCAmelCase       :		Optional[int] ,   _UpperCAmelCase       :		List[Any] ,   _UpperCAmelCase       :		Tuple="" ,   _UpperCAmelCase       :		Tuple="pt"						)		->  Tuple:




							"""simple docstring"""


							lowercase__	     =						[0, 0, 0]
							lowercase__	     =						[artist] * len(self.version						)
							lowercase__	     =						[genres] * len(self.version						)

							lowercase__	     =						self.tokenize(a__ ,   a__ ,   a__						)
							lowercase__	     =						self._convert_token_to_id(a__ ,   a__ ,   a__						)

							lowercase__	     =						[-INFINITY] * len(full_tokens[-1]						)
							lowercase__	     =						[
							    self.convert_to_tensors(
							        [input_ids + [artists_id[i]] + genres_ids[i] + full_tokens[i]] ,   tensor_type=a__						)
							    for i in range(len(self.version						)						)
							]
							return BatchEncoding({"""input_ids""": input_ids, """attention_masks""": attention_masks}						)

					def     lowerCamelCase__	(self       :		Optional[int] ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		Optional[str] = None						)		->  Optional[Any]:




							"""simple docstring"""


							if not os.path.isdir(a__						):
									logger.error(f'''Vocabulary path ({save_directory}) should be a directory'''						)
									return

							lowercase__	     =						os.path.join(
							    a__ ,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""artists_file"""]						)
							with open(a__ ,   """w""" ,   encoding="""utf-8"""						) as f:
									f.write(json.dumps(self.artists_encoder ,   ensure_ascii=a__						)						)

							lowercase__	     =						os.path.join(
							    a__ ,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""genres_file"""]						)
							with open(a__ ,   """w""" ,   encoding="""utf-8"""						) as f:
									f.write(json.dumps(self.genres_encoder ,   ensure_ascii=a__						)						)

							lowercase__	     =						os.path.join(
							    a__ ,   (filename_prefix + """-""" if filename_prefix else """""") + VOCAB_FILES_NAMES["""lyrics_file"""]						)
							with open(a__ ,   """w""" ,   encoding="""utf-8"""						) as f:
									f.write(json.dumps(self.lyrics_encoder ,   ensure_ascii=a__						)						)

							return (artists_file, genres_file, lyrics_file)


					def     lowerCamelCase__	(self       :		List[Any] ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		str ,   _UpperCAmelCase       :		List[str]						)		->  List[str]:




							"""simple docstring"""


							lowercase__	     =						self.artists_decoder.get(a__						)
							lowercase__	     =						[self.genres_decoder.get(a__						) for genre in genres_index]
							lowercase__	     =						[self.lyrics_decoder.get(a__						) for character in lyric_index]
							return artist, genres, lyrics



'''simple docstring'''

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    lowerCAmelCase       :


 def __init__(    self  : str			,							a__  : Union[str, Any]			,							a__  : Union[str, Any]=13			,							a__  : Union[str, Any]=7			,							a__  : Any=True			,							a__  : str=True			,							a__  : Optional[Any]=True			,							a__  : Any=99			,							a__  : Dict=32			,							a__  : Tuple=5			,							a__  : List[Any]=4			,							a__  : List[Any]=37			,							a__  : List[str]="gelu"			,							a__  : Dict=0.1			,							a__  : str=0.1			,							a__  : str=512			,							a__  : List[str]=16			,							a__  : Dict=2			,							a__  : Union[str, Any]=0.02			,							a__  : Dict=3			,							a__  : List[Any]=4			,							a__  : Optional[int]=None			,							):
  '''simple docstring'''

  lowerCAmelCase__     :   List[Any]     		=	parent
  lowerCAmelCase__     :   Optional[Any]     		=	batch_size
  lowerCAmelCase__     :   Optional[int]     		=	seq_length
  lowerCAmelCase__     :   int     		=	is_training
  lowerCAmelCase__     :   int     		=	use_token_type_ids
  lowerCAmelCase__     :   List[Any]     		=	use_labels
  lowerCAmelCase__     :   int     		=	vocab_size
  lowerCAmelCase__     :   Dict     		=	hidden_size
  lowerCAmelCase__     :   Tuple     		=	num_hidden_layers
  lowerCAmelCase__     :   Tuple     		=	num_attention_heads
  lowerCAmelCase__     :   Any     		=	intermediate_size
  lowerCAmelCase__     :   Optional[int]     		=	hidden_act
  lowerCAmelCase__     :   Optional[int]     		=	hidden_dropout_prob
  lowerCAmelCase__     :   Optional[Any]     		=	attention_probs_dropout_prob
  lowerCAmelCase__     :   Tuple     		=	max_position_embeddings
  lowerCAmelCase__     :   str     		=	type_vocab_size
  lowerCAmelCase__     :   List[Any]     		=	type_sequence_label_size
  lowerCAmelCase__     :   List[str]     		=	initializer_range
  lowerCAmelCase__     :   Tuple     		=	num_labels
  lowerCAmelCase__     :   Optional[Any]     		=	num_choices
  lowerCAmelCase__     :   int     		=	scope
  lowerCAmelCase__     :   List[str]     		=	self.vocab_size - 1


 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.vocab_size    )

  lowerCAmelCase__     :   Dict     		=	None
  if self.use_token_type_ids:
   lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.type_vocab_size    )

  lowerCAmelCase__     :   List[str]     		=	None
  lowerCAmelCase__     :   Tuple     		=	None
  lowerCAmelCase__     :   Optional[int]     		=	None
  if self.use_labels:
   lowerCAmelCase__     :   int     		=	ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
   lowerCAmelCase__     :   Any     		=	ids_tensor([self.batch_size, self.seq_length]			,							self.num_labels    )
   lowerCAmelCase__     :   Optional[Any]     		=	ids_tensor([self.batch_size]			,							self.num_choices    )

  lowerCAmelCase__     :   Any     		=	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__     :   Optional[Any]     		=	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    _A	(    self  : Dict			,							a__  : Any			,							a__  : Any			,							a__  : int			,							a__  : str			,							*a__  : Optional[Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModel(config=a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							head_mask=a__    )
  lowerCAmelCase__     :   Optional[int]     		=	model(a__			,							token_type_ids=a__    )
  lowerCAmelCase__     :   Any     		=	model(a__    )

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


 def    _A	(    self  : Optional[int]			,							a__  : List[Any]			,							a__  : int			,							a__  : Dict			,							a__  : Any			,							*a__  : Any    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	OpenAIGPTLMHeadModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Dict     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : List[str]			,							a__  : str			,							a__  : Dict			,							a__  : Union[str, Any]			,							a__  : int			,							*a__  : Dict    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	OpenAIGPTDoubleHeadsModel(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   Optional[Any]     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.loss.shape			,							()    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.seq_length, self.vocab_size)    )


 def    _A	(    self  : Any			,							a__  : Any			,							a__  : Union[str, Any]			,							a__  : Optional[int]			,							a__  : Any			,							*a__  : List[str]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[Any]     		=	self.num_labels
  lowerCAmelCase__     :   Union[str, Any]     		=	OpenAIGPTForSequenceClassification(a__    )
  model.to(a__    )
  model.eval()

  lowerCAmelCase__     :   List[str]     		=	ids_tensor([self.batch_size]			,							self.type_sequence_label_size    )
  lowerCAmelCase__     :   Tuple     		=	model(a__			,							token_type_ids=a__			,							labels=a__    )
  self.parent.assertEqual(result.logits.shape			,							(self.batch_size, self.num_labels)    )


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   List[str]     		=	self.prepare_config_and_inputs()
  (
      (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     (
      lowerCAmelCase__
  )		,     
  )     :   Union[str, Any]     		=	config_and_inputs
  lowerCAmelCase__     :   str     		=	{
      "input_ids": input_ids,
      "token_type_ids": token_type_ids,
      "head_mask": head_mask,
  }

  return config, inputs_dict




@require_torch
class    lowerCAmelCase       (     UpperCamelCase_    ,  UpperCamelCase_    ,  UpperCamelCase_    ,  unittest.TestCase  ):
 A_				:				str	=			(
     (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
     if is_torch_available()
     else ()
 )
 A_				:				Any	=			(
     (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
 )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
 A_				:				int	=			(
     {
         """feature-extraction""": OpenAIGPTModel,
         """text-classification""": OpenAIGPTForSequenceClassification,
         """text-generation""": OpenAIGPTLMHeadModel,
         """zero-shot""": OpenAIGPTForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )


 def    _A	(    self  : List[Any]			,							a__  : Optional[Any]			,							a__  : Optional[int]			,							a__  : Optional[Any]			,							a__  : List[Any]			,							a__  : int    ):
  '''simple docstring'''

  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    _A	(    self  : Dict			,							a__  : Optional[int]			,							a__  : List[Any]			,							a__  : List[Any]=False    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Any     		=	super()._prepare_for_class(a__			,							a__			,							return_labels=a__    )

  if return_labels:
   if model_class.__name__ == "OpenAIGPTDoubleHeadsModel":
    lowerCAmelCase__     :   Tuple     		=	torch.zeros(
        (self.model_tester.batch_size, self.model_tester.num_choices, self.model_tester.seq_length)			,							dtype=torch.long			,							device=a__			,							)
    lowerCAmelCase__     :   Union[str, Any]     		=	inputs_dict["labels"]
    lowerCAmelCase__     :   int     		=	inputs_dict["labels"]
    lowerCAmelCase__     :   Optional[int]     		=	torch.zeros(
        (self.model_tester.batch_size, self.model_tester.num_choices)			,							dtype=torch.long			,							device=a__			,							)
    lowerCAmelCase__     :   List[str]     		=	torch.zeros(
        self.model_tester.batch_size			,							dtype=torch.long			,							device=a__    )
  return inputs_dict


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   str     		=	OpenAIGPTModelTester(self    )
  lowerCAmelCase__     :   Any     		=	ConfigTester(self			,							config_class=a__			,							n_embd=37    )


 def    _A	(    self  : List[str]    ):
  '''simple docstring'''

  self.config_tester.run_common_tests()


 def    _A	(    self  : Optional[int]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Dict     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_openai_gpt_model(*a__    )


 def    _A	(    self  : Union[str, Any]    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Optional[int]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_lm_head_model(*a__    )


 def    _A	(    self  : int    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Tuple     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_double_lm_head_model(*a__    )


 def    _A	(    self  : str    ):
  '''simple docstring'''

  lowerCAmelCase__     :   Union[str, Any]     		=	self.model_tester.prepare_config_and_inputs()
  self.model_tester.create_and_check_openai_gpt_for_sequence_classification(*a__    )


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
   lowerCAmelCase__     :   Any     		=	OpenAIGPTModel.from_pretrained(a__    )
   self.assertIsNotNone(a__    )




@require_torch
class    lowerCAmelCase       (     unittest.TestCase  ):


 @slow
 def    _A	(    self  : Tuple    ):
  '''simple docstring'''

  lowerCAmelCase__     :   int     		=	OpenAIGPTLMHeadModel.from_pretrained("openai-gpt"    )
  model.to(a__    )
  lowerCAmelCase__     :   Union[str, Any]     		=	torch.tensor([[481, 4735, 544]]			,							dtype=torch.long			,							device=a__    )  # the president is
  lowerCAmelCase__     :   Optional[int]     		=	[
      481,
      4735,
      544,
      246,
      963,
      870,
      762,
      239,
      244,
      4_0477,
      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__     :   Optional[int]     		=	model.generate(a__			,							do_sample=a__    )
  self.assertListEqual(output_ids[0].tolist()			,							a__    )





