File size: 10,228 Bytes
7825400
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
"""Bounding-box conventions, and the one transform between them.

Models disagree about what four numbers in a box mean. Qwen-VL emits
``[x1, y1, x2, y2]`` on a 0-1000 integer grid; Llama 4 emits the same corners
normalised 0-1; YOLO gives normalised corners; the prompt asks for offsets and
extents. Storing any of those verbatim scores IoU near zero against ground truth
without raising anything, which is exactly how three model runs came to be
recorded as complete failures.

So the convention is *declared* (see ``configs/box_conventions.json``) and
converted here, once, on the way in. Everything downstream — metrics, the
contract, the drift report — may assume the canonical form:

    unit-normalised ``[x, y, width, height]``, origin top-left.

Nothing in this module guesses. If a box does not fit its declared convention it
is passed through with the problem recorded, so the drift report flags it; a
silent rescue would hide the very drift this repo exists to measure.
"""

from __future__ import annotations

from dataclasses import dataclass
from typing import Literal

BoxSpace = Literal["unit", "grid1000", "pixel"]
"""The coordinate space a model's numbers live in.

* ``unit`` — normalised 0.0-1.0
* ``grid1000`` — integer 0-1000 grid (the Qwen-VL family)
* ``pixel`` — absolute pixels; needs the image size to normalise

**``unit`` repairs partial non-compliance, per coordinate.** Models are asked for
0-1 and some of them only partly comply: Gemma 4 E2B returned
``[0.41, 580, 0.65, 780]`` — x normalised as instructed, y left on the 0-1000
grid it thinks in — and Qwen3.8 27B does the same on 3 boxes in 30. So a
``unit``-declared coordinate above 1 is divided by 1000 rather than clipped.

This is narrower than it looks, and it is not a guess. A coordinate *declared*
unit-scale and greater than 1 is already known illegal; the only question is what
to do about it, and clipping is the one answer guaranteed to be wrong — it
collapsed every one of Gemma's boxes to a zero-height sliver on the frame's
bottom edge. Rescaling is recorded (``out_of_declared_range`` and
``rescaled_from_grid``), never silent, so a run can always say how far the model
missed and what was done about it.

It applies to ``unit`` only. ``grid1000`` divides everything by 1000 already, and
a per-coordinate rule there would read a legitimate ``1`` (meaning 0.001) as the
full width of the image. A model that emits genuine pixel coordinates must be
declared ``pixel``; declared ``unit`` it would be divided by 1000 and land in the
top-left corner.
"""

BoxOrder = Literal["xywh", "xyxy", "yxyx"]
"""What the four numbers are, and in which axis order.

* ``xywh`` — top-left corner, then width and height
* ``xyxy`` — top-left corner, then bottom-right corner
* ``yxyx`` — the same two corners with the **axes swapped**: ``[y1, x1, y2, x2]``

``yxyx`` exists because Gemini emits it. Google's documentation is explicit —
"The box_2d should be [ymin, xmin, ymax, xmax] normalized to 0-1000" — and it
is the only major family that does. Read as ``xyxy`` it does not produce
obvious rubbish; it produces a transposed box, which on a roughly square image
is plausible enough to pass every range check and simply score badly. That is
the same failure mode as the corners-read-as-extents bug, so it gets a name
rather than a comment.
"""

# Boxes are rounded to 4dp, so allow a hair of slack before calling a coordinate
# out of range. Matches utils.contract.BBOX_TOLERANCE.
TOLERANCE = 1e-3

_SCALE = {"unit": 1.0, "grid1000": 1000.0}


@dataclass(frozen=True)
class BoxConvention:
    """How to read a model's four box numbers."""

    space: BoxSpace = "unit"
    order: BoxOrder = "xywh"

    @classmethod
    def parse(cls, spec: str) -> "BoxConvention":
        """Build from a ``"space:order"`` string, e.g. ``"grid1000:xyxy"``."""
        try:
            space, order = spec.strip().split(":")
        except ValueError:
            raise ValueError(
                f"box convention {spec!r} must look like 'space:order', "
                f"e.g. 'grid1000:xyxy'"
            ) from None
        if space not in ("unit", "grid1000", "pixel"):
            raise ValueError(f"unknown box space {space!r} in {spec!r}")
        if order not in ("xywh", "xyxy", "yxyx"):
            raise ValueError(f"unknown box order {order!r} in {spec!r}")
        return cls(space=space, order=order)  # type: ignore[arg-type]

    def __str__(self) -> str:
        return f"{self.space}:{self.order}"


CANONICAL = BoxConvention("unit", "xywh")
"""What every box on disk is expected to be."""


def to_unit_xywh(
    bbox: list[float],
    convention: BoxConvention = CANONICAL,
    image_size: tuple[int, int] | None = None,
) -> tuple[list[float], list[str]]:
    """Convert *bbox* from *convention* to canonical unit ``[x, y, w, h]``.

    Args:
        bbox: Four numbers as the model emitted them.
        convention: How to read them.
        image_size: ``(width, height)`` in pixels. Required for ``pixel`` space.

    Returns:
        ``(canonical_bbox, repairs)``. ``repairs`` names every adjustment made,
        so a run can report how much interpretation its boxes needed. An empty
        list means the box was already well formed.
    """
    if len(bbox) != 4:
        return list(bbox), ["bbox is not four numbers"]

    repairs: list[str] = []
    values = [float(v) for v in bbox]
    order = convention.order

    # --- 0. Put the axes in x-first order --------------------------------
    # Reordering is scale-free, so doing it before anything else means the rest
    # of the pipeline — including which slots divide by width — never has to
    # know that a y-first convention exists.
    if order == "yxyx":
        y1, x1, y2, x2 = values
        values = [x1, y1, x2, y2]
        order = "xyxy"

    # --- 1. Normalise into 0-1 -------------------------------------------
    if convention.space == "pixel":
        if not image_size:
            return values, ["pixel space needs an image size to normalise"]
        img_w, img_h = image_size
        if img_w <= 0 or img_h <= 0:
            return values, [f"invalid image size {image_size}"]
        # x-like values divide by width, y-like by height, in both orderings.
        values = [
            values[0] / img_w,
            values[1] / img_h,
            values[2] / img_w,
            values[3] / img_h,
        ]
    elif convention.space == "unit":
        # Per coordinate, because a model is not necessarily consistent within
        # one box. Both flags are recorded: the first says the model did not do
        # what it was asked, the second says what we did about it. Keeping them
        # separate matters — the non-compliance is a result about the model and
        # must stay visible even though the box is now usable.
        rescaled = [v > 1.0 + TOLERANCE for v in values]
        if any(rescaled):
            repairs.append("out_of_declared_range")
            repairs.append("rescaled_from_grid")
        if all(rescaled):
            # Nothing was in unit scale at all, so this box needed no
            # per-coordinate judgement: plain grid1000 would read it identically.
            repairs.append("wholly_on_grid")
        values = [v / 1000.0 if r else v for v, r in zip(values, rescaled)]
    elif convention.space == "grid1000":
        # Qwen-VL normally uses its native 0-1000 grid, but has occasionally
        # complied with the prompt's requested unit scale for an entire box.
        # Decimal coordinates wholly inside 0-1 are unambiguous evidence of
        # that switch (unlike integer 0/1, which are valid grid coordinates).
        # Preserve those values and record the per-box deviation explicitly.
        wholly_unit_decimal = (
            all(-TOLERANCE <= v <= 1.0 + TOLERANCE for v in values)
            and any(abs(v - round(v)) > TOLERANCE for v in values)
        )
        if wholly_unit_decimal:
            repairs.append("response_scale_override")
            repairs.append("preserved_unit_scale")
        else:
            values = [v / _SCALE[convention.space] for v in values]

    # --- 2. Reduce to offsets and extents --------------------------------
    if order == "xyxy":
        x1, y1, x2, y2 = values
        if x2 < x1:
            x1, x2 = x2, x1
            repairs.append("swapped_x")
        if y2 < y1:
            y1, y2 = y2, y1
            repairs.append("swapped_y")
        values = [x1, y1, x2 - x1, y2 - y1]

    # --- 3. Clip to the frame --------------------------------------------
    x, y, w, h = values
    clipped_x = min(max(x, 0.0), 1.0)
    clipped_y = min(max(y, 0.0), 1.0)
    clipped_w = min(w, 1.0 - clipped_x)
    clipped_h = min(h, 1.0 - clipped_y)
    if (
        abs(clipped_x - x) > TOLERANCE
        or abs(clipped_y - y) > TOLERANCE
        or abs(clipped_w - w) > TOLERANCE
        or abs(clipped_h - h) > TOLERANCE
    ):
        repairs.append("clipped")

    canonical = [round(v, 4) for v in (clipped_x, clipped_y, clipped_w, clipped_h)]
    return canonical, repairs


def looks_like(bbox: list[float], convention: BoxConvention) -> bool:
    """Whether *bbox* is *consistent* with *convention* — never proof of it.

    Used by the probe script to weigh hypotheses and by adapters to report
    format compliance. A single box rarely settles the question; aggregate over
    a whole run before concluding anything.
    """
    if len(bbox) != 4:
        return False

    in_unit = all(-TOLERANCE <= v <= 1.0 + TOLERANCE for v in bbox)
    if convention.space == "unit" and not in_unit:
        return False
    if convention.space == "grid1000" and not all(0 <= v <= 1000 for v in bbox):
        return False


    # Range checks above are order-blind; the shape check below is not.
    order = convention.order
    if order == "yxyx":
        bbox = [bbox[1], bbox[0], bbox[3], bbox[2]]
        order = "xyxy"

    scale = _SCALE.get(convention.space, 1.0)
    x, y, a, b = (v / scale for v in bbox)
    if order == "xywh":
        # Extents must be positive and stay inside the frame.
        return a > 0 and b > 0 and x + a <= 1.0 + TOLERANCE and y + b <= 1.0 + TOLERANCE
    return a > x and b > y