





import argparse
import inspect
import logging
from typing import Tuple

import numpy as np
import torch

from transformers import (
    AutoTokenizer,
    BloomForCausalLM,
    BloomTokenizerFast,
    CTRLLMHeadModel,
    CTRLTokenizer,
    GenerationMixin,
    GPTaLMHeadModel,
    GPTaTokenizer,
    GPTJForCausalLM,
    LlamaForCausalLM,
    LlamaTokenizer,
    OpenAIGPTLMHeadModel,
    OpenAIGPTTokenizer,
    OPTForCausalLM,
    TransfoXLLMHeadModel,
    TransfoXLTokenizer,
    XLMTokenizer,
    XLMWithLMHeadModel,
    XLNetLMHeadModel,
    XLNetTokenizer,
)
from transformers.modeling_outputs import CausalLMOutputWithPast


logging.basicConfig(
    format="%(asctime)s - %(levelname)s - %(name)s - %(message)s",
    datefmt="%m/%d/%Y %H:%M:%S",
    level=logging.INFO,
)
_lowerCAmelCase  :				Optional[int]						=				logging.getLogger(__name__)

_lowerCAmelCase  :				List[str]						=				int(1_0_0_0_0)  # Hardcoded max length to avoid infinite loop

_lowerCAmelCase  :				Any						=				{
    "gpt2": (GPTaLMHeadModel, GPTaTokenizer),
    "ctrl": (CTRLLMHeadModel, CTRLTokenizer),
    "openai-gpt": (OpenAIGPTLMHeadModel, OpenAIGPTTokenizer),
    "xlnet": (XLNetLMHeadModel, XLNetTokenizer),
    "transfo-xl": (TransfoXLLMHeadModel, TransfoXLTokenizer),
    "xlm": (XLMWithLMHeadModel, XLMTokenizer),
    "gptj": (GPTJForCausalLM, AutoTokenizer),
    "bloom": (BloomForCausalLM, BloomTokenizerFast),
    "llama": (LlamaForCausalLM, LlamaTokenizer),
    "opt": (OPTForCausalLM, GPTaTokenizer),
}

# Padding text to help Transformer-XL and XLNet with short prompts as proposed by Aman Rusia
# in https://github.com/rusiaaman/XLNet-gen#methodology
# and https://medium.com/@amanrusia/xlnet-speaks-comparison-to-gpt-2-ea1a4e9ba39e
_lowerCAmelCase  :				List[Any]						=				"In 1991, the remains of Russian Tsar Nicholas II and his family\n(except for Alexei and Maria) are discovered.\nThe voice of Nicholas\'s young son, Tsarevich Alexei Nikolaevich, narrates the\nremainder of the story. 1883 Western Siberia,\na young Grigori Rasputin is asked by his father and a group of men to perform magic.\nRasputin has a vision and denounces one of the men as a horse thief. Although his\nfather initially slaps him for making such an accusation, Rasputin watches as the\nman is chased outside and beaten. Twenty years later, Rasputin sees a vision of\nthe Virgin Mary, prompting him to become a priest. Rasputin quickly becomes famous,\nwith people, even a bishop, begging for his blessing. <eod> </s> <eos>"



def   lowerCAmelCase						(						_lowerCAmelCase							:				Dict		):




 """simple docstring"""







 np.random.seed(args.seed		)
 torch.manual_seed(args.seed		)
 if args.n_gpu > 0:
  torch.cuda.manual_seed_all(args.seed		)



def   lowerCAmelCase						(						_lowerCAmelCase							:				Tuple  ,							_lowerCAmelCase							:				List[str]  ,							_lowerCAmelCase							:				List[Any]  ,							_lowerCAmelCase							:				Optional[int]		):




 """simple docstring"""







 if args.temperature > 0.7:
  logger.info("CTRL typically works better with lower temperatures (and lower top_k)."		)

 UpperCAmelCase__								=  tokenizer.encode(_lowerCAmelCase  ,							add_special_tokens=_lowerCAmelCase		)
 if not any(encoded_prompt[0] == x for x in tokenizer.control_codes.values()		):
  logger.info("WARNING! You are not starting your generation from a control code so you won\'t get good results"		)
 return prompt_text



def   lowerCAmelCase						(						_lowerCAmelCase							:				str  ,							_lowerCAmelCase							:				Optional[Any]  ,							_lowerCAmelCase							:				Tuple  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 UpperCAmelCase__								=  hasattr(model.config  ,							"use_lang_emb"		) and model.config.use_lang_emb
 if hasattr(model.config  ,							"lang2id"		) and use_lang_emb:
  UpperCAmelCase__								=  model.config.langaid.keys()
  if args.xlm_language in available_languages:
   UpperCAmelCase__								=  args.xlm_language
  else:
   UpperCAmelCase__								=  None
   while language not in available_languages:
    UpperCAmelCase__								=  input("Using XLM. Select language in " + str(list(_lowerCAmelCase		)		) + " >>> "		)

  UpperCAmelCase__								=  model.config.langaid[language]
  # kwargs["language"] = tokenizer.lang2id[language]

 # TODO fix mask_token_id setup when configurations will be synchronized between models and tokenizers
 # XLM masked-language modeling (MLM) models need masked token
 # is_xlm_mlm = "mlm" in args.model_name_or_path
 # if is_xlm_mlm:
 #     kwargs["mask_token_id"] = tokenizer.mask_token_id

 return prompt_text



def   lowerCAmelCase						(						_lowerCAmelCase							:				str  ,							_lowerCAmelCase							:				Tuple  ,							_lowerCAmelCase							:				Optional[int]  ,							_lowerCAmelCase							:				Any		):




 """simple docstring"""







 UpperCAmelCase__								=  args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
 UpperCAmelCase__								=  prefix + prompt_text
 return prompt_text



def   lowerCAmelCase						(						_lowerCAmelCase							:				str  ,							_lowerCAmelCase							:				Dict  ,							_lowerCAmelCase							:				int  ,							_lowerCAmelCase							:				Optional[Any]		):




 """simple docstring"""







 UpperCAmelCase__								=  args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
 UpperCAmelCase__								=  prefix + prompt_text
 return prompt_text


_lowerCAmelCase  :				List[Any]						=				{
    "ctrl": prepare_ctrl_input,
    "xlm": prepare_xlm_input,
    "xlnet": prepare_xlnet_input,
    "transfo-xl": prepare_transfoxl_input,
}



def   lowerCAmelCase						(						_lowerCAmelCase							:				Optional[Any]  ,							_lowerCAmelCase							:				Tuple		):




 """simple docstring"""







 if length < 0 and max_sequence_length > 0:
  UpperCAmelCase__								=  max_sequence_length
 elif 0 < max_sequence_length < length:
  UpperCAmelCase__								=  max_sequence_length  # No generation bigger than model size
 elif length < 0:
  UpperCAmelCase__								=  MAX_LENGTH  # avoid infinite loop
 return length



def   lowerCAmelCase						(						_lowerCAmelCase							:				str		):




 """simple docstring"""







 UpperCAmelCase__								=  None
 if hasattr(_lowerCAmelCase  ,							"hidden_size"		):
  UpperCAmelCase__								=  model_config.hidden_size
 elif hasattr(_lowerCAmelCase  ,							"n_embed"		):
  UpperCAmelCase__								=  model_config.n_embed
 elif hasattr(_lowerCAmelCase  ,							"n_embd"		):
  UpperCAmelCase__								=  model_config.n_embd

 UpperCAmelCase__								=  None
 if hasattr(_lowerCAmelCase  ,							"num_attention_heads"		):
  UpperCAmelCase__								=  model_config.num_attention_heads
 elif hasattr(_lowerCAmelCase  ,							"n_head"		):
  UpperCAmelCase__								=  model_config.n_head

 if embedding_size is None or num_head is None or num_head == 0:
  raise ValueError("Check the model config"		)

 UpperCAmelCase__								=  int(embedding_size / num_head		)
 if hasattr(_lowerCAmelCase  ,							"n_layer"		):
  UpperCAmelCase__								=  model_config.n_layer
 elif hasattr(_lowerCAmelCase  ,							"num_hidden_layers"		):
  UpperCAmelCase__								=  model_config.num_hidden_layers
 else:
  raise ValueError("Number of hidden layers couldn\'t be determined from the model config"		)

 return num_layer, num_head, num_embedding_size_per_head



def   lowerCAmelCase						(						_lowerCAmelCase							:				Optional[Any]  ,							_lowerCAmelCase							:				Tuple  ,							_lowerCAmelCase							:				int		):




 """simple docstring"""







 UpperCAmelCase__								=  sparse_model_config(model.config		)
 if model.config.model_type == "bloom":
  UpperCAmelCase__								=  tuple(
      (
          torch.empty(int(num_attention_heads * batch_size		)  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)
          .to(model.dtype		)
          .to(model.device		),
          torch.empty(int(num_attention_heads * batch_size		)  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)
          .to(model.dtype		)
          .to(model.device		),
      )
      for _ in range(_lowerCAmelCase		)		)
 else:
  UpperCAmelCase__								=  tuple(
      (
          torch.empty(_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)
          .to(model.dtype		)
          .to(model.device		),
          torch.empty(_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)
          .to(model.dtype		)
          .to(model.device		),
      )
      for _ in range(_lowerCAmelCase		)		)
 return past_key_values



def   lowerCAmelCase						(						_lowerCAmelCase							:				Optional[Any]  ,							_lowerCAmelCase							:				Optional[int]  ,							_lowerCAmelCase							:				str		):




 """simple docstring"""







 UpperCAmelCase__								=  len(_lowerCAmelCase		)
 UpperCAmelCase__								=  tokenizer.batch_encode_plus(_lowerCAmelCase  ,							return_tensors="pt"		)
 UpperCAmelCase__								=  dummy_input.to(model.device		)
 if model.config.use_cache:
  UpperCAmelCase__								=  generate_past_key_values(_lowerCAmelCase  ,							_lowerCAmelCase  ,							1		)
 UpperCAmelCase__								=  torch.cat(
     [
         torch.zeros(dummy_input["attention_mask"].shape[0]  ,							1		)
         .to(dummy_input["attention_mask"].dtype		)
         .to(model.device		),
         dummy_input["attention_mask"],
     ]  ,							-1  ,							)
 return dummy_input
class      _UpperCamelCase (			snake_case__						):
      UpperCAmelCase_            =						('_optimized', '_default')
      def __init__(     self				:Tuple	, lowerCamelCase				:Tuple	, lowerCamelCase				:int )       ->     Dict:
       UpperCAmelCase__								=  optimized
       UpperCAmelCase__								=  default
      def __call__(     self				:List[Any]	, *lowerCamelCase				:Optional[Any]	, **lowerCamelCase				:str )       ->     Tuple:
       if kwargs["past_key_values"] is None and self._default.config.use_cache:
        UpperCAmelCase__								=  generate_past_key_values(self._default	, kwargs["input_ids"].shape[0]	, 0 )
       kwargs.pop("position_ids"	, lowerCamelCase )
       for k in list(kwargs.keys() ):
        if kwargs[k] is None or isinstance(kwargs[k]	, lowerCamelCase ):
         kwargs.pop(lowerCamelCase )
       UpperCAmelCase__								=  self._optimized(**lowerCamelCase )
       UpperCAmelCase__								=  outputs[0]
       UpperCAmelCase__								=  outputs[1]
       UpperCAmelCase__								=  CausalLMOutputWithPast(
           loss=lowerCamelCase	, logits=lowerCamelCase	, past_key_values=lowerCamelCase	, hidden_states=lowerCamelCase	, attentions=lowerCamelCase	, )
       return fixed_output
      def __getattr__(     self				:List[Any]	, lowerCamelCase				:int )       ->     Any:
       return getattr(self._default	, lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Tuple	, lowerCamelCase				:str	, lowerCamelCase				:List[str]=None	, lowerCamelCase				:Dict=None	, lowerCamelCase				:str=None	, **lowerCamelCase				:List[str] )       ->     Tuple:
       return self._default.prepare_inputs_for_generation(
           lowerCamelCase	, past_key_values=lowerCamelCase	, inputs_embeds=lowerCamelCase	, use_cache=lowerCamelCase	, **lowerCamelCase )







      def 		UpperCAmelCase_  (     self				:List[Any]	, lowerCamelCase				:Tuple[Tuple[torch.Tensor]]	, lowerCamelCase				:torch.Tensor )       ->     Tuple[Tuple[torch.Tensor]]:
       return self._default._reorder_cache(lowerCamelCase	, lowerCamelCase )



def   lowerCAmelCase						(						):




 """simple docstring"""







 UpperCAmelCase__								=  argparse.ArgumentParser()
 parser.add_argument(
     "--model_type"  ,							default=_lowerCAmelCase  ,							type=_lowerCAmelCase  ,							required=_lowerCAmelCase  ,							help="Model type selected in the list: " + ", ".join(MODEL_CLASSES.keys()		)  ,							)
 parser.add_argument(
     "--model_name_or_path"  ,							default=_lowerCAmelCase  ,							type=_lowerCAmelCase  ,							required=_lowerCAmelCase  ,							help="Path to pre-trained model or shortcut name selected in the list: " + ", ".join(MODEL_CLASSES.keys()		)  ,							)

 parser.add_argument("--prompt"  ,							type=_lowerCAmelCase  ,							default=""		)
 parser.add_argument("--length"  ,							type=_lowerCAmelCase  ,							default=20		)
 parser.add_argument("--stop_token"  ,							type=_lowerCAmelCase  ,							default=_lowerCAmelCase  ,							help="Token at which text generation is stopped"		)

 parser.add_argument(
     "--temperature"  ,							type=_lowerCAmelCase  ,							default=1.0  ,							help="temperature of 1.0 has no effect, lower tend toward greedy sampling"  ,							)
 parser.add_argument(
     "--repetition_penalty"  ,							type=_lowerCAmelCase  ,							default=1.0  ,							help="primarily useful for CTRL model; in that case, use 1.2"		)
 parser.add_argument("--k"  ,							type=_lowerCAmelCase  ,							default=0		)
 parser.add_argument("--p"  ,							type=_lowerCAmelCase  ,							default=0.9		)

 parser.add_argument("--prefix"  ,							type=_lowerCAmelCase  ,							default=""  ,							help="Text added prior to input."		)
 parser.add_argument("--padding_text"  ,							type=_lowerCAmelCase  ,							default=""  ,							help="Deprecated, the use of `--prefix` is preferred."		)
 parser.add_argument("--xlm_language"  ,							type=_lowerCAmelCase  ,							default=""  ,							help="Optional language when used with the XLM model."		)

 parser.add_argument("--seed"  ,							type=_lowerCAmelCase  ,							default=42  ,							help="random seed for initialization"		)
 parser.add_argument("--no_cuda"  ,							action="store_true"  ,							help="Avoid using CUDA when available"		)
 parser.add_argument("--num_return_sequences"  ,							type=_lowerCAmelCase  ,							default=1  ,							help="The number of samples to generate."		)
 parser.add_argument(
     "--fp16"  ,							action="store_true"  ,							help="Whether to use 16-bit (mixed) precision (through NVIDIA apex) instead of 32-bit"  ,							)
 parser.add_argument("--jit"  ,							action="store_true"  ,							help="Whether or not to use jit trace to accelerate inference"		)
 UpperCAmelCase__								=  parser.parse_args()

 UpperCAmelCase__								=  torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"		)
 UpperCAmelCase__								=  0 if args.no_cuda else torch.cuda.device_count()

 logger.warning(F'''device: {args.device}, n_gpu: {args.n_gpu}, 16-bits training: {args.fpaa}'''		)

 set_seed(_lowerCAmelCase		)

 # Initialize the model and tokenizer
 try:
  UpperCAmelCase__								=  args.model_type.lower()
  UpperCAmelCase__								=  MODEL_CLASSES[args.model_type]
 except KeyError:
  raise KeyError("the model {} you specified is not supported. You are welcome to add it and open a PR :)"		)

 UpperCAmelCase__								=  tokenizer_class.from_pretrained(args.model_name_or_path		)
 if tokenizer.pad_token is None:
  UpperCAmelCase__								=  tokenizer.eos_token
 UpperCAmelCase__								=  model_class.from_pretrained(args.model_name_or_path		)
 model.to(args.device		)

 if args.fpaa:
  model.half()
 UpperCAmelCase__								=  getattr(model.config  ,							"max_position_embeddings"  ,							0		)
 UpperCAmelCase__								=  adjust_length_to_model(args.length  ,							max_sequence_length=_lowerCAmelCase		)
 logger.info(_lowerCAmelCase		)

 UpperCAmelCase__								=  args.prompt if args.prompt else input("Model prompt >>> "		)

 # Different models need different input formatting and/or extra arguments
 UpperCAmelCase__								=  args.model_type in PREPROCESSING_FUNCTIONS.keys()
 if requires_preprocessing:
  UpperCAmelCase__								=  PREPROCESSING_FUNCTIONS.get(args.model_type		)
  UpperCAmelCase__								=  prepare_input(_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)

  if model.__class__.__name__ in ["TransfoXLLMHeadModel"]:
   UpperCAmelCase__								=  {'add_space_before_punct_symbol': True}
  else:
   UpperCAmelCase__								=  {}

  UpperCAmelCase__								=  tokenizer.encode(
      _lowerCAmelCase  ,							add_special_tokens=_lowerCAmelCase  ,							return_tensors="pt"  ,							**_lowerCAmelCase		)
 else:
  UpperCAmelCase__								=  args.prefix if args.prefix else args.padding_text
  UpperCAmelCase__								=  tokenizer.encode(prefix + prompt_text  ,							add_special_tokens=_lowerCAmelCase  ,							return_tensors="pt"		)
 UpperCAmelCase__								=  encoded_prompt.to(args.device		)

 if encoded_prompt.size()[-1] == 0:
  UpperCAmelCase__								=  None
 else:
  UpperCAmelCase__								=  encoded_prompt

 if args.jit:
  UpperCAmelCase__								=  ['enable jit']
  UpperCAmelCase__								=  prepare_jit_inputs(_lowerCAmelCase  ,							_lowerCAmelCase  ,							_lowerCAmelCase		)
  torch._C._jit_set_texpr_fuser_enabled(_lowerCAmelCase		)
  UpperCAmelCase__								=  False
  if hasattr(_lowerCAmelCase  ,							"forward"		):
   UpperCAmelCase__								=  inspect.signature(model.forward		)
  else:
   UpperCAmelCase__								=  inspect.signature(model.__call__		)
  UpperCAmelCase__								=  tuple(jit_inputs[key] for key in sig.parameters if jit_inputs.get(_lowerCAmelCase  ,							_lowerCAmelCase		) is not None		)
  UpperCAmelCase__								=  torch.jit.trace(_lowerCAmelCase  ,							_lowerCAmelCase  ,							strict=_lowerCAmelCase		)
  UpperCAmelCase__								=  torch.jit.freeze(traced_model.eval()		)
  traced_model(*_lowerCAmelCase		)
  traced_model(*_lowerCAmelCase		)

  UpperCAmelCase__								=  _ModelFallbackWrapper(_lowerCAmelCase  ,							_lowerCAmelCase		)

 UpperCAmelCase__								=  model.generate(
     input_ids=_lowerCAmelCase  ,							max_length=args.length + len(encoded_prompt[0]		)  ,							temperature=args.temperature  ,							top_k=args.k  ,							top_p=args.p  ,							repetition_penalty=args.repetition_penalty  ,							do_sample=_lowerCAmelCase  ,							num_return_sequences=args.num_return_sequences  ,							)

 # Remove the batch dimension when returning multiple sequences
 if len(output_sequences.shape		) > 2:
  output_sequences.squeeze_()

 UpperCAmelCase__								=  []

 for generated_sequence_idx, generated_sequence in enumerate(_lowerCAmelCase		):
  print(F'''=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==='''		)
  UpperCAmelCase__								=  generated_sequence.tolist()

  # Decode text
  UpperCAmelCase__								=  tokenizer.decode(_lowerCAmelCase  ,							clean_up_tokenization_spaces=_lowerCAmelCase		)

  # Remove all text after the stop token
  UpperCAmelCase__								=  text[: text.find(args.stop_token		) if args.stop_token else None]

  # Add the prompt at the beginning of the sequence. Remove the excess text that was used for pre-processing
  UpperCAmelCase__								=  (
      prompt_text + text[len(tokenizer.decode(encoded_prompt[0]  ,							clean_up_tokenization_spaces=_lowerCAmelCase		)		) :]
  )

  generated_sequences.append(_lowerCAmelCase		)
  print(_lowerCAmelCase		)

 return generated_sequences


if __name__ == "__main__":
  main()











import unittest

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

from ...test_configuration_common import ConfigTester
from ...test_modeling_common import ModelTesterMixin, floats_tensor, ids_tensor, random_attention_mask
from ...test_pipeline_mixin import PipelineTesterMixin


if is_torch_available():
  import torch

  from transformers import (
      YosoForMaskedLM,
      YosoForMultipleChoice,
      YosoForQuestionAnswering,
      YosoForSequenceClassification,
      YosoForTokenClassification,
      YosoModel,
  )
  from transformers.models.yoso.modeling_yoso import YOSO_PRETRAINED_MODEL_ARCHIVE_LIST
class      _UpperCamelCase :
      def __init__(     self				:int	, lowerCamelCase				:int	, lowerCamelCase				:Optional[Any]=13	, lowerCamelCase				:Optional[Any]=7	, lowerCamelCase				:Union[str, Any]=True	, lowerCamelCase				:Tuple=True	, lowerCamelCase				:Optional[Any]=True	, lowerCamelCase				:str=True	, lowerCamelCase				:Any=99	, lowerCamelCase				:Optional[int]=32	, lowerCamelCase				:Any=5	, lowerCamelCase				:List[Any]=4	, lowerCamelCase				:Optional[Any]=37	, lowerCamelCase				:Tuple="gelu"	, lowerCamelCase				:Optional[int]=0.1	, lowerCamelCase				:Any=0.1	, lowerCamelCase				:List[Any]=512	, lowerCamelCase				:Tuple=16	, lowerCamelCase				:Optional[int]=2	, lowerCamelCase				:str=0.02	, lowerCamelCase				:Dict=3	, lowerCamelCase				:Union[str, Any]=4	, lowerCamelCase				:Union[str, Any]=None	, )       ->     List[Any]:
       UpperCAmelCase__								=  parent
       UpperCAmelCase__								=  batch_size
       UpperCAmelCase__								=  seq_length
       UpperCAmelCase__								=  is_training
       UpperCAmelCase__								=  use_input_mask
       UpperCAmelCase__								=  use_token_type_ids
       UpperCAmelCase__								=  use_labels
       UpperCAmelCase__								=  vocab_size
       UpperCAmelCase__								=  hidden_size
       UpperCAmelCase__								=  num_hidden_layers
       UpperCAmelCase__								=  num_attention_heads
       UpperCAmelCase__								=  intermediate_size
       UpperCAmelCase__								=  hidden_act
       UpperCAmelCase__								=  hidden_dropout_prob
       UpperCAmelCase__								=  attention_probs_dropout_prob
       UpperCAmelCase__								=  max_position_embeddings
       UpperCAmelCase__								=  type_vocab_size
       UpperCAmelCase__								=  type_sequence_label_size
       UpperCAmelCase__								=  initializer_range
       UpperCAmelCase__								=  num_labels
       UpperCAmelCase__								=  num_choices
       UpperCAmelCase__								=  scope
      def 		UpperCAmelCase_  (     self				:Union[str, Any] )       ->     Any:
       UpperCAmelCase__								=  ids_tensor([self.batch_size, self.seq_length]	, self.vocab_size )

       UpperCAmelCase__								=  None
       if self.use_input_mask:
        UpperCAmelCase__								=  random_attention_mask([self.batch_size, self.seq_length] )

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

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

       UpperCAmelCase__								=  self.get_config()

       return config, input_ids, token_type_ids, input_mask, sequence_labels, token_labels, choice_labels
      def 		UpperCAmelCase_  (     self				:List[Any] )       ->     Optional[Any]:
       return YosoConfig(
           vocab_size=self.vocab_size	, hidden_size=self.hidden_size	, num_hidden_layers=self.num_hidden_layers	, num_attention_heads=self.num_attention_heads	, intermediate_size=self.intermediate_size	, hidden_act=self.hidden_act	, hidden_dropout_prob=self.hidden_dropout_prob	, attention_probs_dropout_prob=self.attention_probs_dropout_prob	, max_position_embeddings=self.max_position_embeddings	, type_vocab_size=self.type_vocab_size	, is_decoder=lowerCamelCase	, initializer_range=self.initializer_range	, )
      def 		UpperCAmelCase_  (     self				:int )       ->     Any:
       UpperCAmelCase__								=  self.get_config()
       UpperCAmelCase__								=  300
       return config
      def 		UpperCAmelCase_  (     self				:List[str] )       ->     Tuple:
       (
           (
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	
       )								=  self.prepare_config_and_inputs()

       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  floats_tensor([self.batch_size, self.seq_length, self.hidden_size] )
       UpperCAmelCase__								=  ids_tensor([self.batch_size, self.seq_length]	, vocab_size=2 )

       return (
           config,
           input_ids,
           token_type_ids,
           input_mask,
           sequence_labels,
           token_labels,
           choice_labels,
           encoder_hidden_states,
           encoder_attention_mask,
       )
      def 		UpperCAmelCase_  (     self				:Any	, lowerCamelCase				:List[str]	, lowerCamelCase				:List[str]	, lowerCamelCase				:str	, lowerCamelCase				:Union[str, Any]	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:Any	, lowerCamelCase				:Tuple )       ->     List[Any]:
       UpperCAmelCase__								=  YosoModel(config=lowerCamelCase )
       model.to(lowerCamelCase )
       model.eval()
       UpperCAmelCase__								=  model(lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase )
       UpperCAmelCase__								=  model(lowerCamelCase	, token_type_ids=lowerCamelCase )
       UpperCAmelCase__								=  model(lowerCamelCase )
       self.parent.assertEqual(result.last_hidden_state.shape	, (self.batch_size, self.seq_length, self.hidden_size) )
      def 		UpperCAmelCase_  (     self				:Any	, lowerCamelCase				:str	, lowerCamelCase				:Dict	, lowerCamelCase				:Any	, lowerCamelCase				:Any	, lowerCamelCase				:int	, lowerCamelCase				:Dict	, lowerCamelCase				:Any	, lowerCamelCase				:Union[str, Any]	, lowerCamelCase				:List[Any]	, )       ->     Optional[int]:
       UpperCAmelCase__								=  True
       UpperCAmelCase__								=  YosoModel(lowerCamelCase )
       model.to(lowerCamelCase )
       model.eval()
       UpperCAmelCase__								=  model(
           lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase	, encoder_hidden_states=lowerCamelCase	, encoder_attention_mask=lowerCamelCase	, )
       UpperCAmelCase__								=  model(
           lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase	, encoder_hidden_states=lowerCamelCase	, )
       UpperCAmelCase__								=  model(lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase )
       self.parent.assertEqual(result.last_hidden_state.shape	, (self.batch_size, self.seq_length, self.hidden_size) )
      def 		UpperCAmelCase_  (     self				:Tuple	, lowerCamelCase				:List[Any]	, lowerCamelCase				:Tuple	, lowerCamelCase				:List[str]	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:Tuple	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:int )       ->     Optional[int]:
       UpperCAmelCase__								=  YosoForMaskedLM(config=lowerCamelCase )
       model.to(lowerCamelCase )
       model.eval()
       UpperCAmelCase__								=  model(lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase	, labels=lowerCamelCase )
       self.parent.assertEqual(result.logits.shape	, (self.batch_size, self.seq_length, self.vocab_size) )
      def 		UpperCAmelCase_  (     self				:Dict	, lowerCamelCase				:str	, lowerCamelCase				:Dict	, lowerCamelCase				:List[Any]	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:Union[str, Any]	, lowerCamelCase				:int	, lowerCamelCase				:Optional[Any] )       ->     Any:
       UpperCAmelCase__								=  YosoForQuestionAnswering(config=lowerCamelCase )
       model.to(lowerCamelCase )
       model.eval()
       UpperCAmelCase__								=  model(
           lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase	, start_positions=lowerCamelCase	, end_positions=lowerCamelCase	, )
       self.parent.assertEqual(result.start_logits.shape	, (self.batch_size, self.seq_length) )
       self.parent.assertEqual(result.end_logits.shape	, (self.batch_size, self.seq_length) )
      def 		UpperCAmelCase_  (     self				:Optional[Any]	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:Any	, lowerCamelCase				:List[str]	, lowerCamelCase				:Dict	, lowerCamelCase				:str	, lowerCamelCase				:Tuple	, lowerCamelCase				:int )       ->     Dict:
       UpperCAmelCase__								=  self.num_labels
       UpperCAmelCase__								=  YosoForSequenceClassification(lowerCamelCase )
       model.to(lowerCamelCase )
       model.eval()
       UpperCAmelCase__								=  model(lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase	, labels=lowerCamelCase )
       self.parent.assertEqual(result.logits.shape	, (self.batch_size, self.num_labels) )
      def 		UpperCAmelCase_  (     self				:Tuple	, lowerCamelCase				:str	, lowerCamelCase				:int	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:List[str]	, lowerCamelCase				:Dict	, lowerCamelCase				:Optional[int]	, lowerCamelCase				:str )       ->     Dict:
       UpperCAmelCase__								=  self.num_labels
       UpperCAmelCase__								=  YosoForTokenClassification(config=lowerCamelCase )
       model.to(lowerCamelCase )
       model.eval()
       UpperCAmelCase__								=  model(lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase	, labels=lowerCamelCase )
       self.parent.assertEqual(result.logits.shape	, (self.batch_size, self.seq_length, self.num_labels) )
      def 		UpperCAmelCase_  (     self				:Optional[int]	, lowerCamelCase				:Tuple	, lowerCamelCase				:Tuple	, lowerCamelCase				:int	, lowerCamelCase				:Tuple	, lowerCamelCase				:List[str]	, lowerCamelCase				:Optional[Any]	, lowerCamelCase				:List[str] )       ->     List[Any]:
       UpperCAmelCase__								=  self.num_choices
       UpperCAmelCase__								=  YosoForMultipleChoice(config=lowerCamelCase )
       model.to(lowerCamelCase )
       model.eval()
       UpperCAmelCase__								=  input_ids.unsqueeze(1 ).expand(-1	, self.num_choices	, -1 ).contiguous()
       UpperCAmelCase__								=  token_type_ids.unsqueeze(1 ).expand(-1	, self.num_choices	, -1 ).contiguous()
       UpperCAmelCase__								=  input_mask.unsqueeze(1 ).expand(-1	, self.num_choices	, -1 ).contiguous()
       UpperCAmelCase__								=  model(
           lowerCamelCase	, attention_mask=lowerCamelCase	, token_type_ids=lowerCamelCase	, labels=lowerCamelCase	, )
       self.parent.assertEqual(result.logits.shape	, (self.batch_size, self.num_choices) )







      def 		UpperCAmelCase_  (     self				:int )       ->     List[Any]:
       UpperCAmelCase__								=  self.prepare_config_and_inputs()
       (
           (
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	(
           UpperCAmelCase__
       )	,	
       )								=  config_and_inputs
       UpperCAmelCase__								=  {"input_ids": input_ids, "token_type_ids": token_type_ids, "attention_mask": input_mask}
       return config, inputs_dict



@require_torch
class      _UpperCamelCase (			lowerCAmelCase		,    lowerCAmelCase		,    unittest.TestCase						):
      UpperCAmelCase_            =						(
          (
              YosoModel,
              YosoForMaskedLM,
              YosoForMultipleChoice,
              YosoForQuestionAnswering,
              YosoForSequenceClassification,
              YosoForTokenClassification,
          )
          if is_torch_available()
          else ()
      )
      UpperCAmelCase_            =						False
      UpperCAmelCase_            =						False
      UpperCAmelCase_            =						False

      UpperCAmelCase_            =						()
      UpperCAmelCase_            =						(
          {
              """feature-extraction""": YosoModel,
              """fill-mask""": YosoForMaskedLM,
              """question-answering""": YosoForQuestionAnswering,
              """text-classification""": YosoForSequenceClassification,
              """token-classification""": YosoForTokenClassification,
              """zero-shot""": YosoForSequenceClassification,
          }
          if is_torch_available()
          else {}
      )
      def 		UpperCAmelCase_  (     self				:Any )       ->     Optional[Any]:
       UpperCAmelCase__								=  YosoModelTester(self )
       UpperCAmelCase__								=  ConfigTester(self	, config_class=lowerCamelCase	, hidden_size=37 )
      def 		UpperCAmelCase_  (     self				:List[Any] )       ->     List[str]:
       self.config_tester.run_common_tests()
      def 		UpperCAmelCase_  (     self				:Optional[int] )       ->     List[Any]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Tuple )       ->     Optional[Any]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       for type in ["absolute", "relative_key", "relative_key_query"]:
        UpperCAmelCase__								=  type
        self.model_tester.create_and_check_model(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Tuple )       ->     Optional[int]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_masked_lm(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Union[str, Any] )       ->     Dict:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_multiple_choice(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:str )       ->     Optional[Any]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Any )       ->     List[str]:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase )
      def 		UpperCAmelCase_  (     self				:Any )       ->     str:
       UpperCAmelCase__								=  self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*lowerCamelCase )
      @slow
      def 		UpperCAmelCase_  (     self				:List[Any] )       ->     Optional[int]:
       for model_name in YOSO_PRETRAINED_MODEL_ARCHIVE_LIST[:1]:
        UpperCAmelCase__								=  YosoModel.from_pretrained(lowerCamelCase )
        self.assertIsNotNone(lowerCamelCase )







      def 		UpperCAmelCase_  (     self				:int )       ->     List[str]:
       return



@require_torch
class      _UpperCamelCase (			unittest.TestCase						):
      @slow
      def 		UpperCAmelCase_  (     self				:Optional[Any] )       ->     Optional[int]:
       UpperCAmelCase__								=  YosoModel.from_pretrained("uw-madison/yoso-4096" )
       UpperCAmelCase__								=  torch.tensor([[0, 1, 2, 3, 4, 5]] )

       with torch.no_grad():
        UpperCAmelCase__								=  model(lowerCamelCase )[0]

       UpperCAmelCase__								=  torch.Size((1, 6, 768) )
       self.assertEqual(output.shape	, lowerCamelCase )

       UpperCAmelCase__								=  torch.tensor(
           [[[-0.06_11, 0.12_42, 0.08_40], [0.02_80, -0.00_48, 0.11_25], [0.01_06, 0.02_26, 0.07_51]]] )

       self.assertTrue(torch.allclose(output[:, :3, :3]	, lowerCamelCase	, atol=1e-4 ) )
      @slow
      def 		UpperCAmelCase_  (     self				:Optional[Any] )       ->     List[Any]:
       UpperCAmelCase__								=  YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096" )
       UpperCAmelCase__								=  torch.tensor([[0, 1, 2, 3, 4, 5]] )

       with torch.no_grad():
        UpperCAmelCase__								=  model(lowerCamelCase )[0]

       UpperCAmelCase__								=  5_0265

       UpperCAmelCase__								=  torch.Size((1, 6, vocab_size) )
       self.assertEqual(output.shape	, lowerCamelCase )

       UpperCAmelCase__								=  torch.tensor(
           [[[-2.13_13, -3.72_85, -2.24_07], [-2.70_47, -3.33_14, -2.64_08], [0.06_29, -2.51_66, -0.33_56]]] )

       self.assertTrue(torch.allclose(output[:, :3, :3]	, lowerCamelCase	, atol=1e-4 ) )







      @slow
      def 		UpperCAmelCase_  (     self				:Any )       ->     str:
       UpperCAmelCase__								=  YosoForMaskedLM.from_pretrained("uw-madison/yoso-4096" )
       UpperCAmelCase__								=  torch.arange(4096 ).unsqueeze(0 )

       with torch.no_grad():
        UpperCAmelCase__								=  model(lowerCamelCase )[0]

       UpperCAmelCase__								=  5_0265

       UpperCAmelCase__								=  torch.Size((1, 4096, vocab_size) )
       self.assertEqual(output.shape	, lowerCamelCase )

       UpperCAmelCase__								=  torch.tensor(
           [[[-2.39_14, -4.37_42, -5.09_56], [-4.09_88, -4.23_84, -7.04_06], [-3.14_27, -3.71_92, -6.68_00]]] )

       self.assertTrue(torch.allclose(output[:, :3, :3]	, lowerCamelCase	, atol=1e-4 ) )





