cancel
Showing results for 
Search instead for 
Did you mean: 
Technical Blog
Explore in-depth articles, tutorials, and insights on data analytics and machine learning in the Databricks Technical Blog. Stay updated on industry trends, best practices, and advanced techniques.
cancel
Showing results for 
Search instead for 
Did you mean: 
peterpark-db
Databricks Employee
Databricks Employee

AI adoption has moved much faster than measurable business results. McKinsey reports that 88% of organizations now use AI in at least one business function, yet only 39% see a bottom-line effect. A common bottleneck in closing that gap is trust. You can't wire a model into a decision you have to defend unless you can rely on what it produces.

Vision-language models are built for recognition. Show a photo, a scan, or a document page and it will read the text, describe what is there, or pull out a field, which is why they already power so much document AI across invoices, claims, and forms. That strength is also where the boundary starts. Recognition produces an estimate, and for many tasks an estimate is fine. But for tasks requiring exact, reproducible, and auditable numbers, like a net weight on a label, an amount total on an invoice, or a dimension on a spec, an estimate may not suffice.

Why model judgment alone is not a measured result

If you have ever pointed a vision model at a document and asked yourself, "How do I know this is right?" you know the uneasy feeling that follows. An answer you cannot reproduce, explain, or defend to a reviewer is not one you can build a process on. Take packaging artwork, for instance. In the U.S., the net-quantity statement on a package, something like "NET WT 3 LB," has to meet a minimum type height set by the area of the principal display panel, and someone has to confirm the text is large enough before artwork moves forward. This is not a judgment call.

It is tempting to send the artwork to a vision model and ask whether the net weight meets the minimum type size. The model will answer, and it will sound sure of itself. But that answer is not a measured result and it falls short in four ways:

  • It's not reproducible. Ask twice, get two verdicts. Multimodal models don't measure pixels. They estimate from a learned prior, and that estimate drifts with sampling, prompt wording, and image tiling. 
  • It's not auditable. A "fail" with no measured value, no threshold, and no located region is nothing a review or quality team can stand behind. When the auditor asks why, there is no answer to give. 
  • It's not verifiable. Ask for a height in millimeters, and the model will give you one, but it has no instrument to measure with. The number is a plausible guess.
  • It fails open. A hallucinated "looks fine" sails through silently. In a compliance check, the most crucial error is the bad file that slips through unflagged.

None of this means the models are bad. The study "Vision Language Models Are Blind" showed that even strong VLMs miss precise, low-level visual judgments, such as whether two shapes overlap, and Anthropic's Claude vision docs note the same limitation in practice. These systems are strong at recognition and weak at measurement.

So the model still has a role of finding evidence. Here it means locating the net-quantity statement in dense, multilingual, vector-or-raster artwork where plain-text extraction often returns nothing. Once the evidence is found, measuring and judging it belong to deterministic code.

This is Part 1 of a two-part series on a reusable reference pattern for verifiable visual AI on Databricks. The packaging check is only the running example. The pattern itself does not certify regulatory compliance and does not guarantee model performance. What it provides is a design in which every verdict is linked to recorded evidence, a repeatable measurement, and the exact rule applied. Part 1 covers the three stages, Locate, Measure, Judge. Part 2 covers the production shell, evaluation, and the Databricks architecture.

The pattern: Locate, Measure, Judge

The architecture splits the workflow into three stages, each with its own trust model.

Figure 1. The Locate, Measure, Judge pattern separates semantic recognition, deterministic measurement, and governed policy decisions. A workflow may compose these responsibilities more than once, but each handoff retains the same trust boundary.fig1-pattern.png

  1. Locate: the probabilistic step. Use a vision model to find the region that holds the net-quantity declaration. This is semantic recognition, which a vision model handles well even on dense, multilingual layouts. Keep it away from coordinates and dimensions. Give it a deterministic montage of candidate regions and ask it to select the correct index. The stage is evaluated empirically, and its reported confidence is a routing signal rather than a calibrated probability.
  2. Measure: the deterministic step. Given the located region, measure the quantity with ordinary, testable code, things like pixel analysis, vector geometry, or parsing. No model runs here, and the guarantee is repeatability within a validated environment and tolerance.
  3. Judge: the governed step. Compare the measurement to a threshold from a rule table and emit a three-way verdict: pass, review, or fail. The judgment is deterministic against a versioned rule snapshot, and the review verdict routes recorded uncertainty to a human rather than letting it pass silently.

One caveat: the design catches the uncertainty it measures, and it cannot promise to catch what it never measures.

The boundary is easiest to see by separating semantic questions from measured or rule-based answers.

Ask the model (semantic)

Keep deterministic (code or rules)

"Which of these crops contains the net weight?"

"How tall is the text, in inches?"

"Which page region is the principal display panel?"

"What are the bounding-box coordinates?"

"Is this region printed copy or background art?"

"Does this pass the regulation?"

"Transcribe what this declaration says."

"What is the panel area in square inches?"

The same split shows up across industries:

  • Manufacturing: locate the dimension callout on a drawing, measure the geometry, judge against the specification.
  • Financial services: locate the line items on an invoice, recompute the totals, judge against policy.
  • Insurance: locate the evidence in a claim document, compute the attribute deterministically, apply the coverage rule.

The contracts

The pattern is easier to reuse if you define the handoffs between stages first. Six generic contracts cover them, so a team can implement them once and reuse them across document types and checks. The decision trace at the end carries everything upstream of it, plus the artifact hash and the MLflow run and trace IDs, which is enough to reconstruct and review any result. These are conceptual shapes rather than enforceable schemas, and the shapes matter more than the field names.

from decimal import Decimal

InputArtifact = {"artifact_id": str, "artifact_version": str,
                 "uri": str, "kind": "pdf|image|scan|drawing|label|form"}
EvidenceRegion = {"kind": "crop|page_region|object|text_span",
                  "bbox": tuple, "coordinate_space": str, "source": str}
ModelDecision = {"selected": EvidenceRegion, "reported_confidence": "high|medium|low",  # structured, no prose
                 "model_endpoint": str, "model_version": str, "prompt_version": str}
Measurement = {"value": Decimal, "unit": str, "method": str,
               "impl_version": str, "tolerance": Decimal}
RuleDecision = {"rule_id": str, "rule_version": str, "threshold": Decimal,
                "review_band_in": Decimal,
                "verdict": "pass|review|fail", "uncertainty": list[str]}
DecisionTrace = {"trace_id": str, "mlflow_run_id": str, "created_at": str,
                 "artifact": InputArtifact, "artifact_sha256": str,
                 "evidence": EvidenceRegion, "model": ModelDecision,
                 "measurement": Measurement, "rule": RuleDecision}

Two details make the record auditable. The model returns only a choice and a reported confidence. A reviewer can verify the selected evidence, while evaluation determines whether the confidence label is useful for routing. And every verdict carries its own inputs, so you can pull up any result later and see how it got there. These are plain structured records. Store them in Delta and link each one explicitly to its MLflow run and trace.

Stage 1: Locate. Ask for semantics, not coordinates

Most teams' first instinct is to ask the model for the bounding box, the pixel coordinates of a rectangle drawn tightly around the target field like the net weight in our example. It comes back confidently wrong, either off by half an inch or landing on a nearby callout. None of that should surprise you, because a bounding box is a measurement and the model has no instrument for it, so the locate stage doesn't ask for one.

A sturdy locate stage runs geometry first and vision second, with the model there to pick the right candidate.

The geometry step leans on what the file already holds. A born-digital PDF, one exported straight from design or authoring software, stores the text and shapes it draws with their positions on the page, and the code reads that structure to propose candidate regions before the model sees anything. A flat scan, a photograph, or a PDF that is really a wrapped image has none of it, so the code falls back to the pixel path below, adding OCR with a tool like Tesseract where it also needs the text.

  1. Generate candidates deterministically. Three sources cover most artwork. Glyph runs are the sequences of characters the PDF draws, each with its coordinates. Live text spans are the stretches of selectable, extractable text. Rendered-ink blobs are the clumps of dark pixels found by rasterizing the page and scanning for text-sized shapes, which catches wording flattened into an image. A library like PyMuPDF exposes live text and vector drawing geometry and can render the page. Ordinary image-processing code then derives rendered-ink blobs from the rendered pixels. The step is cheap, gives real coordinates, and has coverage you can evaluate. 
  2. Let the model choose. Each candidate is a box with coordinates, so cropping it is a slice of the rendered page. Paste the crops onto one blank canvas in a grid, draw a number beside each, and keep a list that maps every number back to its original region. That numbered composite is the labeled montage. You send the model two things, the montage image and a short text prompt naming what to find, and you get back a single number. The model is answering a multiple-choice question, picking an index rather than producing a coordinate, which is the kind of task it is reliably good at.

    The whole exchange is one call. The regions travel as pixels in the image, not as a data structure, and the mapping stays on your side so a returned index resolves to real coordinates.

    No single built-in function handles drawing a labeled montage. Looking at the code example below, both tile_with_labels and the fallback grid overlay are constructed using a few lines of basic drawing code that pastes cropped regions onto a canvas and renders numbers. This is easily achieved using an imaging library like Pillow, or by drawing directly onto the page with PyMuPDF.
  3. Fall back to a coarse region only when needed. For dense artwork, candidate generation can yield too many false hits. When that happens, overlay a numbered grid on the page, the same tiling idea applied to fixed cells rather than detected crops. Ask the model which cell the net weight sits in, then rebuild the candidates inside that one cell, where there's much less to confuse them.
crops = [render_region(page, c.bbox) for c in candidates]
montage = tile_with_labels(crops)          # numbered grid on one canvas
index_to_region = dict(enumerate(candidates))   # your private mapping

resp = client.chat.completions.create(
       model=ENDPOINT,
       messages=[{"role": "user", "content": [
           {"type": "text", "text":
            "Each crop is numbered. Reply with JSON "
            '{"index": <int>, "confidence": "high|medium|low"} '
            "for the crop showing the net-quantity statement."},
           {"type": "image_url",
            "image_url": {"url": f"data&colon;image/png;base64,{b64(montage)}"}},
       ]}],
)
# parse_pick, shown in Part 2, validates the reply. None routes to review.
pick = parse_pick(resp.choices[0].message.content, len(candidates))
region = index_to_region[pick[0]] if pick else None

Two practices make the locate stage hold up in production:

Make it model-agnostic. Provider APIs disagree on small things that break code. One model rejects a temperature parameter, another returns message content as a list of parts rather than a string. Instead of branching on model names, which go out of date the week a new model lands, keep a small capability flag per endpoint, like temperature_supported or content_shape, and read from it at call time.

Tag every result with how it was found. Mark each located result as a high-confidence geometric pick, a model-selected fallback, or a low-confidence guess. The fail-closed logic reads that tag later, and a result that only turned up through the coarse fallback is not allowed to auto-pass.

On Databricks, send the request through Unity Gateway to a vision-capable model service, such as a supported system.ai foundation model or a governed external model. Use the documented multimodal request format, and require every model change to pass the same evaluation gate.

Stage 2: Measure. Deterministic and reproducible

To measure type height, the code renders the located region to pixels, separates ink from background so the reading holds on both dark-on-light and knockout white-on-color text, labels the connected components that make up each glyph, and takes the rule-defined character-height metric, cap height in this example, from the tallest stable cluster. These are ordinary image and geometry operations. A library like PyMuPDF can do the rendering, and Pillow, NumPy, SciPy, or OpenCV the pixel work. The pattern does not care which you pick, only that every step stays deterministic and testable.

That reproducibility comes with one caveat. Font handling, anti-aliasing, and rasterization all drift between library versions, so the claim holds only inside a pinned environment, the same libraries, the same renderer, and a fixed DPI. Measure repeatability at the canonical DPI, and test the supported DPI range separately as a robustness check. Once both hold, the same input returns the same value within the validated tolerance.

This is the stage that makes the results verifiable. You can unit-test the code, diff its output across versions, and explain how it reached a value. For a cross-check, run a second measurement with a different method or on a different region of the same evidence. When the two disagree beyond tolerance, mark the result uncertain and send it to review.

For example, on a 25.8-square-inch principal display panel, the rule, 21 CFR 101.105 for FDA-regulated products with FTC parallels at 16 CFR 500 for others, requires a minimum cap height of 3/16 inch, or 0.1875 inches. Suppose the engine locates the declaration and measures roughly 0.28 inches. Define the robustness criterion before testing, for example no more than 0.002 inch of variation across the supported DPI range, and verify it in the pinned environment. The measurement didn't come from the model. The model only pointed at the text.

Some measurements come straight from the artwork's geometry, and the applicable rule defines how. In this example, the panel area that sets the thresholds comes from the dieline layer, the cut and fold lines. The rule bounds a folded carton's front panel by its fold edges, and a cylindrical tub uses the formula in 21 CFR 101.1, 40 percent of height times circumference. Either way, the value is computed deterministically and the model is excluded from the calculation. The difference between cartons and tubs comes back in Part 2, as an example of how quietly a deterministic stage can fail.

Stage 3: Judge. Governed data for rules and failing closed

The final step compares the measured value against the tier threshold and produces a verdict. Where the thresholds live is a critical design decision. Hardcode them and every rule update needs a code review and a redeploy, and the value the engine enforces can drift from the value a reviewer sees on the rules page.

To avoid these issues, keep policy thresholds in governed data. A Unity Catalog Delta table holds them, and the engine and the rules UI read the same approved versions. A rule change lands as a new immutable version with an effective date and an approver, and every verdict records the exact version applied. Configuration can activate or parameterize a check already installed in the engine, but it cannot create a new analysis capability. A genuinely new check still requires a tested Locate, Measure, and Judge implementation.


Figure 2. Rules as governed data. One Unity Catalog table feeds both the enforcing engine and the human-facing rules view, so displayed and enforced thresholds stay aligned.fig2-rules-as-data.png

A minimal rule table for the example, built to layer global and class-specific rules and to version every change:

Column

Type

Description

rule_id

STRING

Stable identifier for the rule, carried into every rule decision

rule_version

STRING

Immutable version identifier, recorded in every verdict

effective_from

DATE

When this version takes force

approved_by

STRING

Who approved the version, with the approval logged

classification

STRING

ALL for rules that apply to every product class, or a class name for overrides that take precedence over ALL

tier_order

INT

Ordering of the area tiers

pdp_min_sqin

DECIMAL(12,6)

Lower bound of the panel-area tier in square inches, inclusive

pdp_max_sqin

DECIMAL(12,6)

Upper bound, exclusive, NULL for the open-ended top tier

min_cap_in

DECIMAL(12,6)

Minimum cap height the tier requires, in inches

review_band_in

DECIMAL(12,6)

Half-width of the review band around the threshold, in inches

min_cap_label

STRING

Human label, like 3/16"

The judge reads the table, picks the threshold and review band for the measured area, and applies a three-way verdict.

from decimal import Decimal

def verdict(measure_in: Decimal, min_in: Decimal, band_in: Decimal,
            uncertain: list[str] | None = None) -> str:
    # band_in comes from the rule row's review_band_in, versioned with the rule.
    # Fail closed. Recorded uncertainty caps the result at REVIEW,
    # in both directions. An untrustworthy "fail" is as wrong as a silent pass.
    if uncertain:
        return "review"
    if measure_in >= min_in + band_in:
        return "pass"
    if measure_in <  min_in - band_in:
        return "fail"
    return "review"   # within the tolerance band, a human confirms

Two design choices make this auditable. The three-way verdict makes uncertainty explicit, so ambiguous cases go to a human. And the decision trace travels with every result, carrying the located text, the measured value, the threshold, the exact rule version, and any review reasons. That trace is the answer when the auditor asks why.

Failing closed keeps a wrong answer from passing silently, and Figure 3 shows the routing.

Figure 3. The fail-closed verdict flow. Recorded uncertainty at any stage routes to human review. Only a measurement with no recorded uncertainty passes or fails on its merits. fig3-failclosed.png

Coming up in Part 2

At this point the pattern works on paper. An artifact goes in, a model points at the evidence, code measures it, a governed rule judges it, and the trace explains every step. Part 2 takes it into production, where inputs break assumptions, models get swapped, and reviewers start sending answers back. It covers the failure modes and the response to each, an evaluation scored for safety, and how the design maps onto the Databricks ecosystem. If you want to try the idea before then, pick one check with a clear rule and build the deterministic measurement first.