"""simple docstring"""


import inspect
from typing import Callable, List, Optional, Set, Tuple, Union

import torch
from packaging import version
from safetensors.torch import storage_ptr, storage_size
from torch import nn

from .utils import logging


__A       			=      [nn.LayerNorm]

__A       			=      logging.get_logger(__name__)

__A       			=      version.parse(version.parse(torch.__version__).base_version)

__A       			=      parsed_torch_version_base >= version.parse("""2.0""")
__A       			=      parsed_torch_version_base >= version.parse("""1.12""")
__A       			=      parsed_torch_version_base >= version.parse("""1.11""")
__A       			=      parsed_torch_version_base < version.parse("""1.11""")

def 						UpperCamelCase				(	_lowerCAmelCase   :							Tuple				, _lowerCAmelCase   :							List[str]				, _lowerCAmelCase   :							Union[str, Any]				, _lowerCAmelCase   :							int				, self   :							Optional[Any]						):
    from torch import _softmax_backward_data

    if is_torch_less_than_1_11:
        return _softmax_backward_data(_lowerCAmelCase				, _lowerCAmelCase				, parent.dim				, self						)
    else:
        return _softmax_backward_data(_lowerCAmelCase				, _lowerCAmelCase				, parent.dim				, self.dtype						)

def 						UpperCamelCase				(	_lowerCAmelCase   :							nn.Linear				, _lowerCAmelCase   :							torch.LongTensor				, _lowerCAmelCase   :							int = 0						):
    __a			      =						index.to(layer.weight.device						)
    __a			      =						layer.weight.index_select(_lowerCAmelCase				, _lowerCAmelCase						).clone().detach()
    if layer.bias is not None:
        if dim == 1:
            __a			      =						layer.bias.clone().detach()
        else:
            __a			      =						layer.bias[index].clone().detach()
    __a			      =						list(layer.weight.size()						)
    __a			      =						len(_lowerCAmelCase						)
    __a			      =						nn.Linear(new_size[1]				, new_size[0]				, bias=layer.bias is not None						).to(layer.weight.device						)
    __a			      =						False
    new_layer.weight.copy_(W.contiguous()						)
    __a			      =						True
    if layer.bias is not None:
        __a			      =						False
        new_layer.bias.copy_(b.contiguous()						)
        __a			      =						True
    return new_layer






class 					a					(				nn.Module							):



  def __init__(		self   :    Optional[int]						,  lowerCamelCase_   :    Optional[Any]						,  lowerCamelCase_   :    List[Any]     )      -> List[str]:
      super().__init__()
      __a			      =						nf
      __a			      =						nn.Parameter(torch.empty(lowerCamelCase_						,  lowerCamelCase_     )     )
      __a			      =						nn.Parameter(torch.zeros(lowerCamelCase_     )     )
      nn.init.normal_(self.weight						,  std=0.02     )



  def        lowerCAmelCase_				(		self   :    int						,  lowerCamelCase_   :    Optional[Any]     )      -> Union[str, Any]:
      __a			      =						x.size()[:-1] + (self.nf,)
      __a			      =						torch.addmm(self.bias						,  x.view(-1						,  x.size(-1     )     )						,  self.weight     )
      __a			      =						x.view(lowerCamelCase_     )
      return x

def 						UpperCamelCase				(	_lowerCAmelCase   :							ConvaD				, _lowerCAmelCase   :							torch.LongTensor				, _lowerCAmelCase   :							int = 1						):
    __a			      =						index.to(layer.weight.device						)
    __a			      =						layer.weight.index_select(_lowerCAmelCase				, _lowerCAmelCase						).clone().detach()
    if dim == 0:
        __a			      =						layer.bias.clone().detach()
    else:
        __a			      =						layer.bias[index].clone().detach()
    __a			      =						list(layer.weight.size()						)
    __a			      =						len(_lowerCAmelCase						)
    __a			      =						ConvaD(new_size[1]				, new_size[0]						).to(layer.weight.device						)
    __a			      =						False
    new_layer.weight.copy_(W.contiguous()						)
    __a			      =						True
    __a			      =						False
    new_layer.bias.copy_(b.contiguous()						)
    __a			      =						True
    return new_layer

def 						UpperCamelCase				(	_lowerCAmelCase   :							Union[nn.Linear, ConvaD]				, _lowerCAmelCase   :							torch.LongTensor				, _lowerCAmelCase   :							Optional[int] = None						):
    if isinstance(_lowerCAmelCase				, nn.Linear						):
        return prune_linear_layer(_lowerCAmelCase				, _lowerCAmelCase				, dim=0 if dim is None else dim						)
    elif isinstance(_lowerCAmelCase				, _lowerCAmelCase						):
        return prune_convad_layer(_lowerCAmelCase				, _lowerCAmelCase				, dim=1 if dim is None else dim						)
    else:
        raise ValueError(f"""Can't prune layer of class {layer.__class__}"""						)

def 						UpperCamelCase				(	_lowerCAmelCase   :							Callable[..., torch.Tensor]				, _lowerCAmelCase   :							int				, _lowerCAmelCase   :							int				, *_lowerCAmelCase   :							List[Any]						):
    assert len(_lowerCAmelCase						) > 0, f"""{input_tensors} has to be a tuple/list of tensors"""

    # inspect.signature exist since python 3.5 and is a python method -> no problem with backward compatibility
    __a			      =						len(inspect.signature(_lowerCAmelCase						).parameters						)
    if num_args_in_forward_chunk_fn != len(_lowerCAmelCase						):
        raise ValueError(
            f"""forward_chunk_fn expects {num_args_in_forward_chunk_fn} arguments, but only {len(_lowerCAmelCase						)} input """
            """tensors are given"""						)

    if chunk_size > 0:
        __a			      =						input_tensors[0].shape[chunk_dim]
        for input_tensor in input_tensors:
            if input_tensor.shape[chunk_dim] != tensor_shape:
                raise ValueError(
                    f"""All input tenors have to be of the same shape: {tensor_shape}, """
                    f"""found shape {input_tensor.shape[chunk_dim]}"""						)

        if input_tensors[0].shape[chunk_dim] % chunk_size != 0:
            raise ValueError(
                f"""The dimension to be chunked {input_tensors[0].shape[chunk_dim]} has to be a multiple of the chunk """
                f"""size {chunk_size}"""						)

        __a			      =						input_tensors[0].shape[chunk_dim] // chunk_size

        # chunk input tensor into tuples
        __a			      =						tuple(input_tensor.chunk(_lowerCAmelCase				, dim=_lowerCAmelCase						) for input_tensor in input_tensors						)
        # apply forward fn to every tuple
        __a			      =						tuple(forward_fn(*_lowerCAmelCase						) for input_tensors_chunk in zip(*_lowerCAmelCase						)						)
        # concatenate output at same dimension
        return torch.cat(_lowerCAmelCase				, dim=_lowerCAmelCase						)

    return forward_fn(*_lowerCAmelCase						)

def 						UpperCamelCase				(	_lowerCAmelCase   :							List[int]				, _lowerCAmelCase   :							int				, _lowerCAmelCase   :							int				, _lowerCAmelCase   :							Set[int]						):
    __a			      =						torch.ones(_lowerCAmelCase				, _lowerCAmelCase						)
    __a			      =						set(_lowerCAmelCase						) - already_pruned_heads  # Convert to set and remove already pruned heads
    for head in heads:
        # Compute how many pruned heads are before the head and move the index accordingly
        __a			      =						head - sum(1 if h < head else 0 for h in already_pruned_heads						)
        __a			      =						0
    __a			      =						mask.view(-1						).contiguous().eq(1						)
    __a			      =						torch.arange(len(_lowerCAmelCase						)						)[mask].long()
    return heads, index

def 						UpperCamelCase				(	*_lowerCAmelCase   :							Union[torch.Tensor, List[torch.Tensor]]				, _lowerCAmelCase   :							Optional[str] = None						):
    return torch.meshgrid(*_lowerCAmelCase				, indexing=_lowerCAmelCase						)






def 						UpperCamelCase				(	_lowerCAmelCase   :							torch.Tensor						):
    return tensor.device, storage_ptr(_lowerCAmelCase						), storage_size(_lowerCAmelCase						)

"""simple docstring"""


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					:



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



  def        lowerCAmelCase_				(		self   :    Dict     )      -> Dict:
      __a			      =						ids_tensor([self.batch_size, self.seq_length]						,  self.vocab_size     )

      __a			      =						ids_tensor(
          [self.batch_size, self.seq_length, self.max_depth]						,  self.max_xpath_tag_unit_embeddings     )

      __a			      =						ids_tensor(
          [self.batch_size, self.seq_length, self.max_depth]						,  self.max_xpath_subs_unit_embeddings     )

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

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

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

      __a			      =						self.get_config()

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



  def        lowerCAmelCase_				(		self   :    List[Any]     )      -> Optional[Any]:
      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        lowerCAmelCase_				(		self   :    Tuple						,  lowerCamelCase_   :    int						,  lowerCamelCase_   :    int						,  lowerCamelCase_   :    List[str]						,  lowerCamelCase_   :    int						,  lowerCamelCase_   :    Any						,  lowerCamelCase_   :    Optional[Any]						,  lowerCamelCase_   :    Any						,  lowerCamelCase_   :    List[Any]						,  )      -> int:
      __a			      =						MarkupLMModel(config=lowerCamelCase_     )
      model.to(lowerCamelCase_     )
      model.eval()
      print("""Configs:"""						,  model.config.tag_pad_id						,  model.config.subs_pad_id     )
      __a			      =						model(lowerCamelCase_						,  attention_mask=lowerCamelCase_						,  token_type_ids=lowerCamelCase_     )
      __a			      =						model(lowerCamelCase_						,  token_type_ids=lowerCamelCase_     )
      __a			      =						model(lowerCamelCase_     )
      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        lowerCAmelCase_				(		self   :    Optional[int]						,  lowerCamelCase_   :    List[Any]						,  lowerCamelCase_   :    Optional[int]						,  lowerCamelCase_   :    str						,  lowerCamelCase_   :    Optional[int]						,  lowerCamelCase_   :    List[Any]						,  lowerCamelCase_   :    Tuple						,  lowerCamelCase_   :    List[str]						,  lowerCamelCase_   :    int						,  )      -> Optional[Any]:
      __a			      =						self.num_labels
      __a			      =						MarkupLMForSequenceClassification(lowerCamelCase_     )
      model.to(lowerCamelCase_     )
      model.eval()
      __a			      =						model(
          lowerCamelCase_						,  xpath_tags_seq=lowerCamelCase_						,  xpath_subs_seq=lowerCamelCase_						,  attention_mask=lowerCamelCase_						,  token_type_ids=lowerCamelCase_						,  labels=lowerCamelCase_						,  )
      self.parent.assertEqual(result.logits.shape						,  (self.batch_size, self.num_labels)     )



  def        lowerCAmelCase_				(		self   :    int						,  lowerCamelCase_   :    Any						,  lowerCamelCase_   :    Any						,  lowerCamelCase_   :    List[Any]						,  lowerCamelCase_   :    Dict						,  lowerCamelCase_   :    Union[str, Any]						,  lowerCamelCase_   :    Union[str, Any]						,  lowerCamelCase_   :    str						,  lowerCamelCase_   :    Union[str, Any]						,  )      -> int:
      __a			      =						self.num_labels
      __a			      =						MarkupLMForTokenClassification(config=lowerCamelCase_     )
      model.to(lowerCamelCase_     )
      model.eval()
      __a			      =						model(
          lowerCamelCase_						,  xpath_tags_seq=lowerCamelCase_						,  xpath_subs_seq=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        lowerCAmelCase_				(		self   :    List[Any]						,  lowerCamelCase_   :    Tuple						,  lowerCamelCase_   :    Dict						,  lowerCamelCase_   :    Optional[int]						,  lowerCamelCase_   :    Optional[Any]						,  lowerCamelCase_   :    Optional[Any]						,  lowerCamelCase_   :    Union[str, Any]						,  lowerCamelCase_   :    Dict						,  lowerCamelCase_   :    List[Any]						,  )      -> Tuple:
      __a			      =						MarkupLMForQuestionAnswering(config=lowerCamelCase_     )
      model.to(lowerCamelCase_     )
      model.eval()
      __a			      =						model(
          lowerCamelCase_						,  xpath_tags_seq=lowerCamelCase_						,  xpath_subs_seq=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        lowerCAmelCase_				(		self   :    str     )      -> str:
      __a			      =						self.prepare_config_and_inputs()
      (
          (
          __a
      )      ,  (
          __a
      )      ,  (
          __a
      )      ,  (
          __a
      )      ,  (
          __a
      )      ,  (
          __a
      )      ,  (
          __a
      )      ,  (
          __a
      )      ,  
      )			      =						config_and_inputs
      __a			      =						{
          """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							):
  A_ :				int 			=							(
      (
          MarkupLMModel,
          MarkupLMForSequenceClassification,
          MarkupLMForTokenClassification,
          MarkupLMForQuestionAnswering,
      )
      if is_torch_available()
      else None
  )
  A_ :				Any 			=							(
      {
          '''feature-extraction''': MarkupLMModel,
          '''question-answering''': MarkupLMForQuestionAnswering,
          '''text-classification''': MarkupLMForSequenceClassification,
          '''token-classification''': MarkupLMForTokenClassification,
          '''zero-shot''': MarkupLMForSequenceClassification,
      }
      if is_torch_available()
      else {}
  )



  def        lowerCAmelCase_				(		self   :    Union[str, Any]						,  lowerCamelCase_   :    Optional[Any]						,  lowerCamelCase_   :    Union[str, Any]						,  lowerCamelCase_   :    Optional[int]						,  lowerCamelCase_   :    List[str]						,  lowerCamelCase_   :    Union[str, Any]     )      -> List[Any]:
      # ValueError: Nodes must be of type `List[str]` (single pretokenized example), or `List[List[str]]`
      # (batch of pretokenized examples).
      return True



  def        lowerCAmelCase_				(		self   :    Tuple     )      -> str:
      __a			      =						MarkupLMModelTester(self     )
      __a			      =						ConfigTester(self						,  config_class=lowerCamelCase_						,  hidden_size=37     )



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



  def        lowerCAmelCase_				(		self   :    str     )      -> Dict:
      __a			      =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_model(*lowerCamelCase_     )



  def        lowerCAmelCase_				(		self   :    Dict     )      -> Optional[int]:
      __a			      =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_sequence_classification(*lowerCamelCase_     )



  def        lowerCAmelCase_				(		self   :    Tuple     )      -> Tuple:
      __a			      =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_token_classification(*lowerCamelCase_     )



  def        lowerCAmelCase_				(		self   :    Union[str, Any]     )      -> int:
      __a			      =						self.model_tester.prepare_config_and_inputs()
      self.model_tester.create_and_check_for_question_answering(*lowerCamelCase_     )

def 						UpperCamelCase				(	):
    __a			      =						"""
    <!DOCTYPE html>
    <html>
    <head>
    <title>Page Title</title>
    </head>
    <body>

    <h1>This is a Heading</h1>
    <p>This is a paragraph.</p>

    </body>
    </html>
    """

    return html_string






@require_torch
class 					a					(				unittest.TestCase							):



  @cached_property
  def        lowerCAmelCase_				(		self   :    int     )      -> Any:
      # TODO use from_pretrained here
      __a			      =						MarkupLMFeatureExtractor()
      __a			      =						MarkupLMTokenizer.from_pretrained("""microsoft/markuplm-base"""     )

      return MarkupLMProcessor(lowerCamelCase_						,  lowerCamelCase_     )



  @slow
  def        lowerCAmelCase_				(		self   :    Optional[int]     )      -> Dict:
      __a			      =						MarkupLMModel.from_pretrained("""microsoft/markuplm-base"""     ).to(lowerCamelCase_     )

      __a			      =						self.default_processor

      __a			      =						processor(prepare_html_string()						,  return_tensors="""pt"""     )
      __a			      =						inputs.to(lowerCamelCase_     )

      # forward pass
      with torch.no_grad():
          __a			      =						model(**lowerCamelCase_     )

      # verify the last hidden states
      __a			      =						torch.Size([1, 14, 7_68]     )
      self.assertEqual(outputs.last_hidden_state.shape						,  lowerCamelCase_     )

      __a			      =						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(lowerCamelCase_     )

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