

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     __lowercase :
 def __init__(				self ,				A_ ,				A_=13 ,				A_=7 ,				A_=True ,				A_=True ,				A_=True ,				A_=99 ,				A_=32 ,				A_=5 ,				A_=4 ,				A_=37 ,				A_="gelu" ,				A_=0.1 ,				A_=0.1 ,				A_=512 ,				A_=16 ,				A_=2 ,				A_=0.02 ,				A_=3 ,				A_=4 ,				A_=None ,				)   ->Any:



       '''simple docstring'''





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



       '''simple docstring'''





       __lowerCAmelCase   :		Tuple   =   ids_tensor([self.batch_size, self.seq_length] ,				self.vocab_size   )

       __lowerCAmelCase   :		int   =   None
       if self.use_token_type_ids:
             __lowerCAmelCase   :		List[Any]   =   ids_tensor([self.batch_size, self.seq_length] ,				self.type_vocab_size   )

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

       __lowerCAmelCase   :		List[str]   =   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   :		Tuple   =   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       UpperCamelCase__    (				self ,				A_ ,				A_ ,				A_ ,				A_ ,				*A_   )   ->Dict:



       '''simple docstring'''





       __lowerCAmelCase   :		List[Any]   =   OpenAIGPTModel(config=__lowerCamelCase   )
       model.to(__lowerCamelCase   )
       model.eval()

       __lowerCAmelCase   :		Any   =   model(__lowerCamelCase ,				token_type_ids=__lowerCamelCase ,				head_mask=__lowerCamelCase   )
       __lowerCAmelCase   :		Union[str, Any]   =   model(__lowerCamelCase ,				token_type_ids=__lowerCamelCase   )
       __lowerCAmelCase   :		Dict   =   model(__lowerCamelCase   )

       self.parent.assertEqual(result.last_hidden_state.shape ,				(self.batch_size, self.seq_length, self.hidden_size)   )
 def       UpperCamelCase__    (				self ,				A_ ,				A_ ,				A_ ,				A_ ,				*A_   )   ->Optional[int]:



       '''simple docstring'''





       __lowerCAmelCase   :		List[str]   =   OpenAIGPTLMHeadModel(__lowerCamelCase   )
       model.to(__lowerCamelCase   )
       model.eval()

       __lowerCAmelCase   :		List[str]   =   model(__lowerCamelCase ,				token_type_ids=__lowerCamelCase ,				labels=__lowerCamelCase   )
       self.parent.assertEqual(result.loss.shape ,				()   )
       self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.seq_length, self.vocab_size)   )
 def       UpperCamelCase__    (				self ,				A_ ,				A_ ,				A_ ,				A_ ,				*A_   )   ->Tuple:



       '''simple docstring'''





       __lowerCAmelCase   :		Optional[int]   =   OpenAIGPTDoubleHeadsModel(__lowerCamelCase   )
       model.to(__lowerCamelCase   )
       model.eval()

       __lowerCAmelCase   :		List[Any]   =   model(__lowerCamelCase ,				token_type_ids=__lowerCamelCase ,				labels=__lowerCamelCase   )
       self.parent.assertEqual(result.loss.shape ,				()   )
       self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.seq_length, self.vocab_size)   )
 def       UpperCamelCase__    (				self ,				A_ ,				A_ ,				A_ ,				A_ ,				*A_   )   ->Any:



       '''simple docstring'''





       __lowerCAmelCase   :		int   =   self.num_labels
       __lowerCAmelCase   :		Optional[int]   =   OpenAIGPTForSequenceClassification(__lowerCamelCase   )
       model.to(__lowerCamelCase   )
       model.eval()

       __lowerCAmelCase   :		Any   =   ids_tensor([self.batch_size] ,				self.type_sequence_label_size   )
       __lowerCAmelCase   :		Union[str, Any]   =   model(__lowerCamelCase ,				token_type_ids=__lowerCamelCase ,				labels=__lowerCamelCase   )
       self.parent.assertEqual(result.logits.shape ,				(self.batch_size, self.num_labels)   )





 def       UpperCamelCase__    (				self   )   ->List[Any]:



       '''simple docstring'''





       __lowerCAmelCase   :		Any   =   self.prepare_config_and_inputs()
       (
           (
           __lowerCAmelCase      
       ),				(
           __lowerCAmelCase      
       ),				(
           __lowerCAmelCase      
       ),				(
           __lowerCAmelCase      
       ),				(
           __lowerCAmelCase      
       ),				(
           __lowerCAmelCase      
       ),				(
           __lowerCAmelCase      
       ),				      
       )   :		Optional[int]   =   config_and_inputs
       __lowerCAmelCase   :		Dict   =   {
           '''input_ids''': input_ids,
           '''token_type_ids''': token_type_ids,
           '''head_mask''': head_mask,
       }

       return config, inputs_dict







@require_torch
class     __lowercase (_a						,  _a						,  _a						,  unittest.TestCase					):
 _UpperCamelCase         =    (
     (OpenAIGPTModel, OpenAIGPTLMHeadModel, OpenAIGPTDoubleHeadsModel, OpenAIGPTForSequenceClassification)
     if is_torch_available()
     else ()
 )
 _UpperCamelCase         =    (
     (OpenAIGPTLMHeadModel,) if is_torch_available() else ()
 )  # TODO (PVP): Add Double HeadsModel when generate() function is changed accordingly
 _UpperCamelCase         =    (
     {
         "feature-extraction": OpenAIGPTModel,
         "text-classification": OpenAIGPTForSequenceClassification,
         "text-generation": OpenAIGPTLMHeadModel,
         "zero-shot": OpenAIGPTForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )
 def       UpperCamelCase__    (				self ,				A_ ,				A_ ,				A_ ,				A_ ,				A_   )   ->Dict:



       '''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       UpperCamelCase__    (				self ,				A_ ,				A_ ,				A_=False   )   ->str:



       '''simple docstring'''





       __lowerCAmelCase   :		Optional[int]   =   super()._prepare_for_class(__lowerCamelCase ,				__lowerCamelCase ,				return_labels=__lowerCamelCase   )

       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=__lowerCamelCase ,				)
                   __lowerCAmelCase   :		Optional[int]   =   inputs_dict['''labels''']
                   __lowerCAmelCase   :		str   =   inputs_dict['''labels''']
                   __lowerCAmelCase   :		Dict   =   torch.zeros(
                       (self.model_tester.batch_size, self.model_tester.num_choices) ,				dtype=torch.long ,				device=__lowerCamelCase ,				)
                   __lowerCAmelCase   :		Dict   =   torch.zeros(
                       self.model_tester.batch_size ,				dtype=torch.long ,				device=__lowerCamelCase   )
       return inputs_dict
 def       UpperCamelCase__    (				self   )   ->List[str]:



       '''simple docstring'''





       __lowerCAmelCase   :		List[Any]   =   OpenAIGPTModelTester(self   )
       __lowerCAmelCase   :		List[Any]   =   ConfigTester(self ,				config_class=__lowerCamelCase ,				n_embd=37   )
 def       UpperCamelCase__    (				self   )   ->Optional[Any]:



       '''simple docstring'''





       self.config_tester.run_common_tests()
 def       UpperCamelCase__    (				self   )   ->Union[str, Any]:



       '''simple docstring'''





       __lowerCAmelCase   :		List[Any]   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_openai_gpt_model(*__lowerCamelCase   )
 def       UpperCamelCase__    (				self   )   ->Any:



       '''simple docstring'''





       __lowerCAmelCase   :		Optional[Any]   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_lm_head_model(*__lowerCamelCase   )
 def       UpperCamelCase__    (				self   )   ->Optional[Any]:



       '''simple docstring'''





       __lowerCAmelCase   :		Optional[int]   =   self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_double_lm_head_model(*__lowerCamelCase   )
 def       UpperCamelCase__    (				self   )   ->Dict:



       '''simple docstring'''





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





 @slow
 def       UpperCamelCase__    (				self   )   ->Any:



       '''simple docstring'''





       for model_name in OPENAI_GPT_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
             __lowerCAmelCase   :		str   =   OpenAIGPTModel.from_pretrained(__lowerCamelCase   )
             self.assertIsNotNone(__lowerCamelCase   )







@require_torch
class     __lowercase (unittest.TestCase					):
 @slow
 def       UpperCamelCase__    (				self   )   ->str:



       '''simple docstring'''





       __lowerCAmelCase   :		Dict   =   OpenAIGPTLMHeadModel.from_pretrained('''openai-gpt'''   )
       model.to(__lowerCamelCase   )
       __lowerCAmelCase   :		Any   =   torch.tensor([[481, 4735, 544]] ,				dtype=torch.long ,				device=__lowerCamelCase   )  # the president is
       __lowerCAmelCase   :		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   :		Tuple   =   model.generate(__lowerCamelCase ,				do_sample=__lowerCamelCase   )
       self.assertListEqual(output_ids[0].tolist() ,				__lowerCamelCase   )








from __future__ import annotations
def 		a_							( __lowerCAmelCase   , __lowerCAmelCase = None				):
  lowerCAmelCase__										=      word_bank or []
  # create a table
  lowerCAmelCase__										=      len(__lowerCAmelCase				) + 1

  lowerCAmelCase__										=      []
  for _ in range(__lowerCAmelCase				):
    table.append([]				)
  # seed value
  lowerCAmelCase__										=      [[]]  # because empty string has empty combination

  # iterate through the indices
  for i in range(__lowerCAmelCase				):
    # condition
    if table[i] != []:
      for word in word_bank:
        # slice condition
        if target[i : i + len(__lowerCAmelCase				)] == word:
          lowerCAmelCase__										=      [
              [word, *way] for way in table[i]
          ]
          # adds the word to every combination the current position holds
          # now,push that combination to the table[i+len(word)]
          table[i + len(__lowerCAmelCase				)] += new_combinations

    # combinations are in reverse order so reverse for better output
  for combination in table[len(__lowerCAmelCase				)]:
    combination.reverse()

  return table[len(__lowerCAmelCase				)]


if __name__ == "__main__":
      print(all_construct("""jwajalapa""", ["""jwa""", """j""", """w""", """a""", """la""", """lapa"""]))
      print(all_construct("""rajamati""", ["""s""", """raj""", """amat""", """raja""", """ma""", """i""", """t"""]))
      print(
          all_construct(
              """hexagonosaurus""",
              ["""h""", """ex""", """hex""", """ag""", """ago""", """ru""", """auru""", """rus""", """go""", """no""", """o""", """s"""],
          )
      )

