MarkupLM

## [](#overview)Overview

The MarkupLM model was proposed in [MarkupLM: Pre-training of Text and Markup Language for Visually-rich Document Understanding](https://arxiv.org/abs/2110.08518) by Junlong Li, Yiheng Xu, Lei Cui, Furu Wei. MarkupLM is BERT, but applied to HTML pages instead of raw text documents. The model incorporates additional embedding layers to improve performance, similar to [LayoutLM](layoutlm).

The model can be used for tasks like question answering on web pages or information extraction from web pages. It obtains state-of-the-art results on 2 important benchmarks:

-   [WebSRC](https://x-lance.github.io/WebSRC/), a dataset for Web-Based Structural Reading Comprehension (a bit like SQuAD but for web pages)
-   [SWDE](https://www.researchgate.net/publication/221299838_From_one_tree_to_a_forest_a_unified_solution_for_structured_web_data_extraction), a dataset for information extraction from web pages (basically named-entity recogntion on web pages)

The abstract from the paper is the following:

_Multimodal pre-training with text, layout, and image has made significant progress for Visually-rich Document Understanding (VrDU), especially the fixed-layout documents such as scanned document images. While, there are still a large number of digital documents where the layout information is not fixed and needs to be interactively and dynamically rendered for visualization, making existing layout-based pre-training approaches not easy to apply. In this paper, we propose MarkupLM for document understanding tasks with markup languages as the backbone such as HTML/XML-based documents, where text and markup information is jointly pre-trained. Experiment results show that the pre-trained MarkupLM significantly outperforms the existing strong baseline models on several document understanding tasks. The pre-trained model and code will be publicly available._

Tips:

-   In addition to `input_ids`, [forward()](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMModel.forward) expects 2 additional inputs, namely `xpath_tags_seq` and `xpath_subs_seq`. These are the XPATH tags and subscripts respectively for each token in the input sequence.
-   One can use [MarkupLMProcessor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMProcessor) to prepare all data for the model. Refer to the [usage guide](#usage-markuplmprocessor) for more info.
-   Demo notebooks can be found [here](https://github.com/NielsRogge/Transformers-Tutorials/tree/master/MarkupLM).

![drawing](https://huggingface.co/datasets/huggingface/documentation-images/resolve/main/transformers/model_doc/markuplm_architecture.jpg) MarkupLM architecture. Taken from the [original paper.](https://arxiv.org/abs/2110.08518)

This model was contributed by [nielsr](https://huggingface.co/nielsr). The original code can be found [here](https://github.com/microsoft/unilm/tree/master/markuplm).

## [](#usage-markuplmprocessor)Usage: MarkupLMProcessor

The easiest way to prepare data for the model is to use [MarkupLMProcessor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMProcessor), which internally combines a feature extractor ([MarkupLMFeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMFeatureExtractor)) and a tokenizer ([MarkupLMTokenizer](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizer) or [MarkupLMTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizerFast)). The feature extractor is used to extract all nodes and xpaths from the HTML strings, which are then provided to the tokenizer, which turns them into the token-level inputs of the model (`input_ids` etc.). Note that you can still use the feature extractor and tokenizer separately, if you only want to handle one of the two tasks.

```
from transformers import MarkupLMFeatureExtractor, MarkupLMTokenizerFast, MarkupLMProcessor

feature_extractor = MarkupLMFeatureExtractor()
tokenizer = MarkupLMTokenizerFast.from_pretrained("microsoft/markuplm-base")
processor = MarkupLMProcessor(feature_extractor, tokenizer)```

In short, one can provide HTML strings (and possibly additional data) to [MarkupLMProcessor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMProcessor), and it will create the inputs expected by the model. Internally, the processor first uses [MarkupLMFeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMFeatureExtractor) to get a list of nodes and corresponding xpaths. The nodes and xpaths are then provided to [MarkupLMTokenizer](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizer) or [MarkupLMTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizerFast), which converts them to token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_subs_seq`, `xpath_tags_seq`. Optionally, one can provide node labels to the processor, which are turned into token-level `labels`.

[MarkupLMFeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMFeatureExtractor) uses [Beautiful Soup](https://www.crummy.com/software/BeautifulSoup/bs4/doc/), a Python library for pulling data out of HTML and XML files, under the hood. Note that you can still use your own parsing solution of choice, and provide the nodes and xpaths yourself to [MarkupLMTokenizer](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizer) or [MarkupLMTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizerFast).

In total, there are 5 use cases that are supported by the processor. Below, we list them all. Note that each of these use cases work for both batched and non-batched inputs (we illustrate them for non-batched inputs).

**Use case 1: web page classification (training, inference) + token classification (inference), parse\_html = True**

This is the simplest case, in which the processor will use the feature extractor to get all nodes and xpaths from the HTML.

```
>>> from transformers import MarkupLMProcessor

>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base")

>>> html_string = """
...  <!DOCTYPE html>
...  <html>
...  <head>
...  <title>Hello world</title>
...  </head>
...  <body>
...  <h1>Welcome</h1>
...  <p>Here is my website.</p>
...  </body>
...  </html>"""

>>> 
>>> encoding = processor(html_string, return_tensors="pt")
>>> print(encoding.keys())
dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq'])```

**Use case 2: web page classification (training, inference) + token classification (inference), parse\_html=False**

In case one already has obtained all nodes and xpaths, one doesn’t need the feature extractor. In that case, one should provide the nodes and corresponding xpaths themselves to the processor, and make sure to set `parse_html` to `False`.

```
>>> from transformers import MarkupLMProcessor

>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base")
>>> processor.parse_html = False

>>> nodes = ["hello", "world", "how", "are"]
>>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span", "html/body", "html/body/div"]
>>> encoding = processor(nodes=nodes, xpaths=xpaths, return_tensors="pt")
>>> print(encoding.keys())
dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq'])```

**Use case 3: token classification (training), parse\_html=False**

For token classification tasks (such as [SWDE](https://paperswithcode.com/dataset/swde)), one can also provide the corresponding node labels in order to train a model. The processor will then convert these into token-level `labels`. By default, it will only label the first wordpiece of a word, and label the remaining wordpieces with -100, which is the `ignore_index` of PyTorch’s CrossEntropyLoss. In case you want all wordpieces of a word to be labeled, you can initialize the tokenizer with `only_label_first_subword` set to `False`.

```
>>> from transformers import MarkupLMProcessor

>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base")
>>> processor.parse_html = False

>>> nodes = ["hello", "world", "how", "are"]
>>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span", "html/body", "html/body/div"]
>>> node_labels = [1, 2, 2, 1]
>>> encoding = processor(nodes=nodes, xpaths=xpaths, node_labels=node_labels, return_tensors="pt")
>>> print(encoding.keys())
dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq', 'labels'])```

**Use case 4: web page question answering (inference), parse\_html=True**

For question answering tasks on web pages, you can provide a question to the processor. By default, the processor will use the feature extractor to get all nodes and xpaths, and create \[CLS\] question tokens \[SEP\] word tokens \[SEP\].

```
>>> from transformers import MarkupLMProcessor

>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base")

>>> html_string = """
...  <!DOCTYPE html>
...  <html>
...  <head>
...  <title>Hello world</title>
...  </head>
...  <body>
...  <h1>Welcome</h1>
...  <p>My name is Niels.</p>
...  </body>
...  </html>"""

>>> question = "What's his name?"
>>> encoding = processor(html_string, questions=question, return_tensors="pt")
>>> print(encoding.keys())
dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq'])```

**Use case 5: web page question answering (inference), parse\_html=False**

For question answering tasks (such as WebSRC), you can provide a question to the processor. If you have extracted all nodes and xpaths yourself, you can provide them directly to the processor. Make sure to set `parse_html` to `False`.

```
>>> from transformers import MarkupLMProcessor

>>> processor = MarkupLMProcessor.from_pretrained("microsoft/markuplm-base")
>>> processor.parse_html = False

>>> nodes = ["hello", "world", "how", "are"]
>>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span", "html/body", "html/body/div"]
>>> question = "What's his name?"
>>> encoding = processor(nodes=nodes, xpaths=xpaths, questions=question, return_tensors="pt")
>>> print(encoding.keys())
dict_keys(['input_ids', 'token_type_ids', 'attention_mask', 'xpath_tags_seq', 'xpath_subs_seq'])```

## [](#documentation-resources)Documentation resources

-   [Text classification task guide](../tasks/sequence_classification)
-   [Token classification task guide](../tasks/token_classification)
-   [Question answering task guide](../tasks/question_answering)

## [](#transformers.MarkupLMConfig)MarkupLMConfig

### class transformers.MarkupLMConfig

[](#transformers.MarkupLMConfig)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/configuration_markuplm.py#L29)

( vocab\_size = 30522hidden\_size = 768num\_hidden\_layers = 12num\_attention\_heads = 12intermediate\_size = 3072hidden\_act = 'gelu'hidden\_dropout\_prob = 0.1attention\_probs\_dropout\_prob = 0.1max\_position\_embeddings = 512type\_vocab\_size = 2initializer\_range = 0.02layer\_norm\_eps = 1e-12pad\_token\_id = 0bos\_token\_id = 0eos\_token\_id = 2max\_xpath\_tag\_unit\_embeddings = 256max\_xpath\_subs\_unit\_embeddings = 1024tag\_pad\_id = 216subs\_pad\_id = 1001xpath\_unit\_hidden\_size = 32max\_depth = 50position\_embedding\_type = 'absolute'use\_cache = Trueclassifier\_dropout = None\*\*kwargs )

This is the configuration class to store the configuration of a [MarkupLMModel](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMModel). It is used to instantiate a MarkupLM model according to the specified arguments, defining the model architecture. Instantiating a configuration with the defaults will yield a similar configuration to that of the MarkupLM [microsoft/markuplm-base](https://huggingface.co/microsoft/markuplm-base) architecture.

Configuration objects inherit from [BertConfig](/docs/transformers/v4.30.0/en/model_doc/bert#transformers.BertConfig) and can be used to control the model outputs. Read the documentation from [BertConfig](/docs/transformers/v4.30.0/en/model_doc/bert#transformers.BertConfig) for more information.

Examples:

```
>>> from transformers import MarkupLMModel, MarkupLMConfig

>>> 
>>> configuration = MarkupLMConfig()

>>> 
>>> model = MarkupLMModel(configuration)

>>> 
>>> configuration = model.config```

## [](#transformers.MarkupLMFeatureExtractor)MarkupLMFeatureExtractor

Constructs a MarkupLM feature extractor. This can be used to get a list of nodes and corresponding xpaths from HTML strings.

This feature extractor inherits from `PreTrainedFeatureExtractor()` which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

( html\_strings ) → [BatchFeature](/docs/transformers/v4.30.0/en/main_classes/image_processor#transformers.BatchFeature)

Parameters

-   [](#transformers.MarkupLMFeatureExtractor.__call__.html_strings)**html\_strings** (`str`, `List[str]`) — The HTML string or batch of HTML strings from which to extract nodes and corresponding xpaths.

A [BatchFeature](/docs/transformers/v4.30.0/en/main_classes/image_processor#transformers.BatchFeature) with the following fields:

-   **nodes** — Nodes.
-   **xpaths** — Corresponding xpaths.

Main method to prepare for the model one or several HTML strings.

Examples:

```
>>> from transformers import MarkupLMFeatureExtractor

>>> page_name_1 = "page1.html"
>>> page_name_2 = "page2.html"
>>> page_name_3 = "page3.html"

>>> with open(page_name_1) as f:
...     single_html_string = f.read()

>>> feature_extractor = MarkupLMFeatureExtractor()

>>> 
>>> encoding = feature_extractor(single_html_string)
>>> print(encoding.keys())
>>> 

>>> 

>>> multi_html_strings = []

>>> with open(page_name_2) as f:
...     multi_html_strings.append(f.read())
>>> with open(page_name_3) as f:
...     multi_html_strings.append(f.read())

>>> encoding = feature_extractor(multi_html_strings)
>>> print(encoding.keys())
>>> ```

## [](#transformers.MarkupLMTokenizer)MarkupLMTokenizer

### class transformers.MarkupLMTokenizer

[](#transformers.MarkupLMTokenizer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm.py#L145)

( vocab\_filemerges\_filetags\_dicterrors = 'replace'bos\_token = '
'eos\_token = '
'sep\_token = '
'cls\_token = '
'unk\_token = '<unk>'pad\_token = '<pad>'mask\_token = '<mask>'add\_prefix\_space = Falsemax\_depth = 50max\_width = 1000pad\_width = 1001pad\_token\_label = -100only\_label\_first\_subword = True\*\*kwargs )

Construct a MarkupLM tokenizer. Based on byte-level Byte-Pair-Encoding (BPE). [MarkupLMTokenizer](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizer) can be used to turn HTML strings into to token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and `xpath_tags_seq`. This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

#### build\_inputs\_with\_special\_tokens

[](#transformers.MarkupLMTokenizer.build_inputs_with_special_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm.py#L423)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.MarkupLMTokenizer.build_inputs_with_special_tokens.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs to which the special tokens will be added.
-   [](#transformers.MarkupLMTokenizer.build_inputs_with_special_tokens.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [input IDs](../glossary#input-ids) with the appropriate special tokens.

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoBERTa sequence has the following format:

-   single sequence: `
 X 
`
-   pair of sequences: `
 A 

 B 
`

#### get\_special\_tokens\_mask

[](#transformers.MarkupLMTokenizer.get_special_tokens_mask)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm.py#L462)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = Nonealready\_has\_special\_tokens: bool = False ) → `List[int]`

Parameters

-   [](#transformers.MarkupLMTokenizer.get_special_tokens_mask.Retrieve)**Retrieve** sequence ids from a token list that has no special tokens added. This method is called when adding —
-   [](#transformers.MarkupLMTokenizer.get_special_tokens_mask.special)**special** tokens using the tokenizer `prepare_for_model` method. — token\_ids\_0 (`List[int]`): List of IDs. token\_ids\_1 (`List[int]`, _optional_): Optional second list of IDs for sequence pairs. already\_has\_special\_tokens (`bool`, _optional_, defaults to `False`): Whether or not the token list is already formatted with special tokens for the model.

A list of integers in the range \[0, 1\]: 1 for a special token, 0 for a sequence token.

#### create\_token\_type\_ids\_from\_sequences

[](#transformers.MarkupLMTokenizer.create_token_type_ids_from_sequences)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm.py#L487)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.MarkupLMTokenizer.create_token_type_ids_from_sequences.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs.
-   [](#transformers.MarkupLMTokenizer.create_token_type_ids_from_sequences.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of zeros.

Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not make use of token type ids, therefore a list of zeros is returned.

#### save\_vocabulary

[](#transformers.MarkupLMTokenizer.save_vocabulary)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm.py#L386)

( save\_directory: strfilename\_prefix: typing.Optional\[str\] = None )

## [](#transformers.MarkupLMTokenizerFast)MarkupLMTokenizerFast

### class transformers.MarkupLMTokenizerFast

[](#transformers.MarkupLMTokenizerFast)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm_fast.py#L99)

( vocab\_filemerges\_filetags\_dicttokenizer\_file = Noneerrors = 'replace'bos\_token = '
'eos\_token = '
'sep\_token = '
'cls\_token = '
'unk\_token = '<unk>'pad\_token = '<pad>'mask\_token = '<mask>'add\_prefix\_space = Falsemax\_depth = 50max\_width = 1000pad\_width = 1001pad\_token\_label = -100only\_label\_first\_subword = Truetrim\_offsets = False\*\*kwargs )

Construct a MarkupLM tokenizer. Based on byte-level Byte-Pair-Encoding (BPE).

[MarkupLMTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizerFast) can be used to turn HTML strings into to token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and `xpath_tags_seq`. This tokenizer inherits from [PreTrainedTokenizer](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizer) which contains most of the main methods.

Users should refer to this superclass for more information regarding those methods.

#### batch\_encode\_plus

[](#transformers.MarkupLMTokenizerFast.batch_encode_plus)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm_fast.py#L429)

( batch\_text\_or\_text\_pairs: typing.Union\[typing.List\[str\], typing.List\[typing.Tuple\[str, str\]\], typing.List\[typing.List\[str\]\]\]is\_pair: bool = Nonexpaths: typing.Optional\[typing.List\[typing.List\[typing.List\[int\]\]\]\] = Nonenode\_labels: typing.Union\[typing.List\[int\], typing.List\[typing.List\[int\]\], NoneType\] = Noneadd\_special\_tokens: bool = Truepadding: typing.Union\[bool, str, transformers.utils.generic.PaddingStrategy\] = Falsetruncation: typing.Union\[bool, str, transformers.tokenization\_utils\_base.TruncationStrategy\] = Nonemax\_length: typing.Optional\[int\] = Nonestride: int = 0pad\_to\_multiple\_of: typing.Optional\[int\] = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType\] = Nonereturn\_token\_type\_ids: typing.Optional\[bool\] = Nonereturn\_attention\_mask: typing.Optional\[bool\] = Nonereturn\_overflowing\_tokens: bool = Falsereturn\_special\_tokens\_mask: bool = Falsereturn\_offsets\_mapping: bool = Falsereturn\_length: bool = Falseverbose: bool = True\*\*kwargs )

add\_special\_tokens (`bool`, _optional_, defaults to `True`): Whether or not to encode the sequences with the special tokens relative to their model. padding (`bool`, `str` or [PaddingStrategy](/docs/transformers/v4.30.0/en/internal/file_utils#transformers.utils.PaddingStrategy), _optional_, defaults to `False`): Activates and controls padding. Accepts the following values:

-   `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    
-   `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided.
    
-   `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [TruncationStrategy](/docs/transformers/v4.30.0/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy), _optional_, defaults to `False`): Activates and controls truncation. Accepts the following values:
    
-   `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    
-   `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    
-   `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    
-   `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max\_length (`int`, _optional_): Controls the maximum length to use by one of the truncation/padding parameters.
    

If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. stride (`int`, _optional_, defaults to 0): If set to a number along with `max_length`, the overflowing tokens returned when `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence returned to provide some overlap between truncated and overflowing sequences. The value of this argument defines the number of overlapping tokens. is\_split\_into\_words (`bool`, _optional_, defaults to `False`): Whether or not the input is already pre-tokenized (e.g., split into words). If set to `True`, the tokenizer assumes the input is already split into words (for instance, by splitting it on whitespace) which it will tokenize. This is useful for NER or token classification. pad\_to\_multiple\_of (`int`, _optional_): If set will pad the sequence to a multiple of the provided value. Requires `padding` to be activated. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). return\_tensors (`str` or [TensorType](/docs/transformers/v4.30.0/en/internal/file_utils#transformers.TensorType), _optional_): If set, will return tensors instead of list of python integers. Acceptable values are:

-   `'tf'`: Return TensorFlow `tf.constant` objects.
-   `'pt'`: Return PyTorch `torch.Tensor` objects.
-   `'np'`: Return Numpy `np.ndarray` objects.

add\_special\_tokens (`bool`, _optional_, defaults to `True`): Whether or not to encode the sequences with the special tokens relative to their model. padding (`bool`, `str` or [PaddingStrategy](/docs/transformers/v4.30.0/en/internal/file_utils#transformers.utils.PaddingStrategy), _optional_, defaults to `False`): Activates and controls padding. Accepts the following values:

-   `True` or `'longest'`: Pad to the longest sequence in the batch (or no padding if only a single sequence if provided).
    
-   `'max_length'`: Pad to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided.
    
-   `False` or `'do_not_pad'` (default): No padding (i.e., can output a batch with sequences of different lengths). truncation (`bool`, `str` or [TruncationStrategy](/docs/transformers/v4.30.0/en/internal/tokenization_utils#transformers.tokenization_utils_base.TruncationStrategy), _optional_, defaults to `False`): Activates and controls truncation. Accepts the following values:
    
-   `True` or `'longest_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will truncate token by token, removing a token from the longest sequence in the pair if a pair of sequences (or a batch of pairs) is provided.
    
-   `'only_first'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the first sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    
-   `'only_second'`: Truncate to a maximum length specified with the argument `max_length` or to the maximum acceptable input length for the model if that argument is not provided. This will only truncate the second sequence of a pair if a pair of sequences (or a batch of pairs) is provided.
    
-   `False` or `'do_not_truncate'` (default): No truncation (i.e., can output batch with sequence lengths greater than the model maximum admissible input size). max\_length (`int`, _optional_): Controls the maximum length to use by one of the truncation/padding parameters. If left unset or set to `None`, this will use the predefined model maximum length if a maximum length is required by one of the truncation/padding parameters. If the model has no specific maximum input length (like XLNet) truncation/padding to a maximum length will be deactivated. stride (`int`, _optional_, defaults to 0): If set to a number along with `max_length`, the overflowing tokens returned when `return_overflowing_tokens=True` will contain some tokens from the end of the truncated sequence returned to provide some overlap between truncated and overflowing sequences. The value of this argument defines the number of overlapping tokens. pad\_to\_multiple\_of (`int`, _optional_): If set will pad the sequence to a multiple of the provided value. This is especially useful to enable the use of Tensor Cores on NVIDIA hardware with compute capability `>= 7.5` (Volta). return\_tensors (`str` or [TensorType](/docs/transformers/v4.30.0/en/internal/file_utils#transformers.TensorType), _optional_): If set, will return tensors instead of list of python integers. Acceptable values are:
    
-   `'tf'`: Return TensorFlow `tf.constant` objects.
    
-   `'pt'`: Return PyTorch `torch.Tensor` objects.
    
-   `'np'`: Return Numpy `np.ndarray` objects.
    

#### build\_inputs\_with\_special\_tokens

[](#transformers.MarkupLMTokenizerFast.build_inputs_with_special_tokens)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm_fast.py#L879)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.MarkupLMTokenizerFast.build_inputs_with_special_tokens.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs to which the special tokens will be added.
-   [](#transformers.MarkupLMTokenizerFast.build_inputs_with_special_tokens.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of [input IDs](../glossary#input-ids) with the appropriate special tokens.

Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A RoBERTa sequence has the following format:

-   single sequence: `
 X 
`
-   pair of sequences: `
 A 

 B 
`

#### create\_token\_type\_ids\_from\_sequences

[](#transformers.MarkupLMTokenizerFast.create_token_type_ids_from_sequences)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm_fast.py#L902)

( token\_ids\_0: typing.List\[int\]token\_ids\_1: typing.Optional\[typing.List\[int\]\] = None ) → `List[int]`

Parameters

-   [](#transformers.MarkupLMTokenizerFast.create_token_type_ids_from_sequences.token_ids_0)**token\_ids\_0** (`List[int]`) — List of IDs.
-   [](#transformers.MarkupLMTokenizerFast.create_token_type_ids_from_sequences.token_ids_1)**token\_ids\_1** (`List[int]`, _optional_) — Optional second list of IDs for sequence pairs.

List of zeros.

Create a mask from the two sequences passed to be used in a sequence-pair classification task. RoBERTa does not make use of token type ids, therefore a list of zeros is returned.

#### encode\_plus

[](#transformers.MarkupLMTokenizerFast.encode_plus)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/tokenization_markuplm_fast.py#L496)

( text: typing.Union\[str, typing.List\[str\]\]text\_pair: typing.Optional\[typing.List\[str\]\] = Nonexpaths: typing.Optional\[typing.List\[typing.List\[int\]\]\] = Nonenode\_labels: typing.Optional\[typing.List\[int\]\] = Noneadd\_special\_tokens: bool = Truepadding: typing.Union\[bool, str, transformers.utils.generic.PaddingStrategy\] = Falsetruncation: typing.Union\[bool, str, transformers.tokenization\_utils\_base.TruncationStrategy\] = Nonemax\_length: typing.Optional\[int\] = Nonestride: int = 0pad\_to\_multiple\_of: typing.Optional\[int\] = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType\] = Nonereturn\_token\_type\_ids: typing.Optional\[bool\] = Nonereturn\_attention\_mask: typing.Optional\[bool\] = Nonereturn\_overflowing\_tokens: bool = Falsereturn\_special\_tokens\_mask: bool = Falsereturn\_offsets\_mapping: bool = Falsereturn\_length: bool = Falseverbose: bool = True\*\*kwargs )

Tokenize and prepare for the model a sequence or a pair of sequences. .. warning:: This method is deprecated, `__call__` should be used instead.

Given the xpath expression of one particular node (like “/html/body/div/li\[1\]/div/span\[2\]”), return a list of tag IDs and corresponding subscripts, taking into account max depth.

## [](#transformers.MarkupLMProcessor)MarkupLMProcessor

### class transformers.MarkupLMProcessor

[](#transformers.MarkupLMProcessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/processing_markuplm.py#L25)

( \*args\*\*kwargs )

Parameters

-   [](#transformers.MarkupLMProcessor.feature_extractor)**feature\_extractor** (`MarkupLMFeatureExtractor`) — An instance of [MarkupLMFeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMFeatureExtractor). The feature extractor is a required input.
-   [](#transformers.MarkupLMProcessor.tokenizer)**tokenizer** (`MarkupLMTokenizer` or `MarkupLMTokenizerFast`) — An instance of [MarkupLMTokenizer](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizer) or [MarkupLMTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizerFast). The tokenizer is a required input.
-   [](#transformers.MarkupLMProcessor.parse_html)**parse\_html** (`bool`, _optional_, defaults to `True`) — Whether or not to use `MarkupLMFeatureExtractor` to parse HTML strings into nodes and corresponding xpaths.

Constructs a MarkupLM processor which combines a MarkupLM feature extractor and a MarkupLM tokenizer into a single processor.

[MarkupLMProcessor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMProcessor) offers all the functionalities you need to prepare data for the model.

It first uses [MarkupLMFeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMFeatureExtractor) to extract nodes and corresponding xpaths from one or more HTML strings. Next, these are provided to [MarkupLMTokenizer](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizer) or [MarkupLMTokenizerFast](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMTokenizerFast), which turns them into token-level `input_ids`, `attention_mask`, `token_type_ids`, `xpath_tags_seq` and `xpath_subs_seq`.

#### \_\_call\_\_

[](#transformers.MarkupLMProcessor.__call__)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/processing_markuplm.py#L48)

( html\_strings = Nonenodes = Nonexpaths = Nonenode\_labels = Nonequestions = Noneadd\_special\_tokens: bool = Truepadding: typing.Union\[bool, str, transformers.utils.generic.PaddingStrategy\] = Falsetruncation: typing.Union\[bool, str, transformers.tokenization\_utils\_base.TruncationStrategy\] = Nonemax\_length: typing.Optional\[int\] = Nonestride: int = 0pad\_to\_multiple\_of: typing.Optional\[int\] = Nonereturn\_token\_type\_ids: typing.Optional\[bool\] = Nonereturn\_attention\_mask: typing.Optional\[bool\] = Nonereturn\_overflowing\_tokens: bool = Falsereturn\_special\_tokens\_mask: bool = Falsereturn\_offsets\_mapping: bool = Falsereturn\_length: bool = Falseverbose: bool = Truereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType\] = None\*\*kwargs )

This method first forwards the `html_strings` argument to [**call**()](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMFeatureExtractor.__call__). Next, it passes the `nodes` and `xpaths` along with the additional arguments to `__call__()` and returns the output.

Optionally, one can also provide a `text` argument which is passed along as first sequence.

Please refer to the docstring of the above two methods for more information.

## [](#transformers.MarkupLMModel)MarkupLMModel

### class transformers.MarkupLMModel

[](#transformers.MarkupLMModel)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L806)

( configadd\_pooling\_layer = True )

Parameters

-   [](#transformers.MarkupLMModel.config)**config** ([MarkupLMConfig](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

The bare MarkupLM Model transformer outputting raw hidden-states without any specific head on top. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.MarkupLMModel.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L834)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonexpath\_tags\_seq: typing.Optional\[torch.LongTensor\] = Nonexpath\_subs\_seq: typing.Optional\[torch.LongTensor\] = Noneattention\_mask: typing.Optional\[torch.FloatTensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.LongTensor\] = Noneposition\_ids: typing.Optional\[torch.LongTensor\] = Nonehead\_mask: typing.Optional\[torch.FloatTensor\] = Noneinputs\_embeds: typing.Optional\[torch.FloatTensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.modeling\_outputs.BaseModelOutputWithPoolingAndCrossAttentions](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.BaseModelOutputWithPoolingAndCrossAttentions) or `tuple(torch.FloatTensor)`

The [MarkupLMModel](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMModel) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoProcessor, MarkupLMModel

>>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
>>> model = MarkupLMModel.from_pretrained("microsoft/markuplm-base")

>>> html_string = "<html> <head> <title>Page Title</title> </head> </html>"

>>> encoding = processor(html_string, return_tensors="pt")

>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state
>>> list(last_hidden_states.shape)
[1, 4, 768]```

## [](#transformers.MarkupLMForSequenceClassification)MarkupLMForSequenceClassification

### class transformers.MarkupLMForSequenceClassification

[](#transformers.MarkupLMForSequenceClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L1201)

( config )

Parameters

-   [](#transformers.MarkupLMForSequenceClassification.config)**config** ([MarkupLMConfig](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

MarkupLM Model transformer with a sequence classification/regression head on top (a linear layer on top of the pooled output) e.g. for GLUE tasks.

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.MarkupLMForSequenceClassification.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L1218)

( input\_ids: typing.Optional\[torch.Tensor\] = Nonexpath\_tags\_seq: typing.Optional\[torch.Tensor\] = Nonexpath\_subs\_seq: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.Tensor\] = Noneposition\_ids: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneinputs\_embeds: typing.Optional\[torch.Tensor\] = Nonelabels: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.modeling\_outputs.SequenceClassifierOutput](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.SequenceClassifierOutput) or `tuple(torch.FloatTensor)`

The [MarkupLMForSequenceClassification](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMForSequenceClassification) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoProcessor, AutoModelForSequenceClassification
>>> import torch

>>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
>>> model = AutoModelForSequenceClassification.from_pretrained("microsoft/markuplm-base", num_labels=7)

>>> html_string = "<html> <head> <title>Page Title</title> </head> </html>"
>>> encoding = processor(html_string, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**encoding)

>>> loss = outputs.loss
>>> logits = outputs.logits```

## [](#transformers.MarkupLMForTokenClassification)MarkupLMForTokenClassification

### class transformers.MarkupLMForTokenClassification

[](#transformers.MarkupLMForTokenClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L1095)

( config )

Parameters

-   [](#transformers.MarkupLMForTokenClassification.config)**config** ([MarkupLMConfig](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

MarkupLM Model with a `token_classification` head on top. This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.MarkupLMForTokenClassification.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L1111)

( input\_ids: typing.Optional\[torch.Tensor\] = Nonexpath\_tags\_seq: typing.Optional\[torch.Tensor\] = Nonexpath\_subs\_seq: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.Tensor\] = Noneposition\_ids: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneinputs\_embeds: typing.Optional\[torch.Tensor\] = Nonelabels: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.modeling\_outputs.MaskedLMOutput](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.MaskedLMOutput) or `tuple(torch.FloatTensor)`

The [MarkupLMForTokenClassification](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMForTokenClassification) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoProcessor, AutoModelForTokenClassification
>>> import torch

>>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base")
>>> processor.parse_html = False
>>> model = AutoModelForTokenClassification.from_pretrained("microsoft/markuplm-base", num_labels=7)

>>> nodes = ["hello", "world"]
>>> xpaths = ["/html/body/div/li[1]/div/span", "/html/body/div/li[1]/div/span"]
>>> node_labels = [1, 2]
>>> encoding = processor(nodes=nodes, xpaths=xpaths, node_labels=node_labels, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**encoding)

>>> loss = outputs.loss
>>> logits = outputs.logits```

## [](#transformers.MarkupLMForQuestionAnswering)MarkupLMForQuestionAnswering

### class transformers.MarkupLMForQuestionAnswering

[](#transformers.MarkupLMForQuestionAnswering)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L973)

( config )

Parameters

-   [](#transformers.MarkupLMForQuestionAnswering.config)**config** ([MarkupLMConfig](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMConfig)) — Model configuration class with all the parameters of the model. Initializing with a config file does not load the weights associated with the model, only the configuration. Check out the [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained) method to load the model weights.

MarkupLM Model with a span classification head on top for extractive question-answering tasks like SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).

This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and behavior.

#### forward

[](#transformers.MarkupLMForQuestionAnswering.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/markuplm/modeling_markuplm.py#L987)

( input\_ids: typing.Optional\[torch.Tensor\] = Nonexpath\_tags\_seq: typing.Optional\[torch.Tensor\] = Nonexpath\_subs\_seq: typing.Optional\[torch.Tensor\] = Noneattention\_mask: typing.Optional\[torch.Tensor\] = Nonetoken\_type\_ids: typing.Optional\[torch.Tensor\] = Noneposition\_ids: typing.Optional\[torch.Tensor\] = Nonehead\_mask: typing.Optional\[torch.Tensor\] = Noneinputs\_embeds: typing.Optional\[torch.Tensor\] = Nonestart\_positions: typing.Optional\[torch.Tensor\] = Noneend\_positions: typing.Optional\[torch.Tensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.modeling\_outputs.QuestionAnsweringModelOutput](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.QuestionAnsweringModelOutput) or `tuple(torch.FloatTensor)`

The [MarkupLMForQuestionAnswering](/docs/transformers/v4.30.0/en/model_doc/markuplm#transformers.MarkupLMForQuestionAnswering) forward method, overrides the `__call__` special method.

Although the recipe for forward pass needs to be defined within this function, one should call the `Module` instance afterwards instead of this since the former takes care of running the pre and post processing steps while the latter silently ignores them.

Examples:

```
>>> from transformers import AutoProcessor, MarkupLMForQuestionAnswering
>>> import torch

>>> processor = AutoProcessor.from_pretrained("microsoft/markuplm-base-finetuned-websrc")
>>> model = MarkupLMForQuestionAnswering.from_pretrained("microsoft/markuplm-base-finetuned-websrc")

>>> html_string = "<html> <head> <title>My name is Niels</title> </head> </html>"
>>> question = "What's his name?"

>>> encoding = processor(html_string, questions=question, return_tensors="pt")

>>> with torch.no_grad():
...     outputs = model(**encoding)

>>> answer_start_index = outputs.start_logits.argmax()
>>> answer_end_index = outputs.end_logits.argmax()

>>> predict_answer_tokens = encoding.input_ids[0, answer_start_index : answer_end_index + 1]
>>> processor.decode(predict_answer_tokens).strip()
'Niels'```