Skip to content

fix(vlm): crop Gemini 2.5/3.5 masks to the image when box_2d leaves 0-1000 - #2793

Merged
Borda merged 3 commits into
roboflow:developfrom
avanish-garg:fix/gemini-box2d-out-of-range
Oct 23, 2026
Merged

Borda merged 3 commits into
roboflow:developfrom
avanish-garg:fix/gemini-box2d-out-of-range

Conversation

@avanish-garg

Copy link
Copy Markdown
Contributor

Description

from_google_gemini_2_5 (also used by GOOGLE_GEMINI_3_5) placed each mask with np_mask[y_min:y_max, x_min:x_max] = ... after resizing the PNG to the whole box. A box_2d coordinate above 1000 or below 0 made the resized mask larger than the slice, or made a negative slice start wrap to an empty slice, so NumPy raised ValueError: could not broadcast input array and the whole response was lost, including every valid item.

Minimal repro (full script in the issue), 1920x1080, one valid item plus one item with box [500, 500, 1001, 1001]:

  • Before: ValueError: could not broadcast input array from shape (541,961) into shape (540,960); [-1, -1, 500, 500] raises ... into shape (0,0).
  • After: both parse. The valid item's mask is unchanged (82944 pixels), the overshooting item gets the part of its mask inside the image (518400 pixels), and xyxy is [192.0, 108.0, 576.0, 324.0] and [960.0, 540.0, 1921.9, 1081.1].

Motivation and Context

Models occasionally overshoot the 0-1000 range, and one such item should not discard a whole response. The function's own contract is exactly one mask per kept item, with every other malformed-mask path degrading to an all-false mask; the Gemini 3.6 parser (polygon_to_mask) and the box-only path already accept the same box.

Closes #2792

Changes Made

  • src/supervision/detection/vlm.py, from_google_gemini_2_5: compute the part of the box inside the image; if none is inside, append an all-false mask (same as the existing empty-box path); otherwise resample straight from the matching part of the PNG (Image.resize(..., box=...)) into that part and assign it. A box fully inside the image uses the full-PNG box, so its mask is the same as before: checked on 1500 random in-range responses (random PNGs, image sizes and boxes), old and new masks and boxes identical.
  • Because only the visible part is resampled, a huge box ([0, 0, 10**9, 10**9]) allocates at most the image size.
  • Docstring sentence on the cropping behaviour; changelog entry under Unreleased.
  • Tests: new TestGeminiMasksForBoxesOutsideImage in tests/detection/test_vlm.py (20 cases): boxes at exactly 1000, overshooting by 1 and by 10, negative, overshooting on both sides, huge (each for Gemini 2.5 and 3.5); boxes wholly outside the image (four positions); the cropped mask is the matching slice of the PNG and not a squashed copy; a response mixing valid, overshooting and wholly-outside items keeps the valid items' masks and boxes; xyxy stays equal to the box-only parse.
  • Left out on purpose: xyxy is not clipped (the box-only and 3.6 paths return it unclipped; see Additional Notes). Other malformed box_2d values (too few elements, NaN/Infinity) fail in other places and are not part of this change.

Testing

Ran on macOS, Python 3.12, uv pip install -e of this branch:

  • New tests on develop (source change stashed): 18 failed, 2 passed (the 2 are the exactly-1000 regression cases); with this change: 20 passed.

  • pytest tests/detection/test_vlm.py plus pytest --doctest-modules src/supervision/detection/vlm.py: 203 passed.

  • pytest tests/detection: 2401 passed, 2 skipped.

  • Whole tests folder: 5811 passed, 2 skipped, 1 failed: tests/cv2/test_integration.py::test_ordinary_suite_passes_when_cv2_is_blocked, which also fails on unmodified develop in my environment. Three metrics test files could not be collected here (missing optional reference packages) and were left out: test_keypoint_mean_average_precision.py, test_mean_average_precision_limits.py, test_sklearn_parity.py.

  • ruff check, ruff format --check, docformatter --check and codespell on the touched files: clean. mypy on vlm.py: one error, Skipping analyzing "deprecate" (missing stubs in my environment), identical on unmodified develop; nothing from the changed lines.

  • Not run: the full pre-commit run --all-files (mdformat for the changelog, prettier, etc.).

  • Added/updated tests, and the full suite passes locally

  • Updated docs (docstrings / mkdocs entry) for new or changed public API

  • Added a changelog entry in docs/changelog.md under Unreleased (skip for lint/type/format-only or pure doc changes)

(First box left unticked: the full suite is not clean in my environment, see Testing.)

Additional Notes

  • Design choice: crop the mask, keep xyxy as returned. The box-only parse and Gemini 3.6 return the same unclipped xyxy, so a response parses to the same boxes with or without masks. Clipping xyxy to the image would be a separate, wider behaviour change; happy to add it here if you prefer.
  • A wholly-outside box keeps its slot with an all-false mask rather than being dropped, so mask stays aligned with xyxy, class_id and confidence.
  • The visible part of the mask is resampled from the corresponding slice of the PNG, so it lines up with where the full box would have drawn it; this is covered by a test that would fail if the whole PNG were squashed into the visible part.
  • Not changed: from_deepseek_vl_2 and Gemini 3.6/3.7 use polygon_to_mask and do not slice-assign, so the same crash does not occur there (checked by running them).

…-1000

A `box_2d` coordinate above 1000 or below 0 made the mask placement in
`from_google_gemini_2_5` raise a NumPy broadcast `ValueError`, discarding
every detection in the response. Place only the part of the mask inside
the image, give a box wholly outside the image an all-false mask, and
keep `xyxy` unclipped as the box-only and Gemini 3.6 paths do.
@Borda Borda added the bug Something isn't working label Oct 23, 2026
@Borda
Borda requested a balanced review from Copilot October 23, 2026 18:16

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Approval recommended

The localized fix has focused regression coverage and no identified blocking defects.

1 open issue
What changed in this PR

🟡 Minor Suggestions

This PR fixes Gemini 2.5/3.5 mask parsing so out-of-range boxes do not discard an entire detection response, addressing #2792.

Changes:

  • Resamples only the visible mask region, keeping allocations bounded by image size.
  • Preserves unclipped boxes and mask alignment, including all-false masks for wholly outside boxes.
  • Adds 20 regression cases and documents the behavior.

The supplied changes cover boundary handling, compatibility, and allocation safety. Tests were not rerun during this review.

Quality: Code 5/5—focused implementation; testing 4/5—targeted regression coverage; documentation 4/5—behavior explained. Overall risk: 1/5.

File Description
tests/​detection/​test_vlm.py Tests cropping, outside boxes, alignment, and unchanged box coordinates.
src/​supervision/​detection/​vlm.py Crops mask placement to image bounds and documents the contract.
docs/​changelog.md Records the Gemini mask-parsing fix.

Review effort: Balanced

Comment thread docs/changelog.md Resolved
Borda and others added 2 commits October 23, 2026 23:05
Changes:
- Integrate the fetched develop target, including grayscale annotator support, overflow-safe box midpoints, precise oriented-box alignment, Pascal VOC coordinate and rounding corrections, and their regression coverage.
- Resolve the Unreleased changelog conflict while retaining both the PR entry and every target entry.

Impact:
- The PR branch now includes current target behavior and tests while preserving the Gemini mask change.
- The changelog conflict resolution changes no PR review finding; the placeholder correction remains a separate selected remediation item.

Verification:
- git merge-tree reported one changelog conflict and clean integration for the other target paths.
- git diff --cached --check passed; the unmerged path list is empty.
- Code tests were not run before this integration commit; the remediation gate remains pending.

Residual limits:
- DOC-1 and the full remediation gates remain pending.

---

Co-authored-by: Codex <[email protected]>
Changes:
- Replace both PR_NUMBER placeholders in the Unreleased Gemini mask entry with PR 2793.
- Link the visible changelog label and destination to the canonical pull request.

Impact:
- Readers can navigate from the changelog entry to the correct pull request.

Verification:
- Full project suite: 5,740 passed, 133 skipped, 37 warnings.
- Pinned MkDocs Markdown format hook passed; exact-link acceptance assertion and git diff --check passed.

Residual limits:
- The local branch was not published; fresh PR metadata reports pre-commit.ci - pr as ERROR, with run details unavailable.

---

Co-authored-by: Codex <[email protected]>
@codecov

codecov Bot commented Oct 23, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 94%. Comparing base (a078c2d) to head (2d4e12f).

Additional details and impacted files
@@           Coverage Diff           @@
##           develop   #2793   +/-   ##
=======================================
  Coverage       94%     94%           
=======================================
  Files           83      83           
  Lines        13695   13702    +7     
=======================================
+ Hits         12904   12911    +7     
  Misses         791     791           
🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@Borda
Borda merged commit b74ed40 into roboflow:develop Oct 23, 2026
35 checks passed
Borda added a commit that referenced this pull request Oct 24, 2026
…-1000 (#2793)

A `box_2d` coordinate above 1000 or below 0 made the mask placement in
`from_google_gemini_2_5` raise a NumPy broadcast `ValueError`, discarding
every detection in the response. Place only the part of the mask inside
the image, give a box wholly outside the image an all-false mask, and
keep `xyxy` unclipped as the box-only and Gemini 3.6 paths do.

---------

Co-authored-by: Jirka Borovec <[email protected]>
Co-authored-by: Codex <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug]: Gemini 2.5 / 3.5 mask parsing raises ValueError for the whole response when box_2d leaves the 0-1000 range

3 participants