Of course! Using LayoutLMv3 to get an "image embedding" is an interesting case because, unlike a pure vision model (like ResNet or ViT), LayoutLMv3 is a multimodal model. Its primary strength is in understanding the interplay of text, its layout (position), and the visual image itself.
Therefore, the "image embedding" from LayoutLMv3 is not just a representation of the pixels, but a contextualized representation of the visual patches, influenced by the text and layout of the document.
Here's a complete example of how to do it. We'll extract the embeddings corresponding to the image patches.
Key Concepts
- Processor (
LayoutLMv3Processor): This is a handy utility from Hugging Face that combines a text tokenizer (for words) and an image feature extractor. It prepares all the different inputs (text tokens, bounding boxes, image pixels) in the format the model expects.
- Base Model (
LayoutLMv3Model): We use the base model because we want the raw outputs (the hidden states or embeddings), not the outputs from a specific task head (like Question Answering or Token Classification).
- Output Structure: The model's output
last_hidden_state contains a sequence of embeddings. This sequence is a concatenation of embeddings for the text tokens first, followed by the embeddings for the image patches. Our goal is to isolate the patch embeddings.
Step-by-Step Code Example
First, let's install the necessary libraries.
pip install transformers torch pillow requests
Now, let's write the Python code. We will use a sample invoice image for this demonstration, as it's a perfect use case for LayoutLMv3.
import torch
from PIL import Image
import requests
from transformers import LayoutLMv3Processor, LayoutLMv3Model
# Step 1: Load the processor and model from Hugging Face Hub
# We use the base model as we only need the embeddings (hidden states).
processor = LayoutLMv3Processor.from_pretrained("microsoft/layoutlmv3-base")
model = LayoutLMv3Model.from_pretrained("microsoft/layoutlmv3-base")
# Check for CUDA availability and move the model to the GPU if possible
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model.to(device)
# Step 2: Prepare the input data (Image, Text, and Bounding Boxes)
# For this example, we'll use a sample invoice image from the web.
url = "https://templates.invoicehome.com/invoice-template-us-neat-750px.png"
image = Image.open(requests.get(url, stream=True).raw).convert("RGB")
# In a real-world scenario, you would use an OCR engine (like Tesseract or a cloud-based one)
# to get the words and their bounding boxes. For this example, we'll manually define a few.
# Bounding boxes are in the format [x1, y1, x2, y2].
words = ["Invoice", "123-456", "12/12/2022", "100.00"]
# These boxes are approximate for demonstration purposes.
boxes = [
[69, 115, 154, 133], # "Invoice"
[592, 114, 664, 131], # "123-456"
[592, 141, 688, 158], # "12/12/2022"
[615, 625, 688, 642], # "100.00"
]
# Step 3: Process the inputs using the LayoutLMv3Processor
# The processor handles tokenization, image preprocessing, and formatting everything for the model.
encoding = processor(image, words, boxes=boxes, return_tensors="pt")
# Move the processed inputs to the same device as the model
for k, v in encoding.items():
encoding[k] = v.to(device)
# Step 4: Perform a forward pass through the model
with torch.no_grad():
outputs = model(**encoding)
# The final hidden states are the embeddings for each token and image patch.
last_hidden_state = outputs.last_hidden_state
print(f"Shape of the final hidden states: {last_hidden_state.shape}")
# Expected output shape: (batch_size, sequence_length, hidden_size)
# e.g., (1, 518, 768) where 518 is num_text_tokens + num_image_patches
# Step 5: Separate Text and Image Embeddings
# The model concatenates text token embeddings and image patch embeddings.
# We can find the split point by looking at the length of the input_ids.
num_text_tokens = len(encoding.input_ids[0])
print(f"Number of text tokens (including special tokens): {num_text_tokens}")
# Text embeddings correspond to the input tokens
text_embeddings = last_hidden_state[:, :num_text_tokens, :]
# Image embeddings correspond to the flattened image patches that come after the text tokens
image_embeddings_sequence = last_hidden_state[:, num_text_tokens:, :]
print(f"Shape of text embeddings: {text_embeddings.shape}")
print(f"Shape of image patch embeddings: {image_embeddings_sequence.shape}")
# The number of patches is typically 49*49=2401 for a 224x224 image divided into 16x16 patches,
# but LayoutLMv3 uses a different patching strategy resulting in 512 patches (16*32) for its default configuration.
# Step 6: Create a single "image embedding" vector
# The `image_embeddings_sequence` is a sequence of embeddings, one for each patch.
# To get a single vector for the entire image, you need to aggregate them.
# A common strategy is to take the mean of all patch embeddings.
aggregated_image_embedding = image_embeddings_sequence.mean(dim=1)
print(f"Shape of the final aggregated image embedding: {aggregated_image_embedding.shape}")
# You can now use this `aggregated_image_embedding` vector for downstream tasks
# like image similarity, classification, or clustering.
# The vector is on the GPU, move it to CPU if needed for other libraries (like scikit-learn)
final_embedding_cpu = aggregated_image_embedding.cpu().numpy()
print("Final embedding ready for use on CPU.")
### Alternative: Using the [CLS] Token Embedding
Another common approach, popular in BERT-like models, is to use the embedding of the special `[CLS]` token (the very first token in the sequence) as a representation of the entire input (text + layout + image).
cls_embedding = last_hidden_state[:, 0, :]
print(f"\nShape of the [CLS] token embedding: {cls_embedding.shape}")
# This single vector is trained to be a good summary of the whole document.
# It can often be a more powerful representation than just aggregating the image patches alone.
Explanation and Interpretation
- Context is Key: The
aggregated_image_embedding is not a pure visual representation. The model's self-attention mechanism allows information to flow between text tokens, their positions, and the image patches. This means the embedding for a patch of the image containing the number "100.00" is aware that it's text, what the text is, and where it is on the page.
- Aggregation: We performed mean pooling (
.mean(dim=1)) to convert the sequence of (num_patches, hidden_size) embeddings into a single (1, hidden_size) vector. This is a necessary step if you need a fixed-size embedding for the entire visual component of the document.
- [CLS] Token vs. Image Patches:
- Aggregated Image Patches: This gives you an embedding that focuses purely on the visual modality, but it is still contextualized by the text and layout.
- [CLS] Token Embedding: This gives you an embedding for the entire document. It's a holistic representation that fuses text, layout, and vision. For many document-level tasks, this is often the most effective embedding to use.