
'''simple docstring'''





import json
import logging
import os
import random
import sys
from dataclasses import dataclass, field
from typing import Optional

import evaluate
import numpy as np
import torch
from datasets import load_dataset
from huggingface_hub import hf_hub_download
from PIL import Image
from torch import nn
from torchvision import transforms
from torchvision.transforms import functional

import transformers
from transformers import (
    AutoConfig,
    AutoImageProcessor,
    AutoModelForSemanticSegmentation,
    HfArgumentParser,
    Trainer,
    TrainingArguments,
    default_data_collator,
)
from transformers.trainer_utils import get_last_checkpoint
from transformers.utils import check_min_version, send_example_telemetry
from transformers.utils.versions import require_version
a__		: Tuple  							=							logging.getLogger(__name__)

# Will error if the minimal version of Transformers is not installed. Remove at your own risks.
check_min_version("4.31.0")

require_version("datasets>=2.0.0", "To fix: pip install -r examples/pytorch/semantic-segmentation/requirements.txt")





def 							snake_case				(		UpperCAmelCase   ,	UpperCAmelCase   ,	UpperCAmelCase=0						)->      Optional[int]:







      """simple docstring"""
      __A													=      (size, size) if isinstance(UpperCAmelCase   ,	UpperCAmelCase						) else size
      __A						,   __A													=      img.size
      __A													=      size[1] - original_height if original_height < size[1] else 0
      __A													=      size[0] - original_width if original_width < size[0] else 0
      __A													=      functional.pad(UpperCAmelCase   ,	(0, 0, pad_width, pad_height)   ,	fill=UpperCAmelCase						)
      return img


class 			UpperCamelCase__	:






 def __init__(      self	:str						,					_A	:List[str]      )					->      Optional[Any]:







       '''simple docstring'''



       __A													=      transforms






 def __call__(      self	:Union[str, Any]						,					_A	:List[str]						,					_A	:Dict      )					->      List[str]:







       '''simple docstring'''



       for t in self.transforms:
             __A						,   __A													=      t(_A						,					_A      )
       return image, target


class 			UpperCamelCase__	:






 def __init__(      self	:str      )					->      Optional[Any]:







       '''simple docstring'''



       pass






 def __call__(      self	:List[Any]						,					_A	:List[str]						,					_A	:Any      )					->      Optional[int]:







       '''simple docstring'''



       return image, target


class 			UpperCamelCase__	:






 def __init__(      self	:Any						,					_A	:int      )					->      Any:







       '''simple docstring'''



       __A													=      size






 def __call__(      self	:str						,					_A	:Optional[int]						,					_A	:Optional[Any]      )					->      Tuple:







       '''simple docstring'''



       __A													=      functional.resize(_A						,					self.size      )
       __A													=      functional.resize(_A						,					self.size						,					interpolation=transforms.InterpolationMode.NEAREST      )
       return image, target


class 			UpperCamelCase__	:






 def __init__(      self	:List[Any]						,					_A	:Optional[int]						,					_A	:Optional[Any]=None      )					->      int:







       '''simple docstring'''



       __A													=      min_size
       if max_size is None:
             __A													=      min_size
       __A													=      max_size






 def __call__(      self	:Any						,					_A	:Optional[int]						,					_A	:Optional[int]      )					->      str:







       '''simple docstring'''



       __A													=      random.randint(self.min_size						,					self.max_size      )
       __A													=      functional.resize(_A						,					_A      )
       __A													=      functional.resize(_A						,					_A						,					interpolation=transforms.InterpolationMode.NEAREST      )
       return image, target


class 			UpperCamelCase__	:






 def __init__(      self	:Any						,					_A	:Optional[int]      )					->      Optional[Any]:







       '''simple docstring'''



       __A													=      size if isinstance(_A						,					_A      ) else (size, size)






 def __call__(      self	:Tuple						,					_A	:List[str]						,					_A	:str      )					->      List[str]:







       '''simple docstring'''



       __A													=      pad_if_smaller(_A						,					self.size      )
       __A													=      pad_if_smaller(_A						,					self.size						,					fill=255      )
       __A													=      transforms.RandomCrop.get_params(_A						,					self.size      )
       __A													=      functional.crop(_A						,					*_A      )
       __A													=      functional.crop(_A						,					*_A      )
       return image, target


class 			UpperCamelCase__	:






 def __init__(      self	:List[str]						,					_A	:Dict      )					->      Dict:







       '''simple docstring'''



       __A													=      flip_prob






 def __call__(      self	:Union[str, Any]						,					_A	:Optional[int]						,					_A	:Dict      )					->      Union[str, Any]:







       '''simple docstring'''



       if random.random() < self.flip_prob:
             __A													=      functional.hflip(_A      )
             __A													=      functional.hflip(_A      )
       return image, target


class 			UpperCamelCase__	:






 def __call__(      self	:Any						,					_A	:Dict						,					_A	:Union[str, Any]      )					->      str:







       '''simple docstring'''



       __A													=      functional.pil_to_tensor(_A      )
       __A													=      torch.as_tensor(np.array(_A      )						,					dtype=torch.intaa      )
       return image, target


class 			UpperCamelCase__	:






 def __init__(      self	:List[Any]						,					_A	:List[Any]      )					->      List[Any]:







       '''simple docstring'''



       __A													=      dtype






 def __call__(      self	:int						,					_A	:List[str]						,					_A	:List[Any]      )					->      int:







       '''simple docstring'''



       __A													=      functional.convert_image_dtype(_A						,					self.dtype      )
       return image, target


class 			UpperCamelCase__	:






 def __init__(      self	:Optional[Any]						,					_A	:Tuple						,					_A	:int      )					->      List[str]:







       '''simple docstring'''



       __A													=      mean
       __A													=      std






 def __call__(      self	:int						,					_A	:Any						,					_A	:Union[str, Any]      )					->      Optional[int]:







       '''simple docstring'''



       __A													=      functional.normalize(_A						,					mean=self.mean						,					std=self.std      )
       return image, target


class 			UpperCamelCase__	:






 def __call__(      self	:Optional[int]						,					_A	:Union[str, Any]						,					_A	:Dict      )					->      Any:







       '''simple docstring'''



       if not isinstance(_A						,					np.ndarray      ):
             __A													=      np.array(_A      ).astype(np.uinta      )
       # avoid using underflow conversion
       __A													=      255
       __A													=      target - 1
       __A													=      255

       __A													=      Image.fromarray(_A      )
       return image, target


@dataclass
class 			UpperCamelCase__	:
 UpperCAmelCase__     :     Optional[str]    					=       field(
     default='segments/sidewalk-semantic'   ,  metadata={
         'help': 'Name of a dataset from the hub (could be your own, possibly private dataset hosted on the hub).'
     }   ,  )
 UpperCAmelCase__     :     Optional[str]    					=       field(
     default=SCREAMING_SNAKE_CASE   ,  metadata={'help': 'The configuration name of the dataset to use (via the datasets library).'})
 UpperCAmelCase__     :     Optional[float]    					=       field(
     default=0.1_5   ,  metadata={'help': 'Percent to split off of train for validation.'})
 UpperCAmelCase__     :     Optional[int]    					=       field(
     default=SCREAMING_SNAKE_CASE   ,  metadata={
         'help': (
             'For debugging purposes or quicker training, truncate the number of training examples to this '
             'value if set.'
         )
     }   ,  )
 UpperCAmelCase__     :     Optional[int]    					=       field(
     default=SCREAMING_SNAKE_CASE   ,  metadata={
         'help': (
             'For debugging purposes or quicker training, truncate the number of evaluation examples to this '
             'value if set.'
         )
     }   ,  )
 UpperCAmelCase__     :     Optional[bool]    					=       field(
     default=SCREAMING_SNAKE_CASE   ,  metadata={'help': 'Whether or not to reduce all labels by 1 and replace background by 255.'}   ,  )






 def 						lowercase_    (      self	:List[str]      )					->      Optional[Any]:







       '''simple docstring'''



       if self.dataset_name is None and (self.train_dir is None and self.validation_dir is None):
             raise ValueError(
                 'You must specify either a dataset name from the hub or a train and/or validation directory.'      )


@dataclass
class 			UpperCamelCase__	:
 UpperCAmelCase__     :     str    					=       field(
     default='nvidia/mit-b0'   ,  metadata={'help': 'Path to pretrained model or model identifier from huggingface.co/models'}   ,  )
 UpperCAmelCase__     :     Optional[str]    					=       field(
     default=SCREAMING_SNAKE_CASE   ,  metadata={'help': 'Pretrained config name or path if not the same as model_name'})
 UpperCAmelCase__     :     Optional[str]    					=       field(
     default=SCREAMING_SNAKE_CASE   ,  metadata={'help': 'Where do you want to store the pretrained models downloaded from s3'})
 UpperCAmelCase__     :     str    					=       field(
     default='main'   ,  metadata={'help': 'The specific model version to use (can be a branch name, tag name or commit id).'}   ,  )
 UpperCAmelCase__     :     str    					=       field(default=SCREAMING_SNAKE_CASE   ,  metadata={'help': 'Name or path of preprocessor config.'})
 UpperCAmelCase__     :     bool    					=       field(
     default=SCREAMING_SNAKE_CASE   ,  metadata={
         'help': (
             'Will use the token generated when running `huggingface-cli login` (necessary to use this script '
             'with private models).'
         )
     }   ,  )





def 							snake_case				(		)->      Dict:







      """simple docstring"""
      # See all possible arguments in src/transformers/training_args.py
      # or by passing the --help flag to this script.
      # We now keep distinct sets of args, for a cleaner separation of concerns.

      __A													=      HfArgumentParser((ModelArguments, DataTrainingArguments, TrainingArguments)						)
      if len(sys.argv						) == 2 and sys.argv[1].endswith('.json'						):
            # If we pass only one argument to the script and it's the path to a json file,
            # let's parse it to get our arguments.
            __A						,   __A						,   __A													=      parser.parse_json_file(json_file=os.path.abspath(sys.argv[1]						)						)
      else:
            __A						,   __A						,   __A													=      parser.parse_args_into_dataclasses()

      # Sending telemetry. Tracking the example usage helps us better allocate resources to maintain them. The
      # information sent is the one passed as arguments along with your Python/PyTorch versions.
      send_example_telemetry('run_semantic_segmentation'   ,	UpperCAmelCase   ,	UpperCAmelCase						)

      # Setup logging
      logging.basicConfig(
          format='%(asctime)s - %(levelname)s - %(name)s - %(message)s'   ,	datefmt='%m/%d/%Y %H:%M:%S'   ,	handlers=[logging.StreamHandler(sys.stdout						)]   ,	)

      if training_args.should_log:
            # The default of training_args.log_level is passive, so we set log level at info here to have that default.
            transformers.utils.logging.set_verbosity_info()

      __A													=      training_args.get_process_log_level()
      logger.setLevel(UpperCAmelCase						)
      transformers.utils.logging.set_verbosity(UpperCAmelCase						)
      transformers.utils.logging.enable_default_handler()
      transformers.utils.logging.enable_explicit_format()

      # Log on each process the small summary:
      logger.warning(
          f'Process rank: {training_args.local_rank}, device: {training_args.device}, n_gpu: {training_args.n_gpu}'
          + f'distributed training: {bool(training_args.local_rank != -1						)}, 16-bits training: {training_args.fpaa}'						)
      logger.info(f'Training/evaluation parameters {training_args}'						)

      # Detecting last checkpoint.
      __A													=      None
      if os.path.isdir(training_args.output_dir						) and training_args.do_train and not training_args.overwrite_output_dir:
            __A													=      get_last_checkpoint(training_args.output_dir						)
            if last_checkpoint is None and len(os.listdir(training_args.output_dir						)						) > 0:
                  raise ValueError(
                      f'Output directory ({training_args.output_dir}) already exists and is not empty. '
                      'Use --overwrite_output_dir to overcome.'						)
            elif last_checkpoint is not None and training_args.resume_from_checkpoint is None:
                  logger.info(
                      f'Checkpoint detected, resuming training at {last_checkpoint}. To avoid this behavior, change '
                      'the `--output_dir` or add `--overwrite_output_dir` to train from scratch.'						)

    # Load dataset
    # In distributed training, the load_dataset function guarantees that only one local process can concurrently
    # download the dataset.
    # TODO support datasets from local folders
      __A													=      load_dataset(data_args.dataset_name   ,	cache_dir=model_args.cache_dir						)

      # Rename column names to standardized names (only "image" and "label" need to be present)
      if "pixel_values" in dataset["train"].column_names:
            __A													=      dataset.rename_columns({'pixel_values': 'image'}						)
      if "annotation" in dataset["train"].column_names:
            __A													=      dataset.rename_columns({'annotation': 'label'}						)

      # If we don't have a validation split, split off a percentage of train as validation.
      __A													=      None if 'validation' in dataset.keys() else data_args.train_val_split
      if isinstance(data_args.train_val_split   ,	UpperCAmelCase						) and data_args.train_val_split > 0.0:
            __A													=      dataset['train'].train_test_split(data_args.train_val_split						)
            __A													=      split['train']
            __A													=      split['test']

      # Prepare label mappings.
      # We'll include these in the model's config to get human readable labels in the Inference API.
      if data_args.dataset_name == "scene_parse_150":
            __A													=      'huggingface/label-files'
            __A													=      'ade20k-id2label.json'
      else:
            __A													=      data_args.dataset_name
            __A													=      'id2label.json'
      __A													=      json.load(open(hf_hub_download(UpperCAmelCase   ,	UpperCAmelCase   ,	repo_type='dataset'						)   ,	'r'						)						)
      __A													=      {int(UpperCAmelCase						): v for k, v in idalabel.items()}
      __A													=      {v: str(UpperCAmelCase						) for k, v in idalabel.items()}

      # Load the mean IoU metric from the datasets package
      __A													=      evaluate.load('mean_iou'						)

      # Define our compute_metrics function. It takes an `EvalPrediction` object (a namedtuple with a
      # predictions and label_ids field) and has to return a dictionary string to float.
      @torch.no_grad()
      def compute_metrics(UpperCAmelCase						):
            __A						,   __A													=      eval_pred
            __A													=      torch.from_numpy(UpperCAmelCase						)
            # scale the logits to the size of the label
            __A													=      nn.functional.interpolate(
                UpperCAmelCase   ,	size=labels.shape[-2:]   ,	mode='bilinear'   ,	align_corners=UpperCAmelCase   ,	).argmax(dim=1						)

            __A													=      logits_tensor.detach().cpu().numpy()
            __A													=      metric.compute(
                predictions=UpperCAmelCase   ,	references=UpperCAmelCase   ,	num_labels=len(UpperCAmelCase						)   ,	ignore_index=0   ,	reduce_labels=image_processor.do_reduce_labels   ,	)
            # add per category metrics as individual key-value pairs
            __A													=      metrics.pop('per_category_accuracy'						).tolist()
            __A													=      metrics.pop('per_category_iou'						).tolist()

            metrics.update({f'accuracy_{idalabel[i]}': v for i, v in enumerate(UpperCAmelCase						)}						)
            metrics.update({f'iou_{idalabel[i]}': v for i, v in enumerate(UpperCAmelCase						)}						)

            return metrics

      __A													=      AutoConfig.from_pretrained(
          model_args.config_name or model_args.model_name_or_path   ,	labelaid=UpperCAmelCase   ,	idalabel=UpperCAmelCase   ,	cache_dir=model_args.cache_dir   ,	revision=model_args.model_revision   ,	use_auth_token=True if model_args.use_auth_token else None   ,	)
      __A													=      AutoModelForSemanticSegmentation.from_pretrained(
          model_args.model_name_or_path   ,	from_tf=bool('.ckpt' in model_args.model_name_or_path						)   ,	config=UpperCAmelCase   ,	cache_dir=model_args.cache_dir   ,	revision=model_args.model_revision   ,	use_auth_token=True if model_args.use_auth_token else None   ,	)
      __A													=      AutoImageProcessor.from_pretrained(
          model_args.image_processor_name or model_args.model_name_or_path   ,	cache_dir=model_args.cache_dir   ,	revision=model_args.model_revision   ,	use_auth_token=True if model_args.use_auth_token else None   ,	)

      # Define torchvision transforms to be applied to each image + target.
      # Not that straightforward in torchvision: https://github.com/pytorch/vision/issues/9
      # Currently based on official torchvision references: https://github.com/pytorch/vision/blob/main/references/segmentation/transforms.py
      if "shortest_edge" in image_processor.size:
            # We instead set the target size as (shortest_edge, shortest_edge) to here to ensure all images are batchable.
            __A													=      (image_processor.size['shortest_edge'], image_processor.size['shortest_edge'])
      else:
            __A													=      (image_processor.size['height'], image_processor.size['width'])
      __A													=      Compose(
          [
              ReduceLabels() if data_args.reduce_labels else Identity(),
              RandomCrop(size=UpperCAmelCase						),
              RandomHorizontalFlip(flip_prob=0.5						),
              PILToTensor(),
              ConvertImageDtype(torch.float						),
              Normalize(mean=image_processor.image_mean   ,	std=image_processor.image_std						),
          ]						)
      # Define torchvision transform to be applied to each image.
      # jitter = ColorJitter(brightness=0.25, contrast=0.25, saturation=0.25, hue=0.1)
      __A													=      Compose(
          [
              ReduceLabels() if data_args.reduce_labels else Identity(),
              Resize(size=UpperCAmelCase						),
              PILToTensor(),
              ConvertImageDtype(torch.float						),
              Normalize(mean=image_processor.image_mean   ,	std=image_processor.image_std						),
          ]						)

      def preprocess_train(UpperCAmelCase						):
            __A													=      []
            __A													=      []
            for image, target in zip(example_batch['image']   ,	example_batch['label']						):
                  __A						,   __A													=      train_transforms(image.convert('RGB'						)   ,	UpperCAmelCase						)
                  pixel_values.append(UpperCAmelCase						)
                  labels.append(UpperCAmelCase						)

            __A													=      {}
            __A													=      torch.stack(UpperCAmelCase						)
            __A													=      torch.stack(UpperCAmelCase						)

            return encoding

      def preprocess_val(UpperCAmelCase						):
            __A													=      []
            __A													=      []
            for image, target in zip(example_batch['image']   ,	example_batch['label']						):
                  __A						,   __A													=      val_transforms(image.convert('RGB'						)   ,	UpperCAmelCase						)
                  pixel_values.append(UpperCAmelCase						)
                  labels.append(UpperCAmelCase						)

            __A													=      {}
            __A													=      torch.stack(UpperCAmelCase						)
            __A													=      torch.stack(UpperCAmelCase						)

            return encoding

      if training_args.do_train:
            if "train" not in dataset:
                  raise ValueError('--do_train requires a train dataset'						)
            if data_args.max_train_samples is not None:
                  __A													=      (
                      dataset['train'].shuffle(seed=training_args.seed						).select(range(data_args.max_train_samples						)						)
                  )
            # Set the training transforms
            dataset["train"].set_transform(UpperCAmelCase						)

      if training_args.do_eval:
            if "validation" not in dataset:
                  raise ValueError('--do_eval requires a validation dataset'						)
            if data_args.max_eval_samples is not None:
                  __A													=      (
                      dataset['validation'].shuffle(seed=training_args.seed						).select(range(data_args.max_eval_samples						)						)
                  )
            # Set the validation transforms
            dataset["validation"].set_transform(UpperCAmelCase						)

      # Initalize our trainer
      __A													=      Trainer(
          model=UpperCAmelCase   ,	args=UpperCAmelCase   ,	train_dataset=dataset['train'] if training_args.do_train else None   ,	eval_dataset=dataset['validation'] if training_args.do_eval else None   ,	compute_metrics=UpperCAmelCase   ,	tokenizer=UpperCAmelCase   ,	data_collator=UpperCAmelCase   ,	)

      # Training
      if training_args.do_train:
            __A													=      None
            if training_args.resume_from_checkpoint is not None:
                  __A													=      training_args.resume_from_checkpoint
            elif last_checkpoint is not None:
                  __A													=      last_checkpoint
            __A													=      trainer.train(resume_from_checkpoint=UpperCAmelCase						)
            trainer.save_model()
            trainer.log_metrics('train'   ,	train_result.metrics						)
            trainer.save_metrics('train'   ,	train_result.metrics						)
            trainer.save_state()

      # Evaluation
      if training_args.do_eval:
            __A													=      trainer.evaluate()
            trainer.log_metrics('eval'   ,	UpperCAmelCase						)
            trainer.save_metrics('eval'   ,	UpperCAmelCase						)

      # Write model card and (optionally) push to hub
      __A													=      {
          'finetuned_from': model_args.model_name_or_path,
          'dataset': data_args.dataset_name,
          'tags': ['image-segmentation', 'vision'],
      }
      if training_args.push_to_hub:
            trainer.push_to_hub(**UpperCAmelCase						)
      else:
            trainer.create_model_card(**UpperCAmelCase						)


if __name__ == "__main__":
 main()








'''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 			UpperCamelCase__	:






 def __init__(      self	:str						,					_A	:Any						,					_A	:Union[str, Any]=13						,					_A	:List[Any]=7						,					_A	:int=True						,					_A	:Union[str, Any]=True						,					_A	:List[Any]=True						,					_A	:Dict=True						,					_A	:int=99						,					_A	:Union[str, Any]=32						,					_A	:int=5						,					_A	:List[str]=4						,					_A	:Optional[int]=37						,					_A	:List[str]="gelu"						,					_A	:Any=0.1						,					_A	:int=0.1						,					_A	:List[str]=512						,					_A	:Optional[Any]=16						,					_A	:Optional[Any]=2						,					_A	:List[str]=0.02						,					_A	:Any=3						,					_A	:Tuple=None						,					_A	:str=20						,					_A	:List[Any]=30						,					_A	:Dict=2						,					_A	:Union[str, Any]=2						,					_A	:int=10						,					)					->      Any:







       '''simple docstring'''



       __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 						lowercase_    (      self	:Tuple      )					->      Optional[int]:







       '''simple docstring'''



       __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 						lowercase_    (      self	:List[Any]      )					->      int:







       '''simple docstring'''



       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 						lowercase_    (      self	:Union[str, Any]						,					_A	:List[str]						,					_A	:str						,					_A	:int						,					_A	:str						,					_A	:Dict						,					_A	:str						,					_A	:Optional[int]						,					_A	:Optional[Any]						,					)					->      Tuple:







       '''simple docstring'''



       __A													=      MarkupLMModel(config=_A      )
       model.to(_A      )
       model.eval()
       print('Configs:'						,					model.config.tag_pad_id						,					model.config.subs_pad_id      )
       __A													=      model(_A						,					attention_mask=_A						,					token_type_ids=_A      )
       __A													=      model(_A						,					token_type_ids=_A      )
       __A													=      model(_A      )
       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 						lowercase_    (      self	:Any						,					_A	:Optional[Any]						,					_A	:Any						,					_A	:Optional[int]						,					_A	:Any						,					_A	:int						,					_A	:List[Any]						,					_A	:Dict						,					_A	:List[str]						,					)					->      Any:







       '''simple docstring'''



       __A													=      self.num_labels
       __A													=      MarkupLMForSequenceClassification(_A      )
       model.to(_A      )
       model.eval()
       __A													=      model(
           _A						,					xpath_tags_seq=_A						,					xpath_subs_seq=_A						,					attention_mask=_A						,					token_type_ids=_A						,					labels=_A						,					)
       self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.num_labels)      )






 def 						lowercase_    (      self	:Any						,					_A	:List[str]						,					_A	:str						,					_A	:str						,					_A	:List[Any]						,					_A	:Optional[Any]						,					_A	:Union[str, Any]						,					_A	:Dict						,					_A	:Union[str, Any]						,					)					->      Dict:







       '''simple docstring'''



       __A													=      self.num_labels
       __A													=      MarkupLMForTokenClassification(config=_A      )
       model.to(_A      )
       model.eval()
       __A													=      model(
           _A						,					xpath_tags_seq=_A						,					xpath_subs_seq=_A						,					attention_mask=_A						,					token_type_ids=_A						,					labels=_A						,					)
       self.parent.assertEqual(result.logits.shape						,					(self.batch_size, self.seq_length, self.num_labels)      )






 def 						lowercase_    (      self	:int						,					_A	:str						,					_A	:Tuple						,					_A	:Any						,					_A	:int						,					_A	:Any						,					_A	:Any						,					_A	:Union[str, Any]						,					_A	:List[Any]						,					)					->      List[str]:







       '''simple docstring'''



       __A													=      MarkupLMForQuestionAnswering(config=_A      )
       model.to(_A      )
       model.eval()
       __A													=      model(
           _A						,					xpath_tags_seq=_A						,					xpath_subs_seq=_A						,					attention_mask=_A						,					token_type_ids=_A						,					start_positions=_A						,					end_positions=_A						,					)
       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 						lowercase_    (      self	:Dict      )					->      List[str]:







       '''simple docstring'''



       __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 			UpperCamelCase__	(     SCREAMING_SNAKE_CASE   ,  SCREAMING_SNAKE_CASE   ,  unittest.TestCase):
 UpperCAmelCase__     :     List[Any]    					=       (
     (
         MarkupLMModel,
         MarkupLMForSequenceClassification,
         MarkupLMForTokenClassification,
         MarkupLMForQuestionAnswering,
     )
     if is_torch_available()
     else None
 )
 UpperCAmelCase__     :     Tuple    					=       (
     {
         'feature-extraction': MarkupLMModel,
         'question-answering': MarkupLMForQuestionAnswering,
         'text-classification': MarkupLMForSequenceClassification,
         'token-classification': MarkupLMForTokenClassification,
         'zero-shot': MarkupLMForSequenceClassification,
     }
     if is_torch_available()
     else {}
 )






 def 						lowercase_    (      self	:Union[str, Any]						,					_A	:List[str]						,					_A	:Optional[Any]						,					_A	:Dict						,					_A	:Optional[Any]						,					_A	:Optional[int]      )					->      Tuple:







       '''simple docstring'''



       return True






 def 						lowercase_    (      self	:List[str]      )					->      Union[str, Any]:







       '''simple docstring'''



       __A													=      MarkupLMModelTester(self      )
       __A													=      ConfigTester(self						,					config_class=_A						,					hidden_size=37      )






 def 						lowercase_    (      self	:Optional[Any]      )					->      int:







       '''simple docstring'''



       self.config_tester.run_common_tests()






 def 						lowercase_    (      self	:Union[str, Any]      )					->      Optional[Any]:







       '''simple docstring'''



       __A													=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_model(*_A      )






 def 						lowercase_    (      self	:Optional[Any]      )					->      Any:







       '''simple docstring'''



       __A													=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_sequence_classification(*_A      )






 def 						lowercase_    (      self	:Tuple      )					->      Union[str, Any]:







       '''simple docstring'''



       __A													=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_token_classification(*_A      )






 def 						lowercase_    (      self	:List[Any]      )					->      Tuple:







       '''simple docstring'''



       __A													=      self.model_tester.prepare_config_and_inputs()
       self.model_tester.create_and_check_for_question_answering(*_A      )





def 							snake_case				(		)->      str:







      """simple docstring"""
      __A													=      '\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 			UpperCamelCase__	(     unittest.TestCase):






 @cached_property
 def 						lowercase_    (      self	:Optional[int]      )					->      Dict:







       '''simple docstring'''



       __A													=      MarkupLMFeatureExtractor()
       __A													=      MarkupLMTokenizer.from_pretrained('microsoft/markuplm-base'      )

       return MarkupLMProcessor(_A						,					_A      )






 @slow
 def 						lowercase_    (      self	:Any      )					->      str:







       '''simple docstring'''



       __A													=      MarkupLMModel.from_pretrained('microsoft/markuplm-base'      ).to(_A      )

       __A													=      self.default_processor

       __A													=      processor(prepare_html_string()						,					return_tensors='pt'      )
       __A													=      inputs.to(_A      )

       # forward pass
       with torch.no_grad():
             __A													=      model(**_A      )

       # verify the last hidden states
       __A													=      torch.Size([1, 14, 768]      )
       self.assertEqual(outputs.last_hidden_state.shape						,					_A      )

       __A													=      torch.tensor(
           [[0.0_675, -0.0_052, 0.5_001], [-0.2_281, 0.0_802, 0.2_192], [-0.0_583, -0.3_311, 0.1_185]]      ).to(_A      )

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






