LayoutLMv3 is a multi-modal model designed for document understanding. This means it processes not only the text (OCR output) and its layout (bounding boxes of text), but also the visual information directly from the image.
When you ask for an "image embedding" from LayoutLMv3, it's important to understand that LayoutLMv3 doesn't produce a purely visual embedding in the same way a model like CLIP or a traditional CNN might. Instead, the "image embedding" you'll get is a fused representation that incorporates the visual features, the textual features, and their spatial relationships.
The most common way to get a single "document" or "image" level embedding from LayoutLMv3 is to extract the embedding corresponding to the [CLS] (classification) token from the last layer's hidden states. This token is designed to aggregate information from the entire input.
Here's an example using the transformers library:
import torch
from transformers import LayoutLMv3Processor, LayoutLMv3Model
from PIL import Image, ImageDraw, ImageFont
import os
# --- 1. Create a Dummy Image and OCR-like Data ---
# In a real scenario, you would use an actual document image and an OCR engine
# (like Tesseract or Google Cloud Vision API) to get the text and its bounding boxes.
def create_dummy_document_data(image_path="dummy_document.png"):
"""
Creates a simple image with text and returns mock OCR data.
"""
# Create a blank white image
img_width, img_height = 800, 600
image = Image.new('RGB', (img_width, img_height), color = (255, 255, 255))
draw = ImageDraw.Draw(image)
# Use a default font, or try to load a system font
try:
font = ImageFont.truetype("arial.ttf", 30) # Common font on Windows
except IOError:
font = ImageFont.load_default() # Fallback
text_content = [
"Invoice",
"Date: 2023-10-27",
"Item: Laptop",
"Price: $1200.00",
"Thank you for your business!"
]
words = []
actual_boxes = [] # Store actual pixel coordinates [x1, y1, x2, y2]
current_y = 50
for line in text_content:
# Split line into words for more realistic token-level bounding boxes
line_words = line.split(" ")
current_x = 50
for word in line_words:
# Estimate text bounding box (simplified)
text_width, text_height = draw.textsize(word, font=font)
box = [current_x, current_y, current_x + text_width, current_y + text_height]
words.append(word)
actual_boxes.append(box)
draw.text((current_x, current_y), word, font=font, fill=(0, 0, 0))
current_x += text_width + 10 # Add some space between words
current_y += text_height + 20 # Add space between lines
image.save(image_path)
print(f"Dummy document saved to {image_path}")
return image, words, actual_boxes, img_width, img_height
# --- 2. Define a function to normalize bounding boxes ---
def normalize_bbox(bbox, width, height):
"""
Normalize bounding box coordinates to 0-1000 range.
LayoutLMv3 expects bbox in [x_min, y_min, x_max, y_max] format
and values normalized to a 0-1000 scale.
"""
return [
int(1000 * (bbox[0] / width)),
int(1000 * (bbox[1] / height)),
int(1000 * (bbox[2] / width)),
int(1000 * (bbox[3] / height)),
]
# --- Main execution ---
if __name__ == "__main__":
# Create dummy data
image_file = "dummy_document.png"
image, words, actual_boxes, img_width, img_height = create_dummy_document_data(image_file)
# Normalize bounding boxes
normalized_boxes = [normalize_bbox(box, img_width, img_height) for box in actual_boxes]
# --- 3. Load LayoutLMv3 Processor and Model ---
# We use LayoutLMv3Model for extracting features, not for classification directly.
processor = LayoutLMv3Processor.from_pretrained("microsoft/layoutlmv3-base")
model = LayoutLMv3Model.from_pretrained("microsoft/layoutlmv3-base")
# Ensure model is in evaluation mode
model.eval()
# --- 4. Prepare Inputs ---
# The processor handles tokenization, image resizing, and feature extraction.
# It requires the image, text, and bounding boxes.
encoding = processor(
image,
words,
boxes=normalized_boxes,
return_tensors="pt"
)
# --- 5. Get Image Embedding ---
with torch.no_grad(): # Disable gradient calculations for inference
outputs = model(
input_ids=encoding["input_ids"],
attention_mask=encoding["attention_mask"],
bbox=encoding["bbox"],
pixel_values=encoding["pixel_values"]
)
# The 'last_hidden_state' contains the embeddings for all tokens in the sequence.
# The [CLS] token is typically at index 0.
# Shape: (batch_size, sequence_length, hidden_size)
last_hidden_state = outputs.last_hidden_state
# Extract the embedding for the [CLS] token (which represents the entire document)
# Shape: (batch_size, hidden_size)
document_embedding = last_hidden_state[:, 0, :]
print("\n--- Image Embedding Results ---")
print(f"Shape of the document embedding (batch_size, hidden_size): {document_embedding.shape}")
print(f"Example embedding values (first 10): {document_embedding[0, :10].tolist()}")
# You can now use 'document_embedding' for tasks like:
# - Document similarity search
# - Classification (by feeding it into a linear layer)
# - Clustering similar documents
# Clean up the dummy image
# os.remove(image_file)
# print(f"\nCleaned up {image_file}")
Explanation:
create_dummy_document_data: In a real application, you'd replace this with:
- Loading an actual image from disk.
- Running an OCR engine (e.g., Tesseract, Google Cloud Vision, Azure AI Vision) on the image to get the
words (text content) and their actual_boxes (pixel coordinates of each word/line).
normalize_bbox: LayoutLMv3 expects bounding box coordinates to be normalized to a fixed scale (0-1000), regardless of the original image dimensions. This function performs that normalization.
- Load Processor and Model:
LayoutLMv3Processor: This is crucial. It handles all the pre-processing steps:
- Tokenizing the
words into input_ids.
- Aligning the
bbox for each original word with the newly generated tokens (some words might split into multiple tokens).
- Resizing the image and converting it into
pixel_values (the visual features that the Vision Transformer part of LayoutLMv3 expects).
LayoutLMv3Model: This is the base model without any specific classification head. We use it to get the raw hidden states.
- Prepare Inputs: The
processor takes the image, the text (words), and their normalized_boxes and returns a dictionary of tensors ready for the model.
- Get Image Embedding:
- We pass the prepared inputs to the
model.
outputs.last_hidden_state gives you the final hidden states for every token in the input sequence. Its shape is (batch_size, sequence_length, hidden_size).
- The
[CLS] token is typically the first token in the sequence (at index 0). Its embedding last_hidden_state[:, 0, :] is commonly used as a representation for the entire input document because the model is trained to aggregate document-level information into this token.
- The resulting
document_embedding will be a PyTorch tensor (or NumPy array if converted) representing your document in a high-dimensional space.
This document_embedding is a powerful representation that captures both the textual content, its layout, and the visual appearance of your document.