LayoutLMV2

## [](#overview)Overview

The LayoutLMV2 model was proposed in [LayoutLMv2: Multi-modal Pre-training for Visually-Rich Document Understanding](https://arxiv.org/abs/2012.14740) by Yang Xu, Yiheng Xu, Tengchao Lv, Lei Cui, Furu Wei, Guoxin Wang, Yijuan Lu, Dinei Florencio, Cha Zhang, Wanxiang Che, Min Zhang, Lidong Zhou. LayoutLMV2 improves [LayoutLM](layoutlm) to obtain state-of-the-art results across several document image understanding benchmarks:

-   information extraction from scanned documents: the [FUNSD](https://guillaumejaume.github.io/FUNSD/) dataset (a collection of 199 annotated forms comprising more than 30,000 words), the [CORD](https://github.com/clovaai/cord) dataset (a collection of 800 receipts for training, 100 for validation and 100 for testing), the [SROIE](https://rrc.cvc.uab.es/?ch=13) dataset (a collection of 626 receipts for training and 347 receipts for testing) and the [Kleister-NDA](https://github.com/applicaai/kleister-nda) dataset (a collection of non-disclosure agreements from the EDGAR database, including 254 documents for training, 83 documents for validation, and 203 documents for testing).
-   document image classification: the [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset (a collection of 400,000 images belonging to one of 16 classes).
-   document visual question answering: the [DocVQA](https://arxiv.org/abs/2007.00398) dataset (a collection of 50,000 questions defined on 12,000+ document images).

The abstract from the paper is the following:

_Pre-training of text and layout has proved effective in a variety of visually-rich document understanding tasks due to its effective model architecture and the advantage of large-scale unlabeled scanned/digital-born documents. In this paper, we present LayoutLMv2 by pre-training text, layout and image in a multi-modal framework, where new model architectures and pre-training tasks are leveraged. Specifically, LayoutLMv2 not only uses the existing masked visual-language modeling task but also the new text-image alignment and text-image matching tasks in the pre-training stage, where cross-modality interaction is better learned. Meanwhile, it also integrates a spatial-aware self-attention mechanism into the Transformer architecture, so that the model can fully understand the relative positional relationship among different text blocks. Experiment results show that LayoutLMv2 outperforms strong baselines and achieves new state-of-the-art results on a wide variety of downstream visually-rich document understanding tasks, including FUNSD (0.7895 -> 0.8420), CORD (0.9493 -> 0.9601), SROIE (0.9524 -> 0.9781), Kleister-NDA (0.834 -> 0.852), RVL-CDIP (0.9443 -> 0.9564), and DocVQA (0.7295 -> 0.8672). The pre-trained LayoutLMv2 model is publicly available at this https URL._

LayoutLMv2 depends on `detectron2`, `torchvision` and `tesseract`. Run the following to install them:

```
python -m pip install 'git+https://github.com/facebookresearch/detectron2.git'
python -m pip install torchvision tesseract```

(If you are developing for LayoutLMv2, note that passing the doctests also requires the installation of these packages.)

Tips:

-   The main difference between LayoutLMv1 and LayoutLMv2 is that the latter incorporates visual embeddings during pre-training (while LayoutLMv1 only adds visual embeddings during fine-tuning).
-   LayoutLMv2 adds both a relative 1D attention bias as well as a spatial 2D attention bias to the attention scores in the self-attention layers. Details can be found on page 5 of the [paper](https://arxiv.org/abs/2012.14740).
-   Demo notebooks on how to use the LayoutLMv2 model on RVL-CDIP, FUNSD, DocVQA, CORD can be found [here](https://github.com/NielsRogge/Transformers-Tutorials).
-   LayoutLMv2 uses Facebook AI’s [Detectron2](https://github.com/facebookresearch/detectron2/) package for its visual backbone. See [this link](https://detectron2.readthedocs.io/en/latest/tutorials/install.html) for installation instructions.
-   In addition to `input_ids`, [forward()](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Model.forward) expects 2 additional inputs, namely `image` and `bbox`. The `image` input corresponds to the original document image in which the text tokens occur. The model expects each document image to be of size 224x224. This means that if you have a batch of document images, `image` should be a tensor of shape (batch\_size, 3, 224, 224). This can be either a `torch.Tensor` or a `Detectron2.structures.ImageList`. You don’t need to normalize the channels, as this is done by the model. Important to note is that the visual backbone expects BGR channels instead of RGB, as all models in Detectron2 are pre-trained using the BGR format. The `bbox` input are the bounding boxes (i.e. 2D-positions) of the input text tokens. This is identical to [LayoutLMModel](/docs/transformers/v4.30.0/en/model_doc/layoutlm#transformers.LayoutLMModel). These can be obtained using an external OCR engine such as Google’s [Tesseract](https://github.com/tesseract-ocr/tesseract) (there’s a [Python wrapper](https://pypi.org/project/pytesseract/) available). Each bounding box should be in (x0, y0, x1, y1) format, where (x0, y0) corresponds to the position of the upper left corner in the bounding box, and (x1, y1) represents the position of the lower right corner. Note that one first needs to normalize the bounding boxes to be on a 0-1000 scale. To normalize, you can use the following function:

```
def normalize_bbox(bbox, width, height):
    return [
        int(1000 * (bbox[0] / width)),
        int(1000 * (bbox[1] / height)),
        int(1000 * (bbox[2] / width)),
        int(1000 * (bbox[3] / height)),
    ]```

Here, `width` and `height` correspond to the width and height of the original document in which the token occurs (before resizing the image). Those can be obtained using the Python Image Library (PIL) library for example, as follows:

```
from PIL import Image

image = Image.open(
    "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
)

width, height = image.size```

However, this model includes a brand new [LayoutLMv2Processor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Processor) which can be used to directly prepare data for the model (including applying OCR under the hood). More information can be found in the “Usage” section below.

-   Internally, [LayoutLMv2Model](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Model) will send the `image` input through its visual backbone to obtain a lower-resolution feature map, whose shape is equal to the `image_feature_pool_shape` attribute of [LayoutLMv2Config](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Config). This feature map is then flattened to obtain a sequence of image tokens. As the size of the feature map is 7x7 by default, one obtains 49 image tokens. These are then concatenated with the text tokens, and send through the Transformer encoder. This means that the last hidden states of the model will have a length of 512 + 49 = 561, if you pad the text tokens up to the max length. More generally, the last hidden states will have a shape of `seq_length` + `image_feature_pool_shape[0]` \* `config.image_feature_pool_shape[1]`.
-   When calling [from\_pretrained()](/docs/transformers/v4.30.0/en/main_classes/model#transformers.PreTrainedModel.from_pretrained), a warning will be printed with a long list of parameter names that are not initialized. This is not a problem, as these parameters are batch normalization statistics, which are going to have values when fine-tuning on a custom dataset.
-   If you want to train the model in a distributed environment, make sure to call `synchronize_batch_norm` on the model in order to properly synchronize the batch normalization layers of the visual backbone.

In addition, there’s LayoutXLM, which is a multilingual version of LayoutLMv2. More information can be found on [LayoutXLM’s documentation page](layoutxlm).

## [](#resources)Resources

A list of official Hugging Face and community (indicated by 🌎) resources to help you get started with LayoutLMv2. If you’re interested in submitting a resource to be included here, please feel free to open a Pull Request and we’ll review it! The resource should ideally demonstrate something new instead of duplicating an existing resource.

-   A notebook on how to [finetune LayoutLMv2 for text-classification on RVL-CDIP dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/RVL-CDIP/Fine_tuning_LayoutLMv2ForSequenceClassification_on_RVL_CDIP.ipynb).
-   See also: [Text classification task guide](../tasks/sequence_classification)

-   A notebook on how to [finetune LayoutLMv2 for question-answering on DocVQA dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/DocVQA/Fine_tuning_LayoutLMv2ForQuestionAnswering_on_DocVQA.ipynb).
-   See also: [Question answering task guide](../tasks/question_answering)
-   See also: [Document question answering task guide](../tasks/document_question_answering)

-   A notebook on how to [finetune LayoutLMv2 for token-classification on CORD dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/CORD/Fine_tuning_LayoutLMv2ForTokenClassification_on_CORD.ipynb).
-   A notebook on how to [finetune LayoutLMv2 for token-classification on FUNSD dataset](https://colab.research.google.com/github/NielsRogge/Transformers-Tutorials/blob/master/LayoutLMv2/FUNSD/Fine_tuning_LayoutLMv2ForTokenClassification_on_FUNSD_using_HuggingFace_Trainer.ipynb).
-   See also: [Token classification task guide](../tasks/token_classification)

## [](#usage-layoutlmv2processor)Usage: LayoutLMv2Processor

The easiest way to prepare data for the model is to use [LayoutLMv2Processor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Processor), which internally combines a feature extractor ([LayoutLMv2FeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2FeatureExtractor)) and a tokenizer ([LayoutLMv2Tokenizer](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer) or [LayoutLMv2TokenizerFast](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2TokenizerFast)). The feature extractor handles the image modality, while the tokenizer handles the text modality. A processor combines both, which is ideal for a multi-modal model like LayoutLMv2. Note that you can still use both separately, if you only want to handle one modality.

```
from transformers import LayoutLMv2FeatureExtractor, LayoutLMv2TokenizerFast, LayoutLMv2Processor

feature_extractor = LayoutLMv2FeatureExtractor()  
tokenizer = LayoutLMv2TokenizerFast.from_pretrained("microsoft/layoutlmv2-base-uncased")
processor = LayoutLMv2Processor(feature_extractor, tokenizer)```

In short, one can provide a document image (and possibly additional data) to [LayoutLMv2Processor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Processor), and it will create the inputs expected by the model. Internally, the processor first uses [LayoutLMv2FeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2FeatureExtractor) to apply OCR on the image to get a list of words and normalized bounding boxes, as well to resize the image to a given size in order to get the `image` input. The words and normalized bounding boxes are then provided to [LayoutLMv2Tokenizer](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer) or [LayoutLMv2TokenizerFast](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2TokenizerFast), which converts them to token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`. Optionally, one can provide word labels to the processor, which are turned into token-level `labels`.

[LayoutLMv2Processor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Processor) uses [PyTesseract](https://pypi.org/project/pytesseract/), a Python wrapper around Google’s Tesseract OCR engine, under the hood. Note that you can still use your own OCR engine of choice, and provide the words and normalized boxes yourself. This requires initializing [LayoutLMv2FeatureExtractor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2FeatureExtractor) with `apply_ocr` set to `False`.

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: document image classification (training, inference) + token classification (inference), apply\_ocr = True**

This is the simplest case, in which the processor (actually the feature extractor) will perform OCR on the image to get the words and normalized bounding boxes.

```
from transformers import LayoutLMv2Processor
from PIL import Image

processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")

image = Image.open(
    "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
encoding = processor(
    image, return_tensors="pt"
)  
print(encoding.keys())
```

**Use case 2: document image classification (training, inference) + token classification (inference), apply\_ocr=False**

In case one wants to do OCR themselves, one can initialize the feature extractor with `apply_ocr` set to `False`. In that case, one should provide the words and corresponding (normalized) bounding boxes themselves to the processor.

```
from transformers import LayoutLMv2Processor
from PIL import Image

processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")

image = Image.open(
    "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
words = ["hello", "world"]
boxes = [[1, 2, 3, 4], [5, 6, 7, 8]]  
encoding = processor(image, words, boxes=boxes, return_tensors="pt")
print(encoding.keys())
```

**Use case 3: token classification (training), apply\_ocr=False**

For token classification tasks (such as FUNSD, CORD, SROIE, Kleister-NDA), one can also provide the corresponding word 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 LayoutLMv2Processor
from PIL import Image

processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")

image = Image.open(
    "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
words = ["hello", "world"]
boxes = [[1, 2, 3, 4], [5, 6, 7, 8]]  
word_labels = [1, 2]
encoding = processor(image, words, boxes=boxes, word_labels=word_labels, return_tensors="pt")
print(encoding.keys())
```

**Use case 4: visual question answering (inference), apply\_ocr=True**

For visual question answering tasks (such as DocVQA), you can provide a question to the processor. By default, the processor will apply OCR on the image, and create \[CLS\] question tokens \[SEP\] word tokens \[SEP\].

```
from transformers import LayoutLMv2Processor
from PIL import Image

processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased")

image = Image.open(
    "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
question = "What's his name?"
encoding = processor(image, question, return_tensors="pt")
print(encoding.keys())
```

**Use case 5: visual question answering (inference), apply\_ocr=False**

For visual question answering tasks (such as DocVQA), you can provide a question to the processor. If you want to perform OCR yourself, you can provide your own words and (normalized) bounding boxes to the processor.

```
from transformers import LayoutLMv2Processor
from PIL import Image

processor = LayoutLMv2Processor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")

image = Image.open(
    "name_of_your_document - can be a png, jpg, etc. of your documents (PDFs must be converted to images)."
).convert("RGB")
question = "What's his name?"
words = ["hello", "world"]
boxes = [[1, 2, 3, 4], [5, 6, 7, 8]]  
encoding = processor(image, question, words, boxes=boxes, return_tensors="pt")
print(encoding.keys())
```

## [](#transformers.LayoutLMv2Config)LayoutLMv2Config

### class transformers.LayoutLMv2Config

[](#transformers.LayoutLMv2Config)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/configuration_layoutlmv2.py#L34)

( 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 = 0max\_2d\_position\_embeddings = 1024max\_rel\_pos = 128rel\_pos\_bins = 32fast\_qkv = Truemax\_rel\_2d\_pos = 256rel\_2d\_pos\_bins = 64convert\_sync\_batchnorm = Trueimage\_feature\_pool\_shape = \[7, 7, 256\]coordinate\_size = 128shape\_size = 128has\_relative\_attention\_bias = Truehas\_spatial\_attention\_bias = Truehas\_visual\_segment\_embedding = Falsedetectron2\_config\_args = None\*\*kwargs )

This is the configuration class to store the configuration of a [LayoutLMv2Model](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Model). It is used to instantiate an LayoutLMv2 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 LayoutLMv2 [microsoft/layoutlmv2-base-uncased](https://huggingface.co/microsoft/layoutlmv2-base-uncased) architecture.

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

Example:

```
>>> from transformers import LayoutLMv2Config, LayoutLMv2Model

>>> 
>>> configuration = LayoutLMv2Config()

>>> 
>>> model = LayoutLMv2Model(configuration)

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

## [](#transformers.LayoutLMv2FeatureExtractor)LayoutLMv2FeatureExtractor

Preprocess an image or a batch of images.

## [](#transformers.LayoutLMv2ImageProcessor)LayoutLMv2ImageProcessor

### class transformers.LayoutLMv2ImageProcessor

[](#transformers.LayoutLMv2ImageProcessor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/image_processing_layoutlmv2.py#L87)

( do\_resize: bool = Truesize: typing.Dict\[str, int\] = Noneresample: Resampling = <Resampling.BILINEAR: 2>apply\_ocr: bool = Trueocr\_lang: typing.Optional\[str\] = Nonetesseract\_config: typing.Optional\[str\] = ''\*\*kwargs )

Constructs a LayoutLMv2 image processor.

#### preprocess

[](#transformers.LayoutLMv2ImageProcessor.preprocess)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/image_processing_layoutlmv2.py#L161)

( images: typing.Union\[ForwardRef('PIL.Image.Image'), numpy.ndarray, ForwardRef('torch.Tensor'), typing.List\[ForwardRef('PIL.Image.Image')\], typing.List\[numpy.ndarray\], typing.List\[ForwardRef('torch.Tensor')\]\]do\_resize: bool = Nonesize: typing.Dict\[str, int\] = Noneresample: Resampling = Noneapply\_ocr: bool = Noneocr\_lang: typing.Optional\[str\] = Nonetesseract\_config: typing.Optional\[str\] = Nonereturn\_tensors: typing.Union\[str, transformers.utils.generic.TensorType, NoneType\] = Nonedata\_format: ChannelDimension = <ChannelDimension.FIRST: 'channels\_first'>\*\*kwargs )

Preprocess an image or batch of images.

## [](#transformers.LayoutLMv2Tokenizer)LayoutLMv2Tokenizer

### class transformers.LayoutLMv2Tokenizer

[](#transformers.LayoutLMv2Tokenizer)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py#L206)

( vocab\_filedo\_lower\_case = Truedo\_basic\_tokenize = Truenever\_split = Noneunk\_token = '\[UNK\]'sep\_token = '\[SEP\]'pad\_token = '\[PAD\]'cls\_token = '\[CLS\]'mask\_token = '\[MASK\]'cls\_token\_box = \[0, 0, 0, 0\]sep\_token\_box = \[1000, 1000, 1000, 1000\]pad\_token\_box = \[0, 0, 0, 0\]pad\_token\_label = -100only\_label\_first\_subword = Truetokenize\_chinese\_chars = Truestrip\_accents = Nonemodel\_max\_length: int = 512additional\_special\_tokens: typing.Optional\[typing.List\[str\]\] = None\*\*kwargs )

Construct a LayoutLMv2 tokenizer. Based on WordPiece. [LayoutLMv2Tokenizer](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer) can be used to turn words, word-level bounding boxes and optional word labels to token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`, and optional `labels` (for token classification).

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.

[LayoutLMv2Tokenizer](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer) runs end-to-end tokenization: punctuation splitting and wordpiece. It also turns the word-level bounding boxes into token-level bounding boxes.

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

[](#transformers.LayoutLMv2Tokenizer.__call__)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py#L425)

( text: typing.Union\[str, typing.List\[str\], typing.List\[typing.List\[str\]\]\]text\_pair: typing.Union\[typing.List\[str\], typing.List\[typing.List\[str\]\], NoneType\] = Noneboxes: typing.Union\[typing.List\[typing.List\[int\]\], typing.List\[typing.List\[typing.List\[int\]\]\]\] = Noneword\_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 ) → [BatchEncoding](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.BatchEncoding)

Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of sequences with word-level normalized bounding boxes and optional labels.

#### save\_vocabulary

[](#transformers.LayoutLMv2Tokenizer.save_vocabulary)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/tokenization_layoutlmv2.py#L405)

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

## [](#transformers.LayoutLMv2TokenizerFast)LayoutLMv2TokenizerFast

### class transformers.LayoutLMv2TokenizerFast

[](#transformers.LayoutLMv2TokenizerFast)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py#L70)

( vocab\_file = Nonetokenizer\_file = Nonedo\_lower\_case = Trueunk\_token = '\[UNK\]'sep\_token = '\[SEP\]'pad\_token = '\[PAD\]'cls\_token = '\[CLS\]'mask\_token = '\[MASK\]'cls\_token\_box = \[0, 0, 0, 0\]sep\_token\_box = \[1000, 1000, 1000, 1000\]pad\_token\_box = \[0, 0, 0, 0\]pad\_token\_label = -100only\_label\_first\_subword = Truetokenize\_chinese\_chars = Truestrip\_accents = None\*\*kwargs )

Construct a “fast” LayoutLMv2 tokenizer (backed by HuggingFace’s _tokenizers_ library). Based on WordPiece.

This tokenizer inherits from [PreTrainedTokenizerFast](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.PreTrainedTokenizerFast) which contains most of the main methods. Users should refer to this superclass for more information regarding those methods.

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

[](#transformers.LayoutLMv2TokenizerFast.__call__)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/tokenization_layoutlmv2_fast.py#L179)

( text: typing.Union\[str, typing.List\[str\], typing.List\[typing.List\[str\]\]\]text\_pair: typing.Union\[typing.List\[str\], typing.List\[typing.List\[str\]\], NoneType\] = Noneboxes: typing.Union\[typing.List\[typing.List\[int\]\], typing.List\[typing.List\[typing.List\[int\]\]\]\] = Noneword\_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 ) → [BatchEncoding](/docs/transformers/v4.30.0/en/main_classes/tokenizer#transformers.BatchEncoding)

Main method to tokenize and prepare for the model one or several sequence(s) or one or several pair(s) of sequences with word-level normalized bounding boxes and optional labels.

## [](#transformers.LayoutLMv2Processor)LayoutLMv2Processor

### class transformers.LayoutLMv2Processor

[](#transformers.LayoutLMv2Processor)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/processing_layoutlmv2.py#L27)

( image\_processor = Nonetokenizer = None\*\*kwargs )

Parameters

-   [](#transformers.LayoutLMv2Processor.image_processor)**image\_processor** (`LayoutLMv2ImageProcessor`) — An instance of [LayoutLMv2ImageProcessor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2ImageProcessor). The image processor is a required input.
-   [](#transformers.LayoutLMv2Processor.tokenizer)**tokenizer** (`LayoutLMv2Tokenizer` or `LayoutLMv2TokenizerFast`) — An instance of [LayoutLMv2Tokenizer](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer) or [LayoutLMv2TokenizerFast](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2TokenizerFast). The tokenizer is a required input.

Constructs a LayoutLMv2 processor which combines a LayoutLMv2 image processor and a LayoutLMv2 tokenizer into a single processor.

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

It first uses [LayoutLMv2ImageProcessor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2ImageProcessor) to resize document images to a fixed size, and optionally applies OCR to get words and normalized bounding boxes. These are then provided to [LayoutLMv2Tokenizer](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer) or [LayoutLMv2TokenizerFast](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2TokenizerFast), which turns the words and bounding boxes into token-level `input_ids`, `attention_mask`, `token_type_ids`, `bbox`. Optionally, one can provide integer `word_labels`, which are turned into token-level `labels` for token classification tasks (such as FUNSD, CORD).

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

[](#transformers.LayoutLMv2Processor.__call__)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/processing_layoutlmv2.py#L67)

( imagestext: typing.Union\[str, typing.List\[str\], typing.List\[typing.List\[str\]\]\] = Nonetext\_pair: typing.Union\[typing.List\[str\], typing.List\[typing.List\[str\]\], NoneType\] = Noneboxes: typing.Union\[typing.List\[typing.List\[int\]\], typing.List\[typing.List\[typing.List\[int\]\]\]\] = Noneword\_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\] = Falsemax\_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 `images` argument to [**call**()](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2FeatureExtractor.__call__). In case [LayoutLMv2ImageProcessor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2ImageProcessor) was initialized with `apply_ocr` set to `True`, it passes the obtained words and bounding boxes along with the additional arguments to [**call**()](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer.__call__) and returns the output, together with resized `images`. In case [LayoutLMv2ImageProcessor](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2ImageProcessor) was initialized with `apply_ocr` set to `False`, it passes the words (`text`/``text_pair`) and `boxes` specified by the user along with the additional arguments to [__call__()](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Tokenizer.__call__) and returns the output, together with resized `images``.

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

## [](#transformers.LayoutLMv2Model)LayoutLMv2Model

### class transformers.LayoutLMv2Model

[](#transformers.LayoutLMv2Model)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L709)

( config )

Parameters

-   [](#transformers.LayoutLMv2Model.config)**config** ([LayoutLMv2Config](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Config)) — 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 LayoutLMv2 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.LayoutLMv2Model.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L819)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonebbox: typing.Optional\[torch.LongTensor\] = Noneimage: typing.Optional\[torch.FloatTensor\] = 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.BaseModelOutput](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.BaseModelOutput) or `tuple(torch.FloatTensor)`

The [LayoutLMv2Model](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Model) 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, LayoutLMv2Model, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset

>>> set_seed(88)

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2Model.from_pretrained("microsoft/layoutlmv2-base-uncased")


>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")

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

>>> outputs = model(**encoding)
>>> last_hidden_states = outputs.last_hidden_state

>>> last_hidden_states.shape
torch.Size([1, 342, 768])```

## [](#transformers.LayoutLMv2ForSequenceClassification)LayoutLMv2ForSequenceClassification

### class transformers.LayoutLMv2ForSequenceClassification

[](#transformers.LayoutLMv2ForSequenceClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L970)

( config )

Parameters

-   [](#transformers.LayoutLMv2ForSequenceClassification.config)**config** ([LayoutLMv2Config](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Config)) — 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.

LayoutLMv2 Model with a sequence classification head on top (a linear layer on top of the concatenation of the final hidden state of the \[CLS\] token, average-pooled initial visual embeddings and average-pooled final visual embeddings, e.g. for document image classification tasks such as the [RVL-CDIP](https://www.cs.cmu.edu/~aharley/rvl-cdip/) dataset.

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.LayoutLMv2ForSequenceClassification.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L984)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonebbox: typing.Optional\[torch.LongTensor\] = Noneimage: typing.Optional\[torch.FloatTensor\] = 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\] = Nonelabels: typing.Optional\[torch.LongTensor\] = 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 [LayoutLMv2ForSequenceClassification](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2ForSequenceClassification) 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.

Example:

```
>>> from transformers import AutoProcessor, LayoutLMv2ForSequenceClassification, set_seed
>>> from PIL import Image
>>> import torch
>>> from datasets import load_dataset

>>> set_seed(88)

>>> dataset = load_dataset("rvl_cdip", split="train", streaming=True)
>>> data = next(iter(dataset))
>>> image = data["image"].convert("RGB")

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForSequenceClassification.from_pretrained(
...     "microsoft/layoutlmv2-base-uncased", num_labels=dataset.info.features["label"].num_classes
... )

>>> encoding = processor(image, return_tensors="pt")
>>> sequence_label = torch.tensor([data["label"]])

>>> outputs = model(**encoding, labels=sequence_label)

>>> loss, logits = outputs.loss, outputs.logits
>>> predicted_idx = logits.argmax(dim=-1).item()
>>> predicted_answer = dataset.info.features["label"].names[4]
>>> predicted_idx, predicted_answer
(4, 'advertisement')```

## [](#transformers.LayoutLMv2ForTokenClassification)LayoutLMv2ForTokenClassification

### class transformers.LayoutLMv2ForTokenClassification

[](#transformers.LayoutLMv2ForTokenClassification)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L1151)

( config )

Parameters

-   [](#transformers.LayoutLMv2ForTokenClassification.config)**config** ([LayoutLMv2Config](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Config)) — 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.

LayoutLMv2 Model with a token classification head on top (a linear layer on top of the text part of the hidden states) e.g. for sequence labeling (information extraction) tasks such as [FUNSD](https://guillaumejaume.github.io/FUNSD/), [SROIE](https://rrc.cvc.uab.es/?ch=13), [CORD](https://github.com/clovaai/cord) and [Kleister-NDA](https://github.com/applicaai/kleister-nda).

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.LayoutLMv2ForTokenClassification.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L1165)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonebbox: typing.Optional\[torch.LongTensor\] = Noneimage: typing.Optional\[torch.FloatTensor\] = 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\] = Nonelabels: typing.Optional\[torch.LongTensor\] = Noneoutput\_attentions: typing.Optional\[bool\] = Noneoutput\_hidden\_states: typing.Optional\[bool\] = Nonereturn\_dict: typing.Optional\[bool\] = None ) → [transformers.modeling\_outputs.TokenClassifierOutput](/docs/transformers/v4.30.0/en/main_classes/output#transformers.modeling_outputs.TokenClassifierOutput) or `tuple(torch.FloatTensor)`

The [LayoutLMv2ForTokenClassification](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2ForTokenClassification) 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.

Example:

```
>>> from transformers import AutoProcessor, LayoutLMv2ForTokenClassification, set_seed
>>> from PIL import Image
>>> from datasets import load_dataset

>>> set_seed(88)

>>> datasets = load_dataset("nielsr/funsd", split="test")
>>> labels = datasets.features["ner_tags"].feature.names
>>> id2label = {v: k for v, k in enumerate(labels)}

>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased", revision="no_ocr")
>>> model = LayoutLMv2ForTokenClassification.from_pretrained(
...     "microsoft/layoutlmv2-base-uncased", num_labels=len(labels)
... )

>>> data = datasets[0]
>>> image = Image.open(data["image_path"]).convert("RGB")
>>> words = data["words"]
>>> boxes = data["bboxes"]  
>>> word_labels = data["ner_tags"]
>>> encoding = processor(
...     image,
...     words,
...     boxes=boxes,
...     word_labels=word_labels,
...     padding="max_length",
...     truncation=True,
...     return_tensors="pt",
... )

>>> outputs = model(**encoding)
>>> logits, loss = outputs.logits, outputs.loss

>>> predicted_token_class_ids = logits.argmax(-1)
>>> predicted_tokens_classes = [id2label[t.item()] for t in predicted_token_class_ids[0]]
>>> predicted_tokens_classes[:5]
['B-ANSWER', 'B-HEADER', 'B-HEADER', 'B-HEADER', 'B-HEADER']```

## [](#transformers.LayoutLMv2ForQuestionAnswering)LayoutLMv2ForQuestionAnswering

### class transformers.LayoutLMv2ForQuestionAnswering

[](#transformers.LayoutLMv2ForQuestionAnswering)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L1282)

( confighas\_visual\_segment\_embedding = True )

Parameters

-   [](#transformers.LayoutLMv2ForQuestionAnswering.config)**config** ([LayoutLMv2Config](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2Config)) — 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.

LayoutLMv2 Model with a span classification head on top for extractive question-answering tasks such as [DocVQA](https://rrc.cvc.uab.es/?ch=17) (a linear layer on top of the text part 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.LayoutLMv2ForQuestionAnswering.forward)[< source \>](https://github.com/huggingface/transformers/blob/v4.30.0/src/transformers/models/layoutlmv2/modeling_layoutlmv2.py#L1296)

( input\_ids: typing.Optional\[torch.LongTensor\] = Nonebbox: typing.Optional\[torch.LongTensor\] = Noneimage: typing.Optional\[torch.FloatTensor\] = 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\] = Nonestart\_positions: typing.Optional\[torch.LongTensor\] = Noneend\_positions: typing.Optional\[torch.LongTensor\] = 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 [LayoutLMv2ForQuestionAnswering](/docs/transformers/v4.30.0/en/model_doc/layoutlmv2#transformers.LayoutLMv2ForQuestionAnswering) 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.

Example:

In this example below, we give the LayoutLMv2 model an image (of texts) and ask it a question. It will give us a prediction of what it thinks the answer is (the span of the answer within the texts parsed from the image).

```
>>> from transformers import AutoProcessor, LayoutLMv2ForQuestionAnswering, set_seed
>>> import torch
>>> from PIL import Image
>>> from datasets import load_dataset

>>> set_seed(88)
>>> processor = AutoProcessor.from_pretrained("microsoft/layoutlmv2-base-uncased")
>>> model = LayoutLMv2ForQuestionAnswering.from_pretrained("microsoft/layoutlmv2-base-uncased")

>>> dataset = load_dataset("hf-internal-testing/fixtures_docvqa")
>>> image_path = dataset["test"][0]["file"]
>>> image = Image.open(image_path).convert("RGB")
>>> question = "When is coffee break?"
>>> encoding = processor(image, question, return_tensors="pt")

>>> outputs = model(**encoding)
>>> predicted_start_idx = outputs.start_logits.argmax(-1).item()
>>> predicted_end_idx = outputs.end_logits.argmax(-1).item()
>>> predicted_start_idx, predicted_end_idx
(154, 287)

>>> predicted_answer_tokens = encoding.input_ids.squeeze()[predicted_start_idx : predicted_end_idx + 1]
>>> predicted_answer = processor.tokenizer.decode(predicted_answer_tokens)
>>> predicted_answer  
'council mem - bers conducted by trrf treasurer philip g. kuehn to get answers which the public ...```

```
>>> target_start_index = torch.tensor([7])
>>> target_end_index = torch.tensor([14])
>>> outputs = model(**encoding, start_positions=target_start_index, end_positions=target_end_index)
>>> predicted_answer_span_start = outputs.start_logits.argmax(-1).item()
>>> predicted_answer_span_end = outputs.end_logits.argmax(-1).item()
>>> predicted_answer_span_start, predicted_answer_span_end
(154, 287)```