
"""simple docstring"""




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,
)
A__   :						Tuple 							=     logging.getLogger(__name__)

A__   :						List[str] 							=     int(10_000)  # Hardcoded max length to avoid infinite loop

A__   :						Dict 							=     {
    """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
A__   :						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 				a__			(					lowerCAmelCase						:							int		):






     '''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 				a__			(					lowerCAmelCase						:							Any							,     lowerCAmelCase						:							Dict							,     lowerCAmelCase						:							Optional[Any]							,     lowerCAmelCase						:							List[Any]		):






     '''simple docstring'''







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

     UpperCAmelCase__				:			List[Any]							=    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 				a__			(					lowerCAmelCase						:							int							,     lowerCAmelCase						:							Union[str, Any]							,     lowerCAmelCase						:							List[str]							,     lowerCAmelCase						:							Any		):






     '''simple docstring'''
     UpperCAmelCase__				:			int							=    hasattr(model.config							,     "use_lang_emb"		) and model.config.use_lang_emb
     if hasattr(model.config							,     "lang2id"		) and use_lang_emb:
          UpperCAmelCase__				:			Union[str, Any]							=    model.config.langaid.keys()
          if args.xlm_language in available_languages:
               UpperCAmelCase__				:			Union[str, Any]							=    args.xlm_language
          else:
               UpperCAmelCase__				:			Optional[int]							=    None
               while language not in available_languages:
                    UpperCAmelCase__				:			Tuple							=    input("Using XLM. Select language in " + str(list(lowerCAmelCase__		)		) + " >>> "		)

          UpperCAmelCase__				:			Tuple							=    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 				a__			(					lowerCAmelCase						:							Dict							,     lowerCAmelCase						:							Optional[int]							,     lowerCAmelCase						:							List[str]							,     lowerCAmelCase						:							Tuple		):






     '''simple docstring'''
     UpperCAmelCase__				:			Union[str, Any]							=    args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     UpperCAmelCase__				:			Optional[int]							=    prefix + prompt_text
     return prompt_text



def 				a__			(					lowerCAmelCase						:							List[str]							,     lowerCAmelCase						:							Union[str, Any]							,     lowerCAmelCase						:							List[Any]							,     lowerCAmelCase						:							Optional[int]		):






     '''simple docstring'''
     UpperCAmelCase__				:			List[Any]							=    args.prefix if args.prefix else args.padding_text if args.padding_text else PREFIX
     UpperCAmelCase__				:			List[str]							=    prefix + prompt_text
     return prompt_text


A__   :						int 							=     {
    """ctrl""": prepare_ctrl_input,
    """xlm""": prepare_xlm_input,
    """xlnet""": prepare_xlnet_input,
    """transfo-xl""": prepare_transfoxl_input,
}



def 				a__			(					lowerCAmelCase						:							Any							,     lowerCAmelCase						:							Union[str, Any]		):






     '''simple docstring'''







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



def 				a__			(					lowerCAmelCase						:							Dict		):






     '''simple docstring'''
     UpperCAmelCase__				:			Optional[int]							=    None
     if hasattr(lowerCAmelCase__							,     "hidden_size"		):
          UpperCAmelCase__				:			str							=    model_config.hidden_size
     elif hasattr(lowerCAmelCase__							,     "n_embed"		):
          UpperCAmelCase__				:			int							=    model_config.n_embed
     elif hasattr(lowerCAmelCase__							,     "n_embd"		):
          UpperCAmelCase__				:			Union[str, Any]							=    model_config.n_embd

     UpperCAmelCase__				:			List[Any]							=    None
     if hasattr(lowerCAmelCase__							,     "num_attention_heads"		):
          UpperCAmelCase__				:			Optional[int]							=    model_config.num_attention_heads
     elif hasattr(lowerCAmelCase__							,     "n_head"		):
          UpperCAmelCase__				:			List[str]							=    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__				:			Tuple							=    int(embedding_size / num_head		)
     if hasattr(lowerCAmelCase__							,     "n_layer"		):
          UpperCAmelCase__				:			int							=    model_config.n_layer
     elif hasattr(lowerCAmelCase__							,     "num_hidden_layers"		):
          UpperCAmelCase__				:			Optional[Any]							=    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 				a__			(					lowerCAmelCase						:							Tuple							,     lowerCAmelCase						:							str							,     lowerCAmelCase						:							str		):






     '''simple docstring'''
     UpperCAmelCase__				:			Any							=    sparse_model_config(model.config		)
     if model.config.model_type == "bloom":
          UpperCAmelCase__				:			int							=    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__				:			Optional[Any]							=    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 				a__			(					lowerCAmelCase						:							List[str]							,     lowerCAmelCase						:							str							,     lowerCAmelCase						:							Any		):






     '''simple docstring'''
     UpperCAmelCase__				:			int							=    len(lowerCAmelCase__		)
     UpperCAmelCase__				:			str							=    tokenizer.batch_encode_plus(lowerCAmelCase__							,     return_tensors="pt"		)
     UpperCAmelCase__				:			Any							=    dummy_input.to(model.device		)
     if model.config.use_cache:
          UpperCAmelCase__				:			Optional[Any]							=    generate_past_key_values(lowerCAmelCase__							,     lowerCAmelCase__							,     1		)
     UpperCAmelCase__				:			Dict							=    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 	_lowercase    (							__A					):


     '''simple docstring'''





     _A		    =				("""_optimized""", """_default""")



     def __init__(   self			,      __UpperCamelCase			,      __UpperCamelCase	)->       Union[str, Any]:
          UpperCAmelCase__				:			str							=    optimized
          UpperCAmelCase__				:			Union[str, Any]							=    default



     def __call__(   self			,      *__UpperCamelCase			,      **__UpperCamelCase	)->       List[str]:
          if kwargs["past_key_values"] is None and self._default.config.use_cache:
               UpperCAmelCase__				:			List[Any]							=    generate_past_key_values(self._default			,      kwargs["input_ids"].shape[0]			,      0	)
          kwargs.pop("position_ids"			,      UpperCamelCase__	)
          for k in list(kwargs.keys()	):
               if kwargs[k] is None or isinstance(kwargs[k]			,      UpperCamelCase__	):
                    kwargs.pop(UpperCamelCase__	)
          UpperCAmelCase__				:			Union[str, Any]							=    self._optimized(**UpperCamelCase__	)
          UpperCAmelCase__				:			int							=    outputs[0]
          UpperCAmelCase__				:			str							=    outputs[1]
          UpperCAmelCase__				:			str							=    CausalLMOutputWithPast(
              loss=UpperCamelCase__			,      logits=UpperCamelCase__			,      past_key_values=UpperCamelCase__			,      hidden_states=UpperCamelCase__			,      attentions=UpperCamelCase__			,      )
          return fixed_output



     def __getattr__(   self			,      __UpperCamelCase	)->       Union[str, Any]:
          return getattr(self._default			,      UpperCamelCase__	)



     def 			lowerCAmelCase__							(   self			,      __UpperCamelCase			,      __UpperCamelCase=None			,      __UpperCamelCase=None			,      __UpperCamelCase=None			,      **__UpperCamelCase	)->       Optional[int]:
          return self._default.prepare_inputs_for_generation(
              UpperCamelCase__			,      past_key_values=UpperCamelCase__			,      inputs_embeds=UpperCamelCase__			,      use_cache=UpperCamelCase__			,      **UpperCamelCase__	)



     def 			lowerCAmelCase__							(   self			,      __UpperCamelCase			,      __UpperCamelCase	)->       List[Any]:
          return self._default._reorder_cache(UpperCamelCase__			,      UpperCamelCase__	)





def 				a__			(					):






     '''simple docstring'''
     UpperCAmelCase__				:			Union[str, Any]							=    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__				:			Dict							=    parser.parse_args()

     UpperCAmelCase__				:			Any							=    torch.device("cuda" if torch.cuda.is_available() and not args.no_cuda else "cpu"		)
     UpperCAmelCase__				:			Tuple							=    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__				:			int							=    args.model_type.lower()
          UpperCAmelCase__				:			str							=    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__				:			Optional[int]							=    tokenizer_class.from_pretrained(args.model_name_or_path		)
     if tokenizer.pad_token is None:
          UpperCAmelCase__				:			Optional[int]							=    tokenizer.eos_token
     UpperCAmelCase__				:			List[Any]							=    model_class.from_pretrained(args.model_name_or_path		)
     model.to(args.device		)

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

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

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

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

          UpperCAmelCase__				:			Dict							=    tokenizer.encode(
              lowerCAmelCase__							,     add_special_tokens=lowerCAmelCase__							,     return_tensors="pt"							,     **lowerCAmelCase__		)
     else:
          UpperCAmelCase__				:			List[str]							=    args.prefix if args.prefix else args.padding_text
          UpperCAmelCase__				:			str							=    tokenizer.encode(prefix + prompt_text							,     add_special_tokens=lowerCAmelCase__							,     return_tensors="pt"		)
     UpperCAmelCase__				:			Optional[int]							=    encoded_prompt.to(args.device		)

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

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

          UpperCAmelCase__				:			Dict							=    _ModelFallbackWrapper(lowerCAmelCase__							,     lowerCAmelCase__		)

     UpperCAmelCase__				:			Dict							=    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__				:			List[str]							=    []

     for generated_sequence_idx, generated_sequence in enumerate(lowerCAmelCase__		):
          print(F"=== GENERATED SEQUENCE {generated_sequence_idx + 1} ==="		)
          UpperCAmelCase__				:			List[Any]							=    generated_sequence.tolist()

          # Decode text
          UpperCAmelCase__				:			Optional[Any]							=    tokenizer.decode(lowerCAmelCase__							,     clean_up_tokenization_spaces=lowerCAmelCase__		)

          # Remove all text after the stop token
          UpperCAmelCase__				:			Optional[int]							=    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__				:			List[str]							=    (
              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 MarkupLMConfig, is_torch_available
from transformers.testing_utils import require_torch, slow, torch_device
from transformers.utils import cached_property

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 (
				    MarkupLMForQuestionAnswering,
				    MarkupLMForSequenceClassification,
				    MarkupLMForTokenClassification,
				    MarkupLMModel,
				)

# TODO check dependencies
from transformers import MarkupLMFeatureExtractor, MarkupLMProcessor, MarkupLMTokenizer


class 				__a				:





		'''simple docstring'''



		def __init__(    self			,     UpperCamelCase__			,     UpperCamelCase__=13			,     UpperCamelCase__=7			,     UpperCamelCase__=True			,     UpperCamelCase__=True			,     UpperCamelCase__=True			,     UpperCamelCase__=True			,     UpperCamelCase__=99			,     UpperCamelCase__=32			,     UpperCamelCase__=5			,     UpperCamelCase__=4			,     UpperCamelCase__=37			,     UpperCamelCase__="gelu"			,     UpperCamelCase__=0.1			,     UpperCamelCase__=0.1			,     UpperCamelCase__=512			,     UpperCamelCase__=16			,     UpperCamelCase__=2			,     UpperCamelCase__=0.02			,     UpperCamelCase__=3			,     UpperCamelCase__=None			,     UpperCamelCase__=20			,     UpperCamelCase__=30			,     UpperCamelCase__=2			,     UpperCamelCase__=2			,     UpperCamelCase__=10			,     ):
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= parent
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= batch_size
						SCREAMING_SNAKE_CASE_ :						int    				= seq_length
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= is_training
						SCREAMING_SNAKE_CASE_ :						Dict    				= use_input_mask
						SCREAMING_SNAKE_CASE_ :						Dict    				= use_token_type_ids
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= use_labels
						SCREAMING_SNAKE_CASE_ :						int    				= vocab_size
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= hidden_size
						SCREAMING_SNAKE_CASE_ :						Any    				= num_hidden_layers
						SCREAMING_SNAKE_CASE_ :						int    				= num_attention_heads
						SCREAMING_SNAKE_CASE_ :						Any    				= intermediate_size
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= hidden_act
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= hidden_dropout_prob
						SCREAMING_SNAKE_CASE_ :						List[str]    				= attention_probs_dropout_prob
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= max_position_embeddings
						SCREAMING_SNAKE_CASE_ :						Tuple    				= type_vocab_size
						SCREAMING_SNAKE_CASE_ :						str    				= type_sequence_label_size
						SCREAMING_SNAKE_CASE_ :						Dict    				= initializer_range
						SCREAMING_SNAKE_CASE_ :						int    				= num_labels
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= scope
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= max_xpath_tag_unit_embeddings
						SCREAMING_SNAKE_CASE_ :						Tuple    				= max_xpath_subs_unit_embeddings
						SCREAMING_SNAKE_CASE_ :						Dict    				= tag_pad_id
						SCREAMING_SNAKE_CASE_ :						str    				= subs_pad_id
						SCREAMING_SNAKE_CASE_ :						Tuple    				= max_depth


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= ids_tensor([self.batch_size, self.seq_length]			,     self.vocab_size							)

						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= ids_tensor(
						    [self.batch_size, self.seq_length, self.max_depth]			,     self.max_xpath_tag_unit_embeddings							)

						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= ids_tensor(
						    [self.batch_size, self.seq_length, self.max_depth]			,     self.max_xpath_subs_unit_embeddings							)

						SCREAMING_SNAKE_CASE_ :						Any    				= None
						if self.use_input_mask:
										SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= ids_tensor([self.batch_size, self.seq_length]			,     vocab_size=2							)

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

						SCREAMING_SNAKE_CASE_ :						int    				= None
						SCREAMING_SNAKE_CASE_ :						Tuple    				= None
						if self.use_labels:
										SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= ids_tensor([self.batch_size]			,     self.type_sequence_label_size							)
										SCREAMING_SNAKE_CASE_ :						Any    				= ids_tensor([self.batch_size, self.seq_length]			,     self.num_labels							)

						SCREAMING_SNAKE_CASE_ :						Tuple    				= self.get_config()

						return (
						    config,
						    input_ids,
						    xpath_tags_seq,
						    xpath_subs_seq,
						    token_type_ids,
						    input_mask,
						    sequence_labels,
						    token_labels,
						)


		def 	__snake_case      (    self							):
						return MarkupLMConfig(
						    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			,     initializer_range=self.initializer_range			,     max_xpath_tag_unit_embeddings=self.max_xpath_tag_unit_embeddings			,     max_xpath_subs_unit_embeddings=self.max_xpath_subs_unit_embeddings			,     tag_pad_id=self.tag_pad_id			,     subs_pad_id=self.subs_pad_id			,     max_depth=self.max_depth			,     )


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     ):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= MarkupLMModel(config=UpperCamelCase__							)
						model.to(UpperCamelCase__							)
						model.eval()
						print('Configs:'			,     model.config.tag_pad_id			,     model.config.subs_pad_id							)
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= model(UpperCamelCase__			,     attention_mask=UpperCamelCase__			,     token_type_ids=UpperCamelCase__							)
						SCREAMING_SNAKE_CASE_ :						List[str]    				= model(UpperCamelCase__			,     token_type_ids=UpperCamelCase__							)
						SCREAMING_SNAKE_CASE_ :						int    				= model(UpperCamelCase__							)
						self.parent.assertEqual(result.last_hidden_state.shape			,     (self.batch_size, self.seq_length, self.hidden_size)							)
						self.parent.assertEqual(result.pooler_output.shape			,     (self.batch_size, self.hidden_size)							)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     ):
						SCREAMING_SNAKE_CASE_ :						Dict    				= self.num_labels
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= MarkupLMForSequenceClassification(UpperCamelCase__							)
						model.to(UpperCamelCase__							)
						model.eval()
						SCREAMING_SNAKE_CASE_ :						str    				= model(
						    UpperCamelCase__			,     xpath_tags_seq=UpperCamelCase__			,     xpath_subs_seq=UpperCamelCase__			,     attention_mask=UpperCamelCase__			,     token_type_ids=UpperCamelCase__			,     labels=UpperCamelCase__			,     )
						self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.num_labels)							)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     ):
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= self.num_labels
						SCREAMING_SNAKE_CASE_ :						List[str]    				= MarkupLMForTokenClassification(config=UpperCamelCase__							)
						model.to(UpperCamelCase__							)
						model.eval()
						SCREAMING_SNAKE_CASE_ :						str    				= model(
						    UpperCamelCase__			,     xpath_tags_seq=UpperCamelCase__			,     xpath_subs_seq=UpperCamelCase__			,     attention_mask=UpperCamelCase__			,     token_type_ids=UpperCamelCase__			,     labels=UpperCamelCase__			,     )
						self.parent.assertEqual(result.logits.shape			,     (self.batch_size, self.seq_length, self.num_labels)							)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     ):
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= MarkupLMForQuestionAnswering(config=UpperCamelCase__							)
						model.to(UpperCamelCase__							)
						model.eval()
						SCREAMING_SNAKE_CASE_ :						int    				= model(
						    UpperCamelCase__			,     xpath_tags_seq=UpperCamelCase__			,     xpath_subs_seq=UpperCamelCase__			,     attention_mask=UpperCamelCase__			,     token_type_ids=UpperCamelCase__			,     start_positions=UpperCamelCase__			,     end_positions=UpperCamelCase__			,     )
						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 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Any    				= self.prepare_config_and_inputs()
						(
						    (
						    SCREAMING_SNAKE_CASE_
						)				,							(
						    SCREAMING_SNAKE_CASE_
						)				,							(
						    SCREAMING_SNAKE_CASE_
						)				,							(
						    SCREAMING_SNAKE_CASE_
						)				,							(
						    SCREAMING_SNAKE_CASE_
						)				,							(
						    SCREAMING_SNAKE_CASE_
						)				,							(
						    SCREAMING_SNAKE_CASE_
						)				,							(
						    SCREAMING_SNAKE_CASE_
						)				,							
						) :						int    				= config_and_inputs
						SCREAMING_SNAKE_CASE_ :						Any    				= {
						    'input_ids': input_ids,
						    'xpath_tags_seq': xpath_tags_seq,
						    'xpath_subs_seq': xpath_subs_seq,
						    'token_type_ids': token_type_ids,
						    'attention_mask': input_mask,
						}
						return config, inputs_dict






@require_torch
class 				__a				(	__A			,						__A			,						unittest.TestCase    ):





		'''simple docstring'''



		UpperCAmelCase__   :					Dict					     =    (
		    (
		        MarkupLMModel,
		        MarkupLMForSequenceClassification,
		        MarkupLMForTokenClassification,
		        MarkupLMForQuestionAnswering,
		    )
		    if is_torch_available()
		    else None
		)
		UpperCAmelCase__   :					Union[str, Any]					     =    (
		    {
		        """feature-extraction""": MarkupLMModel,
		        """question-answering""": MarkupLMForQuestionAnswering,
		        """text-classification""": MarkupLMForSequenceClassification,
		        """token-classification""": MarkupLMForTokenClassification,
		        """zero-shot""": MarkupLMForSequenceClassification,
		    }
		    if is_torch_available()
		    else {}
		)


		def 	__snake_case      (    self			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__			,     UpperCamelCase__							):
						# ValueError: Nodes must be of type `List[str]` (single pretokenized example), or `List[List[str]]`
						# (batch of pretokenized examples).
						return True


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						int    				= MarkupLMModelTester(self							)
						SCREAMING_SNAKE_CASE_ :						Any    				= ConfigTester(self			,     config_class=UpperCamelCase__			,     hidden_size=37							)


		def 	__snake_case      (    self							):
						self.config_tester.run_common_tests()


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Union[str, Any]    				= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_model(*UpperCamelCase__							)


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_sequence_classification(*UpperCamelCase__							)


		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Any    				= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_token_classification(*UpperCamelCase__							)






		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Optional[int]    				= self.model_tester.prepare_config_and_inputs()
						self.model_tester.create_and_check_for_question_answering(*UpperCamelCase__							)






def        _lowerCamelCase(      ):





				'''simple docstring'''







				SCREAMING_SNAKE_CASE_ :						int    				= '\n    <!DOCTYPE html>\n    <html>\n    <head>\n    <title>Page Title</title>\n    </head>\n    <body>\n\n    <h1>This is a Heading</h1>\n    <p>This is a paragraph.</p>\n\n    </body>\n    </html>\n    '

				return html_string


@require_torch
class 				__a				(	unittest.TestCase    ):





		'''simple docstring'''



		@cached_property
		def 	__snake_case      (    self							):
						# TODO use from_pretrained here
						SCREAMING_SNAKE_CASE_ :						List[str]    				= MarkupLMFeatureExtractor()
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= MarkupLMTokenizer.from_pretrained('microsoft/markuplm-base'							)

						return MarkupLMProcessor(UpperCamelCase__			,     UpperCamelCase__							)






		@slow
		def 	__snake_case      (    self							):
						SCREAMING_SNAKE_CASE_ :						Tuple    				= MarkupLMModel.from_pretrained('microsoft/markuplm-base'							).to(UpperCamelCase__							)

						SCREAMING_SNAKE_CASE_ :						Tuple    				= self.default_processor

						SCREAMING_SNAKE_CASE_ :						int    				= processor(prepare_html_string()			,     return_tensors='pt'							)
						SCREAMING_SNAKE_CASE_ :						Optional[Any]    				= inputs.to(UpperCamelCase__							)

						# forward pass
						with torch.no_grad():
										SCREAMING_SNAKE_CASE_ :						str    				= model(**UpperCamelCase__							)

						# verify the last hidden states
						SCREAMING_SNAKE_CASE_ :						List[Any]    				= torch.Size([1, 14, 768]							)
						self.assertEqual(outputs.last_hidden_state.shape			,     UpperCamelCase__							)

						SCREAMING_SNAKE_CASE_ :						Tuple    				= torch.tensor(
						    [[0.06_75, -0.00_52, 0.50_01], [-0.22_81, 0.08_02, 0.21_92], [-0.05_83, -0.33_11, 0.11_85]]							).to(UpperCamelCase__							)

						self.assertTrue(torch.allclose(outputs.last_hidden_state[0, :3, :3]			,     UpperCamelCase__			,     atol=1E-4							)							)