When Your Documents Aren’t Just Text: Training Vision Models for Document Understanding
From the publisher’s feed, collected in the ZeroLabs newsroom.
The fourth in a series on building domain-specific language models from scratchThere’s a problem nobody mentions when you start building a domain-specific AI pipeline.You spend weeks curating your corpus. You clean the text, deduplicate it, filter out the noise. You kick off the training run and watch the loss curve drop. Everything looks fine.Then you actually look at what your pipeline extracted from the source documents.And you realize that a significant chunk of what makes those documents meaningful never made it into your training data at all. The block diagrams. The figures. The structured visual content that domain experts use to communicate things that words alone can’t capture.You didn’t have a text problem. You had a document problem.What text extraction actually does to technical documentsMost pipelines treat a PDF like a container of text. You run a parser, it pulls out the words, you move on.This works fine for documents that are mostly prose. It fails badly for technical documents.Dense technical documents are not just text. They’re a mix of content types: paragraphs of explanation, tables, equations, and visual elements like block diagrams, schematic drawings, and annotated figures. These visual elements aren’t decoration. They carry information that the text around them assumes you’ve understood. Skip them and you’ve extracted a document with half its meaning missing.The parser doesn’t warn you about this. It just quietly drops anything it can’t convert to characters. You end up with text that looks complete but has holes in it you can’t see by reading it linearly.I ran into this firsthand. We were working with technical documents that relied heavily on structured visual elements to communicate domain concepts. The standard extraction pipeline produced text that, on the surface, looked reasonable. But when we cross-referenced it with the original documents, entire sections of meaning were gone. The model was being trained on text that referenced visual content that had simply been discarded.Why this is actually a hard problemThe obvious fix is: detect the visual elements and handle them separately.Easier said than done.Visual elements in technical documents aren’t neatly labeled. They don’t come with a tag that says “this is a block diagram, treat it accordingly.” A PDF is, at a low level, a set of rendering instructions. Some visual content is vector-based. Some is rasterized. Some is a mix of both. The same diagram might look identical to a human reader but be structured completely differently under the hood depending on how the original document was created.And even once you detect that a visual element exists, you still need to figure out what it is. A graph is different from a schematic. A table is different from a flowchart. Each type requires different handling if you want to extract something meaningful from it.This is where computer vision comes in.Training a detection modelWe needed a way to automatically detect and classify visual elements in our documents. Specifically, block diagrams, which were the most common and most information-dense visual type in our corpus.We used YOLO for this. If you haven’t used it before: YOLO (You Only Look Once) is a family of object detection models designed to identify and localize objects in images quickly and accurately. It outputs bounding boxes around detected objects along with confidence scores and class labels.The workflow looked like this:Convert PDF pages to imagesRun the detection model to find and classify visual elementsExtract those regions separatelyFeed them into a vision model for further processing or descriptionRecombine with the surrounding text, preserving contextThe detection step was where the most iteration happened.full pipelineGoing from 72% to 91% accuracyThe first version of the detection model hit around 72% accuracy. That sounds okay until you think about what 28% miss rate means in practice. More than one in four block diagrams either missed entirely or misclassified. At the scale we were operating, that’s a lot of missing information.Getting from 72% to 91% was mostly an annotation problem, not a model problem.This surprised me. I expected the gains to come from architecture changes or hyperparameter tuning. They mostly didn’t. The biggest improvements came from fixing the training data.A few things that moved the needle:Annotation consistency. Early annotations had inconsistent bounding boxes. Some annotators drew tight boxes around just the diagram. Others included surrounding whitespace or captions. The model was learning from mixed signals. Standardizing the annotation guidelines and re-doing a portion of the labels had a bigger impact than I expected.Class imbalance. Our corpus had far more of some visual types than others. The model was good at detecting the common types and poor at the rare ones. Deliberately oversampling the underrepresented classes during training helped significantly.Hard negatives. The model was confused by certain document elements that visually resembled block diagrams but weren’t. Dense tables and certain figure arrangements kept getting flagged as false positives. Adding these as explicit negative examples in training cleaned this up.Image resolution. Some PDFs rendered at low resolution had diagrams that were just too small and blurry to detect reliably. Improving the rendering resolution at the extraction stage improved recall on those documents without any model changes at all.The honest summary: most of the gap between 72% and 91% was annotation quality, data balance, and input quality. Not the model.accuracy bar chartWhat this means for your pretraining corpusIf you’re working with technical documents and you skip this step, your training corpus is incomplete in ways that are hard to quantify but real.The text your model trains on will reference concepts explained visually in the original documents. The model will learn language patterns around those concepts without ever having the visual context those patterns were written to accompany. It’s like studying a textbook with all the figures ripped out.For some domains this matters a little. For domains where visual communication is central, it matters a lot.A practical starting pointIf you want to try this yourself, here’s a bare-bones detection loop using a fine-tuned YOLO model:from ultralytics import YOLOfrom pdf2image import convert_from_pathimport cv2# Load your trained detection modelmodel = YOLO("block_diagram_detector.pt")# Convert PDF pages to imagespages = convert_from_path("document.pdf", dpi=200)detected_regions = []for page_num, page_img in enumerate(pages): # Convert PIL image to numpy array for OpenCV import numpy as np img_array = np.array(page_img) # Run detection results = model(img_array) for result in results: for box in result.boxes: confidence = float(box.conf) if confidence > 0.6: # confidence threshold x1, y1, x2, y2 = map(int, box.xyxy[0]) class_id = int(box.cls) class_name = model.names[class_id] # Crop the detected region region = img_array[y1:y2, x1:x2] detected_regions.append({ "page": page_num, "class": class_name, "confidence": confidence, "region": region, "bbox": (x1, y1, x2, y2) })print(f"Found {len(detected_regions)} visual elements across {len(pages)} pages")This gives you the detected regions. What you do with them next depends on your pipeline. You can feed them to a vision-language model for captioning, store them for separate processing, or use the bounding box coordinates to reconstruct the document with visual context intact.accuracy bar chartThe thing I keep coming back toWe think of “document understanding” as a text problem because that’s the part we can easily measure and train on. But real documents are multimodal. They’ve always been multimodal. The text and the visuals are meant to be read together.Building a model that only sees the text half of a technical document isn’t building domain understanding. It’s building domain understanding with one eye closed.Getting the vision piece right is harder than it sounds and more important than most pipelines treat it. The accuracy gains don’t come from clever architecture choices. They come from caring about the data.Next: Post 5 — “DAPT vs. Fine-Tuning vs. RAG: How to Actually Decide”Connect with me on LinkedIn: https://www.linkedin.com/in/aryamane20/or check out my projects on GitHub: https://github.com/aryamane20When Your Documents Aren’t Just Text: Training Vision Models for Document Understanding was originally published in Towards AI on Medium, where people are continuing the conversation by highlighting and responding to this story.