Agent-S icon indicating copy to clipboard operation
Agent-S copied to clipboard

fix: improve coordinate precision with multi-sample voting

Open Chase-Xuu opened this issue 9 months ago β€’ 3 comments

Summary

Fixes #175 - Improves coordinate accuracy for small UI elements by implementing multi-sample voting.

Problem

When using Agent-S to click on small UI elements (icons, checkboxes, small buttons), the grounding model's coordinate predictions can be slightly off, causing click failures. This is due to:

  1. Single-point prediction variance from the grounding model
  2. Resolution scaling amplifying small errors
  3. No awareness of target element size

Solution

This PR introduces multi-sample voting for coordinate generation:

  • Added n_samples parameter to generate_coords() (default=1 for backward compatibility)
  • When n_samples > 1, runs the grounding model multiple times and takes the median of predictions
  • Median is more robust to outliers than mean
  • Also refactored coordinate parsing to properly handle both integer and normalized (0-1) coordinate formats

Changes

  • gui_agents/s3/agents/grounding.py:
    • Added _parse_coordinates() helper for robust coordinate extraction
    • Added _normalize_coordinates() to handle 0-1 normalized coords
    • Extended generate_coords() with optional n_samples parameter
    • Added numpy import for median calculation

Usage

# Original behavior (backward compatible)
coords = aci.generate_coords(description, obs)

# Improved accuracy for small elements
coords = aci.generate_coords(description, obs, n_samples=3)

Trade-offs

  • Latency: Nx increase when using multi-sample (can be parallelized in future PR)
  • Cost: Nx API calls (acceptable trade-off for accuracy-critical tasks)

Testing

  • Tested with UI-TARS-1.5-7B on Linux
  • Backward compatible: existing code works without modification

Related

  • Complements PR #159 (normalized coordinate handling) - this PR also handles that case

Summary by CodeRabbit

  • New Features

    • Multi-sample coordinate grounding with median aggregation for more robust localization.
    • Parsing and normalization of coordinates from varied model outputs (absolute and normalized).
  • Improvements

    • Better error handling when no valid samples are produced.
    • Enhanced debug logging and per-sample reporting to aid troubleshooting and validation.

Chase-Xuu avatar Feb 09 '26 21:02 Chase-Xuu

[!NOTE]

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • [ ] ▢️ Resume reviews
  • [ ] πŸ” Trigger review
πŸ“ Walkthrough

Walkthrough

The grounding agent now adds structured coordinate parsing and normalization helpers, imports numpy, and updates generate_coords to accept n_samples for multi-sample coordinate generation, median aggregation, improved logging, and stricter error reporting when no valid samples are found.

Changes

Cohort / File(s) Summary
Grounding agent updates
gui_agents/s3/agents/grounding.py
Imported numpy as np. Added _parse_coordinates(response: str) -> Optional[Tuple[float, float]] and _normalize_coordinates(x: float, y: float) -> Tuple[int, int]. Updated generate_coords(self, ref_expr: str, obs: Dict, n_samples: int = 1) -> List[int] to support single- and multi-sample flows, collect valid samples, compute median with numpy.median, normalize to pixel coordinates, log raw/multi-sample results, and raise ValueError when no valid samples are obtained. Replaced prior simplistic extraction and prints with structured parsing and normalization logic.

Sequence Diagram(s)

sequenceDiagram
    participant Caller as Caller
    participant Agent as OSWorldACI
    participant Model as GroundingModel
    participant Image as Image/Normalizer

    Note over Agent,Model: n_samples >= 1
    Caller->>Agent: generate_coords(ref_expr, obs, n_samples)
    Agent->>Model: reset()/send_prompt(ref_expr, obs)
    Model-->>Agent: raw_response (text with coords)
    loop per sample (if n_samples > 1)
        Agent->>Agent: _parse_coordinates(raw_response)
        Agent->>Agent: collect valid (x,y)
    end
    Agent->>Agent: aggregate samples (numpy.median) if multiple
    Agent->>Image: _normalize_coordinates(x,y)
    Image-->>Agent: (x_pixel,y_pixel)
    Agent-->>Caller: [x_pixel, y_pixel]

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐰 I nibbled lines of code at night,

Parsed tuples by soft starlight.
Samples hopped and joined the dance,
Median settled, gave pixels a chance.
πŸ₯•πŸŒ™

πŸš₯ Pre-merge checks | βœ… 4 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 60.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
βœ… Passed checks (4 passed)
Check name Status Explanation
Description Check βœ… Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check βœ… Passed The title accurately summarizes the main change: implementing multi-sample voting to improve coordinate precision.
Linked Issues check βœ… Passed The changes directly address issue #175 by implementing multi-sample voting and improved coordinate parsing to reduce offset and variance for small UI elements.
Out of Scope Changes check βœ… Passed All changes are scoped to coordinate precision improvements; numpy import, helper methods, and n_samples parameter are directly related to the multi-sample voting objective.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing touches
  • [ ] πŸ“ Generate docstrings
πŸ§ͺ Generate unit tests (beta)
  • [ ] Create PR with unit tests
  • [ ] Post copyable unit tests in a comment

No actionable comments were generated in the recent review. πŸŽ‰

🧹 Recent nitpick comments
gui_agents/s3/agents/grounding.py (2)

229-256: Coordinate parsing looks solid; minor regex tightening possible.

The logic correctly prioritizes parenthesized pairs and falls back to last-two-numbers heuristic, addressing previous review feedback well. One small observation: the capture group [\d.]+ on line 239 is looser than the fallback regex β€” it would match strings like 4.5.6 as a single token. In practice this is unlikely from model output, but you could reuse the same precise pattern for consistency.

Optional tightening
-        paren_match = re.search(r"[\(\[]\s*([\d.]+)\s*,\s*([\d.]+)\s*[\)\]]", response)
+        paren_match = re.search(r"[\(\[]\s*(\d+\.?\d*|\.\d+)\s*,\s*(\d+\.?\d*|\.\d+)\s*[\)\]]", response)

313-327: Partial sample failure is silent β€” consider logging a warning.

If some samples fail to parse (e.g., 2 out of 5), the code silently proceeds with fewer samples. A warning log would help users understand reduced confidence.

Proposed addition after the loop
         if not samples:
             raise ValueError(f"Failed to get valid coordinates after {n_samples} attempts")
+        
+        if len(samples) < n_samples:
+            logger.warning("Only %d/%d samples produced valid coordinates", len(samples), n_samples)

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❀️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

coderabbitai[bot] avatar Feb 09 '26 21:02 coderabbitai[bot]

Hi @coderabbitai! Thanks for the detailed review. I wanted to clarify that the latest commit (234d60f) already addresses the issues you raised:

  1. Multi-sample normalization: The code now collects raw float coordinates, computes the median, and normalizes only once at the end. See lines 318-341 β€” we store raw floats in samples, compute np.median() on them, then call _normalize_coordinates() once.

  2. First vs last two numbers: Already fixed β€” the parser now tries parenthesized pairs (x, y) first, then falls back to taking the last two numbers (numericals[-2], numericals[-1]) to handle prefixes like Point 1:.

  3. Temperature for variance: Already using temperature=0.3 for multi-sample calls (line 321).

Let me know if you'd like any additional changes!

Chase-Xuu avatar Feb 11 '26 02:02 Chase-Xuu

[!TIP] For best results, initiate chat on the files or code changes.

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Fetch the current state of the grounding.py file to verify user's claims
cat gui_agents/s3/agents/grounding.py

Length of output: 32330


@Chase-Xuu, thank you for the clarification! I've verified the code and can confirm that all three issues have indeed been properly addressed:

  1. βœ… Multi-sample normalization (lines 318-341): The implementation correctly collects raw float coordinates in the samples list (line 330), computes the median on the raw floats (lines 346-347), and then calls _normalize_coordinates() exactly once at the end (line 350). This preserves sub-pixel precision throughout the aggregation process.

  2. βœ… Last two numbers (line 274): The parser correctly uses numericals[-2] and numericals[-1] to extract the last two numeric values, which properly handles prefixes like "Point 1: (523, 847)".

  3. βœ… Temperature=0.3 (line 321): Confirmed that temperature=0.3 is passed to call_llm_safe() for multi-sample calls, providing the variance needed for effective voting.

The implementation looks solid! The multi-sample voting approach with median aggregation should provide robust coordinate prediction for small UI elements while maintaining backward compatibility with the default n_samples=1 behavior. Great work on this enhancement! πŸŽ‰

coderabbitai[bot] avatar Feb 11 '26 02:02 coderabbitai[bot]