Visual Grounding in Multimodal Models: From Coordinate Outputs to Referential Alignment

    Multimodal models can describe what is in an image, but real-world applications demand precise localization and counting. This article breaks down visual grounding into two challenges—perception and reference—and covers common localization representations, interleaved image-text context budgeting, and engineering practices for reliable grounding, with Python examples for parsing bounding boxes, estimating image token usage, and evaluation metrics like IoU.

    1. Background

    Multimodal large models can already answer “what is in this image.” In real business scenarios, users go further: “Where is the third person standing?”, “How many bottles are on the shelf?”, “Please circle the defective region.” These questions require the model to produce precise locations or counts, not a summary paragraph.

    Answering “what is in the image” relies on holistic understanding; answering “where is it” relies on precise reference. The two fail differently. The former typically suffers from missed details or misattribution, while the latter commonly suffers from positional drift, confusion between similar objects, and broken counting logic in dense scenes.

    2. Two Gaps: Perception and Reference

    From an engineering perspective, the difficulty of visual grounding can be decomposed into two layers.

    The first layer is perception. The vision encoder must convert pixels into features the model can use. Insufficient resolution, too many small objects, and compression artifacts all cause details to be lost during encoding. Improvements at this layer mainly depend on better vision encoders, more sensible resolution strategies, and more sufficient training data.

    The second layer is reference. Even if the model sees the image clearly, it still needs an unambiguous way to map objects mentioned in language to regions in the image. “The second cup from the left” requires the model to first establish the reference frame of “left,” then count to “second,” and finally decide which cup it is. Every step can go wrong. When the reasoning process relies entirely on natural language, the description itself accumulates errors.

    Therefore, improving perception alone cannot automatically solve localization. Introducing explicit coordinate or region representations during inference decouples reference from natural language and reduces ambiguity.

    3. Common Representations for Visual Grounding

    1. Natural language descriptions: flexible, but highly ambiguous and hard to evaluate directly.
    2. Normalized coordinates: points, boxes, or polygons expressed as relative coordinates between 0 and 1, decoupled from pixel dimensions and reusable across resolutions.
    3. Coordinates wrapped in special markers: fixed markers in the text sequence indicate “this is a point or box,” followed by the coordinate values, which simplifies parsing and training.
    4. Placeholders: in interleaved image-text sequences, a segment of position identifiers is reserved for each image so the model knows where visual content is inserted.

    These four approaches can be combined. For example, first identify the target in natural language, then output box coordinates, and finally use a placeholder to associate the box with the original image.

    The following code shows how to parse normalized boxes in the “label“ format and validate their range and ordering:

    1. import re
    2. from dataclasses import dataclass
    3. @dataclass
    4. class Box:
    5. label: str
    6. x1: float
    7. y1: float
    8. x2: float
    9. y2: float
    10. BOX_PATTERN = re.compile(
    11. r"\[(?P<label>[^\]]+)\]\((?P<x1>[\d.]+),(?P<y1>[\d.]+),(?P<x2>[\d.]+),(?P<y2>[\d.]+)\)"
    12. )
    13. def parse_boxes(text: str) -> list[Box]:
    14. boxes = []
    15. for m in BOX_PATTERN.finditer(text):
    16. box = Box(
    17. label=m["label"],
    18. x1=float(m["x1"]), y1=float(m["y1"]),
    19. x2=float(m["x2"]), y2=float(m["y2"]),
    20. )
    21. if not all(0.0 <= v <= 1.0 for v in (box.x1, box.y1, box.x2, box.y2)):
    22. raise ValueError(f"Coordinates out of normalized range: {box}")
    23. if box.x1 >= box.x2 or box.y1 >= box.y2:
    24. raise ValueError(f"Top-left corner must be smaller than bottom-right: {box}")
    25. boxes.append(box)
    26. return boxes
    27. def to_pixels(box: Box, width: int, height: int) -> tuple[int, int, int, int]:
    28. return (round(box.x1 * width), round(box.y1 * height),
    29. round(box.x2 * width), round(box.y2 * height))

    When parsing fails, the system should log the raw output and trigger a retry or fallback, rather than silently discarding the result.

    4. Interleaved Image-Text and Context Budgeting

    After encoding, an image occupies a portion of the context length. This length is determined jointly by resolution, the tiling strategy, and the encoder’s downsampling factor. Multiple images share the same context window, so input design requires estimating usage in advance.

    Placeholder numbering does not necessarily correspond one-to-one with the number of images. A large image may be split into multiple segments, and a single placeholder segment may correspond to only a local region of an image. Therefore, you cannot infer the image count from numbering alone; you should rely on the actual number of input images and the encoded sequence length.

    The example below provides an illustrative estimation function. The patch size and merge factor should be taken from the official documentation of the model you are using:

    1. import math
    2. def estimate_image_tokens(width: int, height: int,
    3. patch_size: int, merge_factor: int) -> int:
    4. """Illustrative estimate: split into patches, then downsample by the merge factor."""
    5. side = patch_size * merge_factor
    6. cols = math.ceil(width / side)
    7. rows = math.ceil(height / side)
    8. return cols * rows
    9. def check_budget(images: list[tuple[int, int]], context_limit: int,
    10. text_tokens: int, patch_size: int, merge_factor: int) -> tuple[int, bool]:
    11. total = text_tokens + sum(
    12. estimate_image_tokens(w, h, patch_size, merge_factor) for w, h in images
    13. )
    14. return total, total <= context_limit

    Budget checks should happen before the request is sent. If the limit is exceeded, you can lower the resolution, reduce the number of images, or split the work into multiple requests.

    5. Making Grounding Results More Reliable

    In engineering practice, the stability of localization outputs can be improved in several ways.

    • Unified coordinate conventions: clearly define the origin, normalization scheme, and box format, and keep them consistent between prompts and parsing code.
    • Structured validation: parse outputs and check value ranges, and record the rate of out-of-bounds and format errors.
    • Step-by-step counting: require the model to list and number each instance before giving a total. Cross-check against independent detection results, and escalate to human review when the discrepancy exceeds a threshold.
    • Stratified evaluation: split the test set into single-object, multi-object, and dense-scene tiers, and compute accuracy separately for each.

    Evaluation metrics should match the task type. Box tasks commonly use Intersection over Union (IoU); point tasks check whether the point falls inside the target box; counting tasks focus on absolute error and exact-match accuracy.

    1. def iou(a: Box, b: Box) -> float:
    2. ix1, iy1 = max(a.x1, b.x1), max(a.y1, b.y1)
    3. ix2, iy2 = min(a.x2, b.x2), min(a.y2, b.y2)
    4. inter = max(0.0, ix2 - ix1) * max(0.0, iy2 - iy1)
    5. area_a = (a.x2 - a.x1) * (a.y2 - a.y1)
    6. area_b = (b.x2 - b.x1) * (b.y2 - b.y1)
    7. union =