Instructions to use ruotian/SelectGround-8B with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- PEFT
How to use ruotian/SelectGround-8B with PEFT:
from peft import PeftModel from transformers import AutoModelForCausalLM base_model = AutoModelForCausalLM.from_pretrained("Qwen/Qwen3-VL-8B-Instruct") model = PeftModel.from_pretrained(base_model, "ruotian/SelectGround-8B") - Notebooks
- Google Colab
- Kaggle
Replace with ContrastGround-trained SelectGround-8B
Browse filesPlain-base single-stage SFT plus auxiliary selection loss checkpoint, exact recipe, checksums, and evaluation code.
- README.md +78 -12
- __pycache__/evaluate.cpython-312.pyc +0 -0
- __pycache__/selectground.cpython-312.pyc +0 -0
- __pycache__/train.cpython-312.pyc +0 -0
- adapter_config.json +34 -1
- adapter_model.safetensors +1 -1
- evaluate.py +166 -0
- selectground.py +465 -0
- selection_head.pt +2 -2
- train.py +663 -0
- training_manifest.json +53 -0
README.md
CHANGED
|
@@ -1,27 +1,93 @@
|
|
| 1 |
---
|
| 2 |
-
license: apache-2.0
|
| 3 |
-
library_name: peft
|
| 4 |
base_model: Qwen/Qwen3-VL-8B-Instruct
|
|
|
|
| 5 |
pipeline_tag: image-text-to-text
|
|
|
|
|
|
|
|
|
|
| 6 |
tags:
|
| 7 |
- gui-grounding
|
| 8 |
- computer-use
|
| 9 |
- qwen3-vl
|
| 10 |
-
|
| 11 |
-
-
|
| 12 |
---
|
| 13 |
|
| 14 |
# SelectGround-8B
|
| 15 |
|
| 16 |
-
SelectGround-8B
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
This
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 19 |
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
|
| 25 |
-
|
| 26 |
|
| 27 |
-
|
|
|
|
|
|
|
|
|
| 1 |
---
|
|
|
|
|
|
|
| 2 |
base_model: Qwen/Qwen3-VL-8B-Instruct
|
| 3 |
+
library_name: peft
|
| 4 |
pipeline_tag: image-text-to-text
|
| 5 |
+
license: apache-2.0
|
| 6 |
+
datasets:
|
| 7 |
+
- ruotian/ContrastGround
|
| 8 |
tags:
|
| 9 |
- gui-grounding
|
| 10 |
- computer-use
|
| 11 |
- qwen3-vl
|
| 12 |
+
- lora
|
| 13 |
+
- selectground
|
| 14 |
---
|
| 15 |
|
| 16 |
# SelectGround-8B
|
| 17 |
|
| 18 |
+
SelectGround-8B maps a screenshot and a natural-language instruction to one
|
| 19 |
+
click point. This release replaces the earlier ClickContrast-trained checkpoint
|
| 20 |
+
with a checkpoint trained from the pinned plain Qwen3-VL-8B-Instruct base on
|
| 21 |
+
the `selectground-8b` configuration of
|
| 22 |
+
[`ruotian/ContrastGround`](https://huggingface.co/datasets/ruotian/ContrastGround).
|
| 23 |
+
It is a single directly trained LoRA checkpoint, not a model soup or weight
|
| 24 |
+
aggregate.
|
| 25 |
+
|
| 26 |
+
## Direct grounding results
|
| 27 |
+
|
| 28 |
+
| Benchmark | Accuracy | Semantic error |
|
| 29 |
+
|---|---:|---:|
|
| 30 |
+
| ScreenSpot-Pro | 65.09 | 29.35 |
|
| 31 |
+
| UI-Vision | 37.12 | 49.10 |
|
| 32 |
+
| OSWorld-G | 69.41 | 20.00 |
|
| 33 |
+
|
| 34 |
+
UI-Vision is the equal-weight macro over its basic, functional, and spatial
|
| 35 |
+
element-grounding subsets. OSWorld-G uses its 510 target-bearing examples;
|
| 36 |
+
refusal-only rows are excluded. These public benchmarks were used during model
|
| 37 |
+
selection, so results are test-tuned rather than held-out validation estimates.
|
| 38 |
+
|
| 39 |
+
## Direct inference
|
| 40 |
+
|
| 41 |
+
The repository includes the exact loader and evaluator. `visual_merger.pt` must
|
| 42 |
+
be loaded in addition to the PEFT adapter; `selectground.py` does this.
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
python evaluate.py \
|
| 46 |
+
--model ruotian/SelectGround-8B \
|
| 47 |
+
--benchmark screenspot_pro \
|
| 48 |
+
--data data/screenspot-pro \
|
| 49 |
+
--output outputs/screenspot-pro.jsonl
|
| 50 |
+
```
|
| 51 |
+
|
| 52 |
+
Inference uses the full native screenshot, the prompt in `selectground.py`,
|
| 53 |
+
Qwen smart resize with `min_pixels=3136` and `max_pixels=8847360`, greedy
|
| 54 |
+
decoding for at most 32 tokens, and normalized 0–1000 point coordinates.
|
| 55 |
+
|
| 56 |
+
## Reproduce training from the plain base
|
| 57 |
+
|
| 58 |
+
```bash
|
| 59 |
+
hf download ruotian/ContrastGround --repo-type dataset \
|
| 60 |
+
--local-dir data/ContrastGround
|
| 61 |
+
|
| 62 |
+
PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True \
|
| 63 |
+
accelerate launch --mixed_precision bf16 --num_processes 2 train.py \
|
| 64 |
+
--model 8b \
|
| 65 |
+
--data data/ContrastGround \
|
| 66 |
+
--pairs-file data/ContrastGround/data/selectground-8b/train_pairs.jsonl \
|
| 67 |
+
--replay-file data/ContrastGround/data/selectground-8b/train_replays.jsonl \
|
| 68 |
+
--output outputs/SelectGround-8B \
|
| 69 |
+
--steps 240 --gpus 2 --accumulation 64 \
|
| 70 |
+
--learning-rate 3e-5 --selector-learning-rate 1e-4 \
|
| 71 |
+
--aux-weight 0.1 --ground-coordinate-weight 1.0 \
|
| 72 |
+
--margin 0.3 --pair-weight 0.5 \
|
| 73 |
+
--warmup-steps 10 --scheduler-steps 384 \
|
| 74 |
+
--holdout-fraction 0.02 --seed 20260819
|
| 75 |
+
```
|
| 76 |
|
| 77 |
+
This is SFT coordinate cross-entropy on pair and replay rows plus the paper's
|
| 78 |
+
auxiliary competitor-selection loss on pair rows. Pair and replay microbatches
|
| 79 |
+
alternate. LoRA uses rank 64, alpha 128, dropout 0.05 on
|
| 80 |
+
`q/k/v/o/gate/up/down` projections. The selector reads semantic attention from
|
| 81 |
+
layers 18–23. See `training_manifest.json` for the complete recipe and artifact
|
| 82 |
+
SHA-256 checksums.
|
| 83 |
|
| 84 |
+
The reference environment used PyTorch 2.11.0+cu128, Transformers 4.57.1,
|
| 85 |
+
PEFT 0.19.1, Accelerate 1.13.0, and qwen-vl-utils 0.0.14. CUDA kernels are not
|
| 86 |
+
bitwise deterministic; clean runs should be expected to be close rather than
|
| 87 |
+
byte-identical.
|
| 88 |
|
| 89 |
+
## License and data
|
| 90 |
|
| 91 |
+
The adapter follows the Apache-2.0 license of the base model. Dataset assets
|
| 92 |
+
retain their upstream terms; consult the ContrastGround data card and its
|
| 93 |
+
row-level provenance.
|
__pycache__/evaluate.cpython-312.pyc
ADDED
|
Binary file (9.57 kB). View file
|
|
|
__pycache__/selectground.cpython-312.pyc
ADDED
|
Binary file (25 kB). View file
|
|
|
__pycache__/train.cpython-312.pyc
ADDED
|
Binary file (41.3 kB). View file
|
|
|
adapter_config.json
CHANGED
|
@@ -1,15 +1,48 @@
|
|
| 1 |
{
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
"base_model_name_or_path": "Qwen/Qwen3-VL-8B-Instruct",
|
| 3 |
"bias": "none",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
"inference_mode": true,
|
| 5 |
"init_lora_weights": true,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
"lora_alpha": 128,
|
|
|
|
| 7 |
"lora_dropout": 0.05,
|
|
|
|
|
|
|
|
|
|
|
|
|
| 8 |
"peft_type": "LORA",
|
|
|
|
|
|
|
| 9 |
"r": 64,
|
|
|
|
| 10 |
"revision": "0c351dd01ed87e9c1b53cbc748cba10e6187ff3b",
|
| 11 |
-
"target_modules": [
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"task_type": "CAUSAL_LM",
|
|
|
|
|
|
|
| 13 |
"use_dora": false,
|
|
|
|
| 14 |
"use_rslora": false
|
| 15 |
}
|
|
|
|
| 1 |
{
|
| 2 |
+
"alora_invocation_tokens": null,
|
| 3 |
+
"alpha_pattern": {},
|
| 4 |
+
"arrow_config": null,
|
| 5 |
+
"auto_mapping": null,
|
| 6 |
"base_model_name_or_path": "Qwen/Qwen3-VL-8B-Instruct",
|
| 7 |
"bias": "none",
|
| 8 |
+
"corda_config": null,
|
| 9 |
+
"ensure_weight_tying": false,
|
| 10 |
+
"eva_config": null,
|
| 11 |
+
"exclude_modules": null,
|
| 12 |
+
"fan_in_fan_out": false,
|
| 13 |
"inference_mode": true,
|
| 14 |
"init_lora_weights": true,
|
| 15 |
+
"layer_replication": null,
|
| 16 |
+
"layers_pattern": null,
|
| 17 |
+
"layers_to_transform": null,
|
| 18 |
+
"loftq_config": {},
|
| 19 |
"lora_alpha": 128,
|
| 20 |
+
"lora_bias": false,
|
| 21 |
"lora_dropout": 0.05,
|
| 22 |
+
"lora_ga_config": null,
|
| 23 |
+
"megatron_config": null,
|
| 24 |
+
"megatron_core": "megatron.core",
|
| 25 |
+
"modules_to_save": null,
|
| 26 |
"peft_type": "LORA",
|
| 27 |
+
"peft_version": "0.19.1",
|
| 28 |
+
"qalora_group_size": 16,
|
| 29 |
"r": 64,
|
| 30 |
+
"rank_pattern": {},
|
| 31 |
"revision": "0c351dd01ed87e9c1b53cbc748cba10e6187ff3b",
|
| 32 |
+
"target_modules": [
|
| 33 |
+
"q_proj",
|
| 34 |
+
"v_proj",
|
| 35 |
+
"gate_proj",
|
| 36 |
+
"down_proj",
|
| 37 |
+
"k_proj",
|
| 38 |
+
"up_proj",
|
| 39 |
+
"o_proj"
|
| 40 |
+
],
|
| 41 |
+
"target_parameters": null,
|
| 42 |
"task_type": "CAUSAL_LM",
|
| 43 |
+
"trainable_token_indices": null,
|
| 44 |
+
"use_bdlora": null,
|
| 45 |
"use_dora": false,
|
| 46 |
+
"use_qalora": false,
|
| 47 |
"use_rslora": false
|
| 48 |
}
|
adapter_model.safetensors
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
size 349251816
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6ff35d55e9000af46eb6e134b78c7c0029369bf3ec5fe74d2dfb29f3a09e923c
|
| 3 |
size 349251816
|
evaluate.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import argparse
|
| 2 |
+
import io
|
| 3 |
+
import itertools
|
| 4 |
+
import json
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
from selectground import SelectGround
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def load_cases(name: str, root: Path):
|
| 13 |
+
if name == "screenspot_pro":
|
| 14 |
+
parquet_files = sorted((root / "data").glob("*.parquet"))
|
| 15 |
+
if parquet_files:
|
| 16 |
+
import pyarrow.parquet as parquet
|
| 17 |
+
|
| 18 |
+
for path in parquet_files:
|
| 19 |
+
for batch in parquet.ParquetFile(path).iter_batches(batch_size=1):
|
| 20 |
+
row = batch.to_pylist()[0]
|
| 21 |
+
encoded = row["image"]
|
| 22 |
+
image = Image.open(io.BytesIO(encoded["bytes"])).convert("RGB")
|
| 23 |
+
yield {
|
| 24 |
+
"id": row["id"],
|
| 25 |
+
"image": image,
|
| 26 |
+
"image_name": encoded.get("path") or row["id"],
|
| 27 |
+
"instruction": row["instruction"],
|
| 28 |
+
"target": row["bbox"],
|
| 29 |
+
"type": "xyxy",
|
| 30 |
+
"group": row.get("group"),
|
| 31 |
+
}
|
| 32 |
+
else:
|
| 33 |
+
for annotation in sorted((root / "annotations").glob("*.json")):
|
| 34 |
+
for row in json.loads(annotation.read_text()):
|
| 35 |
+
yield {
|
| 36 |
+
"id": row["id"],
|
| 37 |
+
"image": root / "images" / row["img_filename"],
|
| 38 |
+
"image_name": row["img_filename"],
|
| 39 |
+
"instruction": row["instruction"],
|
| 40 |
+
"target": row["bbox"],
|
| 41 |
+
"type": "xyxy",
|
| 42 |
+
"group": row.get("group"),
|
| 43 |
+
}
|
| 44 |
+
elif name == "ui_vision":
|
| 45 |
+
for split in ("basic", "functional", "spatial"):
|
| 46 |
+
path = root / "annotations" / "element_grounding" / f"element_grounding_{split}.json"
|
| 47 |
+
for index, row in enumerate(json.loads(path.read_text())):
|
| 48 |
+
yield {
|
| 49 |
+
"id": f"{split}-{index}",
|
| 50 |
+
"image": root / "images" / row["image_path"],
|
| 51 |
+
"image_name": row["image_path"],
|
| 52 |
+
"instruction": row["prompt_to_evaluate"],
|
| 53 |
+
"target": row["bbox"],
|
| 54 |
+
"type": "xyxy",
|
| 55 |
+
"group": split,
|
| 56 |
+
}
|
| 57 |
+
else:
|
| 58 |
+
benchmark = root / "benchmark" if (root / "benchmark").is_dir() else root
|
| 59 |
+
for row in json.loads((benchmark / "OSWorld-G.json").read_text()):
|
| 60 |
+
if row["box_type"] == "refusal":
|
| 61 |
+
continue
|
| 62 |
+
yield {
|
| 63 |
+
"id": row["id"],
|
| 64 |
+
"image": benchmark / "images" / row["image_path"],
|
| 65 |
+
"image_name": row["image_path"],
|
| 66 |
+
"instruction": row["instruction"],
|
| 67 |
+
"target": row["box_coordinates"],
|
| 68 |
+
"type": row["box_type"],
|
| 69 |
+
"group": None,
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def contains(point, target, target_type):
|
| 74 |
+
if point is None:
|
| 75 |
+
return False
|
| 76 |
+
x, y = point
|
| 77 |
+
if target_type in {"bbox", "xyxy"}:
|
| 78 |
+
if target_type == "xyxy":
|
| 79 |
+
left, top, right, bottom = target
|
| 80 |
+
else:
|
| 81 |
+
left, top, width, height = target[:4]
|
| 82 |
+
right, bottom = left + width, top + height
|
| 83 |
+
center_x, center_y = (left + right) / 2, (top + bottom) / 2
|
| 84 |
+
half_width, half_height = abs(right - left) / 2, abs(bottom - top) / 2
|
| 85 |
+
return (
|
| 86 |
+
center_x - half_width <= x <= center_x + half_width
|
| 87 |
+
and center_y - half_height <= y <= center_y + half_height
|
| 88 |
+
)
|
| 89 |
+
vertices = list(zip(target[0::2], target[1::2]))
|
| 90 |
+
previous, inside = vertices[-1], False
|
| 91 |
+
for current in vertices:
|
| 92 |
+
x1, y1 = current
|
| 93 |
+
x2, y2 = previous
|
| 94 |
+
cross = (x - x1) * (y2 - y1) - (y - y1) * (x2 - x1)
|
| 95 |
+
if abs(cross) <= 1e-7 and min(x1, x2) - 1e-7 <= x <= max(x1, x2) + 1e-7 and min(y1, y2) - 1e-7 <= y <= max(y1, y2) + 1e-7:
|
| 96 |
+
return True
|
| 97 |
+
if (y1 > y) != (y2 > y) and x < (x2 - x1) * (y - y1) / (y2 - y1) + x1:
|
| 98 |
+
inside = not inside
|
| 99 |
+
previous = current
|
| 100 |
+
return inside
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def metrics(rows, benchmark):
|
| 104 |
+
if benchmark != "ui_vision":
|
| 105 |
+
return {"total": len(rows), "correct": sum(row["correct"] for row in rows), "accuracy": 100 * sum(row["correct"] for row in rows) / len(rows)}
|
| 106 |
+
splits = {}
|
| 107 |
+
for split in ("basic", "functional", "spatial"):
|
| 108 |
+
selected = [row for row in rows if row["group"] == split]
|
| 109 |
+
if selected:
|
| 110 |
+
splits[split] = 100 * sum(row["correct"] for row in selected) / len(selected)
|
| 111 |
+
return {"total": len(rows), "accuracy": sum(splits.values()) / len(splits), "splits": splits}
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
parser = argparse.ArgumentParser(description="Evaluate SelectGround on a GUI grounding benchmark.")
|
| 115 |
+
parser.add_argument("--model", default="ruotian/SelectGround-8B")
|
| 116 |
+
parser.add_argument("--benchmark", choices=("screenspot_pro", "ui_vision", "osworld_g"), required=True)
|
| 117 |
+
parser.add_argument("--data", type=Path, required=True)
|
| 118 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 119 |
+
parser.add_argument("--lcr", action="store_true")
|
| 120 |
+
parser.add_argument(
|
| 121 |
+
"--lcr-variant",
|
| 122 |
+
choices=("full", "no_competitor", "one_competitor", "no_incumbent"),
|
| 123 |
+
default="full",
|
| 124 |
+
)
|
| 125 |
+
parser.add_argument("--limit", type=int)
|
| 126 |
+
parser.add_argument("--num-shards", type=int, default=1)
|
| 127 |
+
parser.add_argument("--shard", type=int, default=0)
|
| 128 |
+
args = parser.parse_args()
|
| 129 |
+
|
| 130 |
+
cases = (
|
| 131 |
+
case for index, case in enumerate(load_cases(args.benchmark, args.data))
|
| 132 |
+
if index % args.num_shards == args.shard
|
| 133 |
+
)
|
| 134 |
+
if args.limit is not None:
|
| 135 |
+
cases = itertools.islice(cases, args.limit)
|
| 136 |
+
existing = []
|
| 137 |
+
if args.output.exists():
|
| 138 |
+
existing = [json.loads(line) for line in args.output.read_text().splitlines() if line.strip()]
|
| 139 |
+
done = {row["id"] for row in existing}
|
| 140 |
+
grounder = SelectGround(args.model)
|
| 141 |
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
| 142 |
+
with args.output.open("a") as output:
|
| 143 |
+
for number, case in enumerate(cases, 1):
|
| 144 |
+
if case["id"] in done:
|
| 145 |
+
continue
|
| 146 |
+
prediction = grounder.predict(
|
| 147 |
+
case["image"],
|
| 148 |
+
case["instruction"],
|
| 149 |
+
lcr=args.lcr,
|
| 150 |
+
benchmark=args.benchmark,
|
| 151 |
+
lcr_variant=args.lcr_variant,
|
| 152 |
+
)
|
| 153 |
+
row = {
|
| 154 |
+
"id": case["id"],
|
| 155 |
+
"instruction": case["instruction"],
|
| 156 |
+
"image": case["image_name"],
|
| 157 |
+
"point": prediction["point"],
|
| 158 |
+
"correct": contains(prediction["point"], case["target"], case["type"]),
|
| 159 |
+
"group": case["group"],
|
| 160 |
+
"prediction": prediction,
|
| 161 |
+
}
|
| 162 |
+
output.write(json.dumps(row) + "\n")
|
| 163 |
+
output.flush()
|
| 164 |
+
existing.append(row)
|
| 165 |
+
print(f"[{number}] {case['id']} correct={int(row['correct'])}", flush=True)
|
| 166 |
+
print(json.dumps(metrics(existing, args.benchmark), indent=2))
|
selectground.py
ADDED
|
@@ -0,0 +1,465 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
| 1 |
+
import json
|
| 2 |
+
import math
|
| 3 |
+
import re
|
| 4 |
+
from itertools import combinations
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
import torch
|
| 9 |
+
from PIL import Image
|
| 10 |
+
from huggingface_hub import snapshot_download
|
| 11 |
+
from peft import PeftModel
|
| 12 |
+
from transformers import AutoModelForImageTextToText, AutoProcessor
|
| 13 |
+
from transformers.cache_utils import DynamicCache
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
PROMPT = """You are an expert GUI grounding model.
|
| 17 |
+
Given a screenshot and an instruction, point to the UI element that should be clicked.
|
| 18 |
+
Return only one point as [x, y], where x and y are normalized integers from 0 to 1000 relative to the full image.
|
| 19 |
+
For an element with area, return the center point.
|
| 20 |
+
Instruction: {instruction}"""
|
| 21 |
+
|
| 22 |
+
LCR_PROMPT = """You are an expert UI element locator. Given a GUI image and a user's element description, provide the coordinates of the specified element as a single (x,y) point. The image resolution is height {height} and width {width}. For elements with area, return the center point.
|
| 23 |
+
|
| 24 |
+
Output the coordinate pair exactly:
|
| 25 |
+
(x,y)"""
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class SelectGround:
|
| 29 |
+
"""SelectGround direct grounding and LCR test-time inference."""
|
| 30 |
+
|
| 31 |
+
def __init__(self, checkpoint: str = "ruotian/SelectGround-8B") -> None:
|
| 32 |
+
checkpoint_path = Path(checkpoint)
|
| 33 |
+
if not checkpoint_path.exists():
|
| 34 |
+
checkpoint_path = Path(snapshot_download(checkpoint))
|
| 35 |
+
adapter_config = json.loads((checkpoint_path / "adapter_config.json").read_text())
|
| 36 |
+
base_model = adapter_config["base_model_name_or_path"]
|
| 37 |
+
revision = adapter_config["revision"]
|
| 38 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 39 |
+
base_model,
|
| 40 |
+
revision=revision,
|
| 41 |
+
dtype=torch.bfloat16,
|
| 42 |
+
device_map="auto",
|
| 43 |
+
attn_implementation="sdpa",
|
| 44 |
+
)
|
| 45 |
+
self.model = PeftModel.from_pretrained(model, checkpoint_path)
|
| 46 |
+
merger = torch.load(checkpoint_path / "visual_merger.pt", map_location="cpu")
|
| 47 |
+
parameters = dict(self.model.named_parameters())
|
| 48 |
+
with torch.no_grad():
|
| 49 |
+
for name, value in merger.get("state_dict", merger).items():
|
| 50 |
+
parameters[name].copy_(value.to(parameters[name].device, parameters[name].dtype))
|
| 51 |
+
self.model.eval()
|
| 52 |
+
self.model.config.use_cache = True
|
| 53 |
+
self.processor = AutoProcessor.from_pretrained(
|
| 54 |
+
base_model,
|
| 55 |
+
revision=revision,
|
| 56 |
+
min_pixels=3136,
|
| 57 |
+
max_pixels=8847360,
|
| 58 |
+
)
|
| 59 |
+
self.device = next(self.model.parameters()).device
|
| 60 |
+
self.core = self.model.get_base_model().model
|
| 61 |
+
self.vision_start_token_id = int(self.core.config.vision_start_token_id)
|
| 62 |
+
self.vision_end_token_id = int(self.core.config.vision_end_token_id)
|
| 63 |
+
self.merge_size = int(self.core.config.vision_config.spatial_merge_size)
|
| 64 |
+
self.large_lcr = len(self.core.language_model.layers) > 36
|
| 65 |
+
|
| 66 |
+
def predict(
|
| 67 |
+
self,
|
| 68 |
+
image: str | Path | Image.Image,
|
| 69 |
+
instruction: str,
|
| 70 |
+
*,
|
| 71 |
+
lcr: bool = False,
|
| 72 |
+
benchmark: str | None = None,
|
| 73 |
+
lcr_variant: str = "full",
|
| 74 |
+
) -> dict[str, Any]:
|
| 75 |
+
"""Return a source-image click; benchmark only selects UI-Vision's crop size."""
|
| 76 |
+
source = Image.open(image).convert("RGB") if not isinstance(image, Image.Image) else image.convert("RGB")
|
| 77 |
+
size = source.size
|
| 78 |
+
p0, attention, grid = self._observe(
|
| 79 |
+
source,
|
| 80 |
+
instruction,
|
| 81 |
+
capture_attention=lcr,
|
| 82 |
+
lcr_prompt=lcr and not self.large_lcr,
|
| 83 |
+
)
|
| 84 |
+
if not lcr:
|
| 85 |
+
return {"method": "SelectGround", **p0}
|
| 86 |
+
if p0["point"] is None:
|
| 87 |
+
return {"method": "SelectGround+LCR", **p0}
|
| 88 |
+
|
| 89 |
+
attention_boxes = (
|
| 90 |
+
_attention_crops(attention, grid, size, benchmark)
|
| 91 |
+
if attention is not None
|
| 92 |
+
else []
|
| 93 |
+
)
|
| 94 |
+
if lcr_variant not in {"full", "no_competitor", "one_competitor", "no_incumbent"}:
|
| 95 |
+
raise ValueError(f"unknown LCR variant: {lcr_variant}")
|
| 96 |
+
if lcr_variant == "no_competitor":
|
| 97 |
+
attention_boxes = []
|
| 98 |
+
elif lcr_variant == "one_competitor":
|
| 99 |
+
attention_boxes = attention_boxes[:1]
|
| 100 |
+
if self.large_lcr:
|
| 101 |
+
views = [
|
| 102 |
+
*((box, 2.0) for box in attention_boxes[:1]),
|
| 103 |
+
(_fraction_crop(p0["point"], size, 0.25, 256), 2.5),
|
| 104 |
+
(_fraction_crop(p0["point"], size, 0.40, 320), 2.0),
|
| 105 |
+
]
|
| 106 |
+
else:
|
| 107 |
+
views = [
|
| 108 |
+
*((box, 2.0) for box in attention_boxes),
|
| 109 |
+
(_pixel_budget_crop(p0["point"], size, 501_760), 1.5),
|
| 110 |
+
]
|
| 111 |
+
if lcr_variant == "no_incumbent":
|
| 112 |
+
views = views[:-2] if self.large_lcr else views[:-1]
|
| 113 |
+
observations = [(p0, (0, 0, size[0], size[1]))]
|
| 114 |
+
for box, scale in views:
|
| 115 |
+
crop = source.crop(box)
|
| 116 |
+
view = crop.resize(
|
| 117 |
+
(round(crop.width * scale), round(crop.height * scale)),
|
| 118 |
+
Image.Resampling.LANCZOS if self.large_lcr else Image.Resampling.BICUBIC,
|
| 119 |
+
)
|
| 120 |
+
prediction, _, _ = self._observe(
|
| 121 |
+
view, instruction, lcr_prompt=not self.large_lcr
|
| 122 |
+
)
|
| 123 |
+
if prediction["point"] is not None:
|
| 124 |
+
observations.append((_map_crop(prediction, box, size, scale), box))
|
| 125 |
+
if len(observations) == 1:
|
| 126 |
+
return {"method": "SelectGround+LCR", **p0}
|
| 127 |
+
first, second = min(
|
| 128 |
+
combinations(range(len(observations)), 2),
|
| 129 |
+
key=lambda pair: (
|
| 130 |
+
_distance(
|
| 131 |
+
observations[pair[0]][0]["point"],
|
| 132 |
+
observations[pair[1]][0]["point"],
|
| 133 |
+
size,
|
| 134 |
+
),
|
| 135 |
+
pair,
|
| 136 |
+
),
|
| 137 |
+
)
|
| 138 |
+
selected = min(
|
| 139 |
+
(first, second),
|
| 140 |
+
key=lambda index: (_area(observations[index][1]), index),
|
| 141 |
+
)
|
| 142 |
+
result = observations[selected][0]
|
| 143 |
+
return {
|
| 144 |
+
"method": "SelectGround+LCR",
|
| 145 |
+
"point": result["point"],
|
| 146 |
+
"normalized_point": result["normalized_point"],
|
| 147 |
+
"raw_response": result["raw_response"],
|
| 148 |
+
}
|
| 149 |
+
|
| 150 |
+
def _observe(
|
| 151 |
+
self,
|
| 152 |
+
image: Image.Image,
|
| 153 |
+
instruction: str,
|
| 154 |
+
*,
|
| 155 |
+
capture_attention: bool = False,
|
| 156 |
+
lcr_prompt: bool = False,
|
| 157 |
+
) -> tuple[dict[str, Any], torch.Tensor | None, tuple[int, int]]:
|
| 158 |
+
inputs = self._inputs(image, instruction, lcr_prompt)
|
| 159 |
+
input_ids = inputs["input_ids"]
|
| 160 |
+
length = int(input_ids.shape[1])
|
| 161 |
+
image_grid = inputs["image_grid_thw"][0].detach().cpu().long()
|
| 162 |
+
grid = (int(image_grid[1]) // self.merge_size, int(image_grid[2]) // self.merge_size)
|
| 163 |
+
position_ids, _ = self.core.get_rope_index(
|
| 164 |
+
input_ids,
|
| 165 |
+
inputs.get("image_grid_thw"),
|
| 166 |
+
inputs.get("video_grid_thw"),
|
| 167 |
+
attention_mask=inputs.get("attention_mask"),
|
| 168 |
+
)
|
| 169 |
+
cache = DynamicCache(config=self.core.language_model.config)
|
| 170 |
+
attention = (
|
| 171 |
+
_Attention(
|
| 172 |
+
self.core,
|
| 173 |
+
input_ids,
|
| 174 |
+
self.vision_start_token_id,
|
| 175 |
+
self.vision_end_token_id,
|
| 176 |
+
)
|
| 177 |
+
if capture_attention
|
| 178 |
+
else None
|
| 179 |
+
)
|
| 180 |
+
with torch.inference_mode():
|
| 181 |
+
output = self.model(
|
| 182 |
+
**inputs,
|
| 183 |
+
past_key_values=cache,
|
| 184 |
+
position_ids=position_ids,
|
| 185 |
+
cache_position=torch.arange(length, device=self.device),
|
| 186 |
+
use_cache=True,
|
| 187 |
+
logits_to_keep=1,
|
| 188 |
+
)
|
| 189 |
+
raw = self._decode(
|
| 190 |
+
output.logits[:, -1, :],
|
| 191 |
+
cache,
|
| 192 |
+
position_ids[:, :, -1:] + 1,
|
| 193 |
+
attention,
|
| 194 |
+
)
|
| 195 |
+
return (
|
| 196 |
+
_prediction(raw, image.size, integer=lcr_prompt),
|
| 197 |
+
attention.scores if attention else None,
|
| 198 |
+
grid,
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
def _decode(
|
| 202 |
+
self,
|
| 203 |
+
logits: torch.Tensor,
|
| 204 |
+
cache: DynamicCache,
|
| 205 |
+
position_ids: torch.Tensor,
|
| 206 |
+
attention: "_Attention | None",
|
| 207 |
+
) -> str:
|
| 208 |
+
stop = {
|
| 209 |
+
token
|
| 210 |
+
for token in (
|
| 211 |
+
self.processor.tokenizer.eos_token_id,
|
| 212 |
+
self.processor.tokenizer.pad_token_id,
|
| 213 |
+
)
|
| 214 |
+
if token is not None
|
| 215 |
+
}
|
| 216 |
+
generated = []
|
| 217 |
+
for _ in range(32):
|
| 218 |
+
token = int(logits.argmax())
|
| 219 |
+
if token in stop:
|
| 220 |
+
break
|
| 221 |
+
generated.append(token)
|
| 222 |
+
token_text = self.processor.decode([token])
|
| 223 |
+
if attention is not None and ("," in token_text or "," in token_text):
|
| 224 |
+
attention.install(cache)
|
| 225 |
+
try:
|
| 226 |
+
output = self.model(
|
| 227 |
+
input_ids=torch.tensor([[token]], device=self.device),
|
| 228 |
+
past_key_values=cache,
|
| 229 |
+
position_ids=position_ids,
|
| 230 |
+
cache_position=torch.tensor(
|
| 231 |
+
[cache.get_seq_length()], device=self.device
|
| 232 |
+
),
|
| 233 |
+
use_cache=True,
|
| 234 |
+
logits_to_keep=1,
|
| 235 |
+
)
|
| 236 |
+
finally:
|
| 237 |
+
if attention is not None and attention.handle is not None:
|
| 238 |
+
attention.remove()
|
| 239 |
+
cache = output.past_key_values
|
| 240 |
+
logits = output.logits[:, -1, :]
|
| 241 |
+
position_ids = position_ids + 1
|
| 242 |
+
return self.processor.decode(
|
| 243 |
+
generated,
|
| 244 |
+
skip_special_tokens=True,
|
| 245 |
+
clean_up_tokenization_spaces=False,
|
| 246 |
+
).strip()
|
| 247 |
+
|
| 248 |
+
def _inputs(
|
| 249 |
+
self, image: Image.Image, instruction: str, lcr_prompt: bool
|
| 250 |
+
) -> Any:
|
| 251 |
+
from qwen_vl_utils import process_vision_info, smart_resize
|
| 252 |
+
|
| 253 |
+
if lcr_prompt:
|
| 254 |
+
resized_height, resized_width = smart_resize(
|
| 255 |
+
image.height,
|
| 256 |
+
image.width,
|
| 257 |
+
factor=(
|
| 258 |
+
self.processor.image_processor.patch_size
|
| 259 |
+
* self.processor.image_processor.merge_size
|
| 260 |
+
),
|
| 261 |
+
min_pixels=self.processor.image_processor.min_pixels,
|
| 262 |
+
max_pixels=self.processor.image_processor.max_pixels,
|
| 263 |
+
)
|
| 264 |
+
image = image.resize((resized_width, resized_height))
|
| 265 |
+
messages = [
|
| 266 |
+
{
|
| 267 |
+
"role": "system",
|
| 268 |
+
"content": LCR_PROMPT.format(
|
| 269 |
+
height=resized_height, width=resized_width
|
| 270 |
+
),
|
| 271 |
+
},
|
| 272 |
+
{
|
| 273 |
+
"role": "user",
|
| 274 |
+
"content": [
|
| 275 |
+
{"type": "image", "image": image},
|
| 276 |
+
{"type": "text", "text": instruction},
|
| 277 |
+
],
|
| 278 |
+
},
|
| 279 |
+
]
|
| 280 |
+
else:
|
| 281 |
+
messages = [{
|
| 282 |
+
"role": "user",
|
| 283 |
+
"content": [
|
| 284 |
+
{"type": "image", "image": image},
|
| 285 |
+
{"type": "text", "text": PROMPT.format(instruction=instruction)},
|
| 286 |
+
],
|
| 287 |
+
}]
|
| 288 |
+
text = self.processor.apply_chat_template(
|
| 289 |
+
messages, tokenize=False, add_generation_prompt=True
|
| 290 |
+
)
|
| 291 |
+
image_inputs, video_inputs = process_vision_info(messages)
|
| 292 |
+
return self.processor(
|
| 293 |
+
text=[text],
|
| 294 |
+
images=image_inputs,
|
| 295 |
+
videos=video_inputs,
|
| 296 |
+
padding=True,
|
| 297 |
+
return_tensors="pt",
|
| 298 |
+
).to(self.device)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
class _Attention:
|
| 302 |
+
def __init__(
|
| 303 |
+
self,
|
| 304 |
+
model: Any,
|
| 305 |
+
input_ids: torch.Tensor,
|
| 306 |
+
vision_start: int,
|
| 307 |
+
vision_end: int,
|
| 308 |
+
) -> None:
|
| 309 |
+
self.model = model
|
| 310 |
+
self.handle: Any = None
|
| 311 |
+
start = int(torch.nonzero(input_ids[0] == vision_start)[0]) + 1
|
| 312 |
+
end = int(torch.nonzero(input_ids[0] == vision_end)[0])
|
| 313 |
+
self.visual = torch.arange(start, end, device=input_ids.device)
|
| 314 |
+
self.cache: DynamicCache | None = None
|
| 315 |
+
self.scores: torch.Tensor | None = None
|
| 316 |
+
|
| 317 |
+
def install(self, cache: DynamicCache) -> None:
|
| 318 |
+
self.cache = cache
|
| 319 |
+
layers = self.model.language_model.layers
|
| 320 |
+
layer = layers[2 * len(layers) // 3].self_attn
|
| 321 |
+
self.handle = layer.register_forward_hook(self._hook, with_kwargs=True)
|
| 322 |
+
|
| 323 |
+
def remove(self) -> None:
|
| 324 |
+
self.handle.remove()
|
| 325 |
+
self.handle = None
|
| 326 |
+
|
| 327 |
+
def _hook(
|
| 328 |
+
self,
|
| 329 |
+
module: Any,
|
| 330 |
+
args: tuple[Any, ...],
|
| 331 |
+
kwargs: dict[str, Any],
|
| 332 |
+
output: Any,
|
| 333 |
+
) -> None:
|
| 334 |
+
from transformers.models.qwen3_vl.modeling_qwen3_vl import (
|
| 335 |
+
apply_rotary_pos_emb,
|
| 336 |
+
repeat_kv,
|
| 337 |
+
)
|
| 338 |
+
|
| 339 |
+
hidden = kwargs.get("hidden_states", args[0] if args else None)
|
| 340 |
+
shape = (*hidden.shape[:-1], -1, int(module.head_dim))
|
| 341 |
+
query = module.q_norm(module.q_proj(hidden).view(shape)).transpose(1, 2)
|
| 342 |
+
query, _ = apply_rotary_pos_emb(
|
| 343 |
+
query, query, *kwargs["position_embeddings"]
|
| 344 |
+
)
|
| 345 |
+
keys = repeat_kv(
|
| 346 |
+
self.cache.layers[module.layer_idx].keys,
|
| 347 |
+
int(module.num_key_value_groups),
|
| 348 |
+
)
|
| 349 |
+
weights = torch.matmul(query, keys.transpose(-2, -1)) * module.scaling
|
| 350 |
+
weights = weights.squeeze(2).softmax(-1).max(1).values[0]
|
| 351 |
+
self.scores = (
|
| 352 |
+
weights.index_select(0, self.visual.to(weights.device))
|
| 353 |
+
.detach()
|
| 354 |
+
.float()
|
| 355 |
+
.cpu()
|
| 356 |
+
)
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
def _prediction(
|
| 360 |
+
raw: str, size: tuple[int, int], *, integer: bool = False
|
| 361 |
+
) -> dict[str, Any]:
|
| 362 |
+
match = re.search(
|
| 363 |
+
r"[\[((]\s*(?:x\s*=\s*)?(-?\d+(?:\.\d+)?)\s*[,,]\s*"
|
| 364 |
+
r"(?:y\s*=\s*)?(-?\d+(?:\.\d+)?)\s*[\]))]",
|
| 365 |
+
raw,
|
| 366 |
+
flags=re.IGNORECASE,
|
| 367 |
+
)
|
| 368 |
+
normalized = [float(match.group(1)), float(match.group(2))] if match else None
|
| 369 |
+
point = [normalized[0] / 1000 * size[0], normalized[1] / 1000 * size[1]] if normalized else None
|
| 370 |
+
if point is not None and integer:
|
| 371 |
+
point = [int(value) for value in point]
|
| 372 |
+
return {"point": point, "normalized_point": normalized, "raw_response": raw}
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
def _map_crop(
|
| 376 |
+
prediction: dict[str, Any],
|
| 377 |
+
box: tuple[int, int, int, int],
|
| 378 |
+
size: tuple[int, int],
|
| 379 |
+
scale: float,
|
| 380 |
+
) -> dict[str, Any]:
|
| 381 |
+
point = prediction["point"]
|
| 382 |
+
mapped = [box[0] + point[0] / scale, box[1] + point[1] / scale]
|
| 383 |
+
normalized = [mapped[0] / size[0] * 1000, mapped[1] / size[1] * 1000]
|
| 384 |
+
raw = f"[{round(normalized[0])},{round(normalized[1])}]"
|
| 385 |
+
return {"point": mapped, "normalized_point": normalized, "raw_response": raw}
|
| 386 |
+
|
| 387 |
+
|
| 388 |
+
def _pixel_budget_crop(
|
| 389 |
+
point: list[float], size: tuple[int, int], pixels: int
|
| 390 |
+
) -> tuple[int, int, int, int]:
|
| 391 |
+
width, height = size
|
| 392 |
+
fraction = min(1.0, math.sqrt(pixels / (width * height)))
|
| 393 |
+
crop_width = max(1, round(fraction * width))
|
| 394 |
+
crop_height = max(1, round(fraction * height))
|
| 395 |
+
left = round(min(max(0.0, point[0] - crop_width / 2), width - crop_width))
|
| 396 |
+
top = round(min(max(0.0, point[1] - crop_height / 2), height - crop_height))
|
| 397 |
+
return left, top, left + crop_width, top + crop_height
|
| 398 |
+
|
| 399 |
+
|
| 400 |
+
def _fraction_crop(
|
| 401 |
+
point: list[float],
|
| 402 |
+
size: tuple[int, int],
|
| 403 |
+
fraction: float,
|
| 404 |
+
minimum: int,
|
| 405 |
+
) -> tuple[int, int, int, int]:
|
| 406 |
+
width, height = size
|
| 407 |
+
crop_width = min(width, max(minimum, round(fraction * width)))
|
| 408 |
+
crop_height = min(height, max(minimum, round(fraction * height)))
|
| 409 |
+
left = round(min(max(0.0, point[0] - crop_width / 2), width - crop_width))
|
| 410 |
+
top = round(min(max(0.0, point[1] - crop_height / 2), height - crop_height))
|
| 411 |
+
return left, top, left + crop_width, top + crop_height
|
| 412 |
+
|
| 413 |
+
|
| 414 |
+
def _attention_crops(
|
| 415 |
+
attention: torch.Tensor,
|
| 416 |
+
grid: tuple[int, int],
|
| 417 |
+
size: tuple[int, int],
|
| 418 |
+
benchmark: str | None,
|
| 419 |
+
) -> list[tuple[int, int, int, int]]:
|
| 420 |
+
width, height = size
|
| 421 |
+
window = (1280, 720) if benchmark == "ui_vision" else (1288, 728)
|
| 422 |
+
crop_width, crop_height = min(window[0], width), min(window[1], height)
|
| 423 |
+
top = attention.topk(min(100, attention.numel())).indices.tolist()
|
| 424 |
+
positions = [
|
| 425 |
+
((index % grid[1] + 0.5) / grid[1] * width,
|
| 426 |
+
(index // grid[1] + 0.5) / grid[0] * height)
|
| 427 |
+
for index in top
|
| 428 |
+
]
|
| 429 |
+
ranked = []
|
| 430 |
+
for x, y in positions:
|
| 431 |
+
left = min(max(0.0, x - crop_width / 2), width - crop_width)
|
| 432 |
+
upper = min(max(0.0, y - crop_height / 2), height - crop_height)
|
| 433 |
+
box = (
|
| 434 |
+
int(left),
|
| 435 |
+
int(upper),
|
| 436 |
+
int(left + crop_width),
|
| 437 |
+
int(upper + crop_height),
|
| 438 |
+
)
|
| 439 |
+
coverage = sum(
|
| 440 |
+
left <= px <= left + crop_width
|
| 441 |
+
and upper <= py <= upper + crop_height
|
| 442 |
+
for px, py in positions
|
| 443 |
+
)
|
| 444 |
+
ranked.append((coverage, box))
|
| 445 |
+
ranked.sort(key=lambda row: row[0], reverse=True)
|
| 446 |
+
selected = []
|
| 447 |
+
for _, box in ranked:
|
| 448 |
+
if box not in selected:
|
| 449 |
+
selected.append(box)
|
| 450 |
+
if len(selected) == 2:
|
| 451 |
+
break
|
| 452 |
+
return selected
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
def _distance(
|
| 456 |
+
first: list[float], second: list[float], size: tuple[int, int]
|
| 457 |
+
) -> float:
|
| 458 |
+
return math.hypot(
|
| 459 |
+
(first[0] - second[0]) / size[0],
|
| 460 |
+
(first[1] - second[1]) / size[1],
|
| 461 |
+
)
|
| 462 |
+
|
| 463 |
+
|
| 464 |
+
def _area(box: tuple[int, int, int, int]) -> int:
|
| 465 |
+
return (box[2] - box[0]) * (box[3] - box[1])
|
selection_head.pt
CHANGED
|
@@ -1,3 +1,3 @@
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
-
oid sha256:
|
| 3 |
-
size
|
|
|
|
| 1 |
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e74db8e7fc9344ccc477d66d2439a53e67a646eca57bf1fabc7b790bdb0ab420
|
| 3 |
+
size 2458
|
train.py
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import argparse
|
| 4 |
+
import json
|
| 5 |
+
import math
|
| 6 |
+
import random
|
| 7 |
+
import signal
|
| 8 |
+
import shutil
|
| 9 |
+
import time
|
| 10 |
+
from contextlib import nullcontext
|
| 11 |
+
from pathlib import Path
|
| 12 |
+
from typing import Any
|
| 13 |
+
|
| 14 |
+
import numpy as np
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn.functional as F
|
| 17 |
+
from accelerate import Accelerator
|
| 18 |
+
from accelerate.utils import DistributedDataParallelKwargs, set_seed
|
| 19 |
+
from peft import LoraConfig, PeftModel, get_peft_model
|
| 20 |
+
from torch import nn
|
| 21 |
+
from torch.utils.data import DataLoader, Dataset
|
| 22 |
+
from transformers import AutoConfig, AutoModelForImageTextToText, AutoProcessor, get_scheduler
|
| 23 |
+
|
| 24 |
+
from selectground import PROMPT
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
RECIPES = {
|
| 28 |
+
"8b": {
|
| 29 |
+
"base": "Qwen/Qwen3-VL-8B-Instruct",
|
| 30 |
+
"revision": "0c351dd01ed87e9c1b53cbc748cba10e6187ff3b",
|
| 31 |
+
"data": "ruotian/ContrastGround",
|
| 32 |
+
"steps": 135,
|
| 33 |
+
"gpus": 2,
|
| 34 |
+
"accumulation": 64,
|
| 35 |
+
"learning_rate": 5e-5,
|
| 36 |
+
},
|
| 37 |
+
"30b": {
|
| 38 |
+
"base": "Qwen/Qwen3-VL-30B-A3B-Instruct",
|
| 39 |
+
"revision": "9c4b90e1e4ba969fd3b5378b57d966d725f1b86c",
|
| 40 |
+
"data": "ruotian/ContrastGround",
|
| 41 |
+
"steps": 200,
|
| 42 |
+
"gpus": 4,
|
| 43 |
+
"accumulation": 4,
|
| 44 |
+
"learning_rate": 4e-5,
|
| 45 |
+
},
|
| 46 |
+
}
|
| 47 |
+
LAYERS = list(range(18, 24))
|
| 48 |
+
SEED = 20260625
|
| 49 |
+
PREEMPT_REQUESTED = False
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def request_preemption(_signum: int, _frame: Any) -> None:
|
| 53 |
+
global PREEMPT_REQUESTED
|
| 54 |
+
PREEMPT_REQUESTED = True
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def replace_with_retry(source: Path, destination: Path, attempts: int = 5) -> None:
|
| 58 |
+
for attempt in range(attempts):
|
| 59 |
+
try:
|
| 60 |
+
source.replace(destination)
|
| 61 |
+
return
|
| 62 |
+
except OSError:
|
| 63 |
+
if attempt + 1 == attempts:
|
| 64 |
+
raise
|
| 65 |
+
time.sleep(2 ** attempt)
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
def _value(obj: Any, name: str, default: Any = None) -> Any:
|
| 69 |
+
return obj.get(name, default) if isinstance(obj, dict) else getattr(obj, name, default)
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _find_config(model: Any) -> Any:
|
| 73 |
+
config = getattr(model, "config", None)
|
| 74 |
+
if config is None or _value(config, "vision_config") is None:
|
| 75 |
+
raise ValueError("Could not find the Qwen3-VL model config")
|
| 76 |
+
return config
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _repeat_key_value_heads(key_states: torch.Tensor, groups: int) -> torch.Tensor:
|
| 80 |
+
if groups == 1:
|
| 81 |
+
return key_states
|
| 82 |
+
batch, heads, sequence, head_dim = key_states.shape
|
| 83 |
+
return (
|
| 84 |
+
key_states[:, :, None, :, :]
|
| 85 |
+
.expand(batch, heads, groups, sequence, head_dim)
|
| 86 |
+
.reshape(batch, heads * groups, sequence, head_dim)
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _attention_logits(
|
| 91 |
+
attention: Any,
|
| 92 |
+
hidden_states: torch.Tensor,
|
| 93 |
+
query_position: int,
|
| 94 |
+
visual_positions: torch.Tensor,
|
| 95 |
+
position_embeddings: tuple[torch.Tensor, torch.Tensor] | None,
|
| 96 |
+
) -> torch.Tensor:
|
| 97 |
+
if position_embeddings is None:
|
| 98 |
+
raise RuntimeError("Qwen3-VL semantic logits require position_embeddings")
|
| 99 |
+
head_dim = int(attention.head_dim)
|
| 100 |
+
hidden_shape = (*hidden_states.shape[:-1], -1, head_dim)
|
| 101 |
+
query_states = attention.q_norm(attention.q_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 102 |
+
key_states = attention.k_norm(attention.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 103 |
+
from transformers.models.qwen3_vl.modeling_qwen3_vl import apply_rotary_pos_emb
|
| 104 |
+
|
| 105 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, *position_embeddings)
|
| 106 |
+
key_states = _repeat_key_value_heads(key_states, int(getattr(attention, "num_key_value_groups", 1)))
|
| 107 |
+
positions = visual_positions.to(device=hidden_states.device, dtype=torch.long)
|
| 108 |
+
query = query_states[:, :, int(query_position), :]
|
| 109 |
+
visual_keys = key_states.index_select(2, positions)
|
| 110 |
+
logits = (query.unsqueeze(2) * visual_keys).sum(dim=-1) * float(getattr(attention, "scaling", 1.0))
|
| 111 |
+
return logits.squeeze(0)
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def load_visual_merger(model: Any, checkpoint: Path) -> None:
|
| 115 |
+
merger_path = checkpoint / "visual_merger.pt"
|
| 116 |
+
if not merger_path.is_file():
|
| 117 |
+
raise FileNotFoundError(f"Missing visual merger checkpoint: {merger_path}")
|
| 118 |
+
merger = torch.load(merger_path, map_location="cpu", weights_only=False)
|
| 119 |
+
parameters = dict(model.named_parameters())
|
| 120 |
+
state = merger.get("state_dict", merger)
|
| 121 |
+
missing = sorted(set(state) - set(parameters))
|
| 122 |
+
if missing:
|
| 123 |
+
raise KeyError(f"Visual merger parameters missing from model: {missing[:3]}")
|
| 124 |
+
with torch.no_grad():
|
| 125 |
+
for name, value in state.items():
|
| 126 |
+
parameters[name].copy_(value.to(parameters[name].device, parameters[name].dtype))
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
class Rows(Dataset):
|
| 130 |
+
def __init__(self, rows: list[dict[str, Any]], root: Path) -> None:
|
| 131 |
+
self.rows, self.root = rows, root
|
| 132 |
+
|
| 133 |
+
def __len__(self) -> int:
|
| 134 |
+
return len(self.rows)
|
| 135 |
+
|
| 136 |
+
def __getitem__(self, index: int) -> dict[str, Any]:
|
| 137 |
+
return {**self.rows[index], "image": str(self.root / self.rows[index]["image"])}
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
class HeadSelector(nn.Module):
|
| 141 |
+
def __init__(self, heads: int) -> None:
|
| 142 |
+
super().__init__()
|
| 143 |
+
self.layer_head_weights = nn.Parameter(torch.zeros(len(LAYERS), heads))
|
| 144 |
+
|
| 145 |
+
def forward(self, values: list[torch.Tensor]) -> torch.Tensor:
|
| 146 |
+
stacked = torch.stack([value.float() for value in values])
|
| 147 |
+
weights = self.layer_head_weights.flatten().softmax(0).view_as(self.layer_head_weights).to(stacked.device)
|
| 148 |
+
return (stacked * weights[:, :, None]).sum(dim=(0, 1))
|
| 149 |
+
|
| 150 |
+
|
| 151 |
+
class Attention:
|
| 152 |
+
def __init__(self, model: Any, query: int, visual: torch.Tensor) -> None:
|
| 153 |
+
self.model, self.query, self.visual = model, query, visual
|
| 154 |
+
self.values: dict[int, torch.Tensor] = {}
|
| 155 |
+
self.handles: list[Any] = []
|
| 156 |
+
|
| 157 |
+
def __enter__(self) -> "Attention":
|
| 158 |
+
for module in self.model.modules():
|
| 159 |
+
layer = getattr(module, "layer_idx", None)
|
| 160 |
+
if layer in LAYERS and hasattr(module, "q_proj"):
|
| 161 |
+
self.handles.append(module.register_forward_hook(self._hook(int(layer)), with_kwargs=True))
|
| 162 |
+
return self
|
| 163 |
+
|
| 164 |
+
def __exit__(self, *_: Any) -> None:
|
| 165 |
+
for handle in self.handles:
|
| 166 |
+
handle.remove()
|
| 167 |
+
|
| 168 |
+
def _hook(self, layer: int):
|
| 169 |
+
def hook(module: Any, args: tuple[Any, ...], kwargs: dict[str, Any], output: Any) -> None:
|
| 170 |
+
hidden = kwargs.get("hidden_states", args[0] if args else None)
|
| 171 |
+
if hidden is not None and hidden.shape[1] > self.query:
|
| 172 |
+
self.values[layer] = _attention_logits(
|
| 173 |
+
module, hidden, self.query, self.visual, kwargs["position_embeddings"]
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
return hook
|
| 177 |
+
|
| 178 |
+
def ordered(self) -> list[torch.Tensor]:
|
| 179 |
+
return [self.values[layer] for layer in LAYERS]
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
def read_rows(path: Path) -> list[dict[str, Any]]:
|
| 183 |
+
return [json.loads(line) for line in path.read_text().splitlines() if line.strip()]
|
| 184 |
+
|
| 185 |
+
|
| 186 |
+
def stage_files(stage: str) -> tuple[str, str]:
|
| 187 |
+
if stage == "main":
|
| 188 |
+
return "train_pairs.jsonl", "train_replay.jsonl"
|
| 189 |
+
if stage == "refinement":
|
| 190 |
+
return "refinement_pairs.jsonl", "refinement_replay.jsonl"
|
| 191 |
+
raise ValueError(f"Unknown training stage: {stage}")
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
def loader(rows: list[dict[str, Any]], root: Path, seed: int) -> DataLoader:
|
| 195 |
+
return DataLoader(
|
| 196 |
+
Rows(rows, root),
|
| 197 |
+
batch_size=1,
|
| 198 |
+
shuffle=True,
|
| 199 |
+
collate_fn=lambda batch: batch[0],
|
| 200 |
+
generator=torch.Generator().manual_seed(seed),
|
| 201 |
+
)
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
def next_row(data_loader: DataLoader, iterator: Any):
|
| 205 |
+
try:
|
| 206 |
+
return next(iterator), iterator
|
| 207 |
+
except StopIteration:
|
| 208 |
+
iterator = iter(data_loader)
|
| 209 |
+
return next(iterator), iterator
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def encode(processor: Any, row: dict[str, Any], device: torch.device):
|
| 213 |
+
from qwen_vl_utils import process_vision_info
|
| 214 |
+
|
| 215 |
+
user = {
|
| 216 |
+
"role": "user",
|
| 217 |
+
"content": [
|
| 218 |
+
{"type": "image", "image": row["image"]},
|
| 219 |
+
{"type": "text", "text": PROMPT.format(instruction=row["instruction"])},
|
| 220 |
+
],
|
| 221 |
+
}
|
| 222 |
+
prompt = [user]
|
| 223 |
+
full = [user, {"role": "assistant", "content": [{"type": "text", "text": row["response"]}]}]
|
| 224 |
+
|
| 225 |
+
def process(messages: list[dict[str, Any]], generation_prompt: bool):
|
| 226 |
+
text = processor.apply_chat_template(messages, tokenize=False, add_generation_prompt=generation_prompt)
|
| 227 |
+
images, videos = process_vision_info(messages)
|
| 228 |
+
kwargs = {"text": [text], "images": images, "padding": True, "return_tensors": "pt"}
|
| 229 |
+
if videos is not None:
|
| 230 |
+
kwargs["videos"] = videos
|
| 231 |
+
return processor(**kwargs).to(device)
|
| 232 |
+
|
| 233 |
+
inputs = process(full, False)
|
| 234 |
+
prompt_length = int(process(prompt, True)["attention_mask"].sum())
|
| 235 |
+
labels = inputs["input_ids"].clone()
|
| 236 |
+
labels[:, :prompt_length] = -100
|
| 237 |
+
return inputs, labels, prompt_length - 1
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
def coordinate_loss(logits: torch.Tensor, input_ids: torch.Tensor, labels: torch.Tensor) -> torch.Tensor:
|
| 241 |
+
start = input_ids.shape[1] - logits.shape[1]
|
| 242 |
+
targets = input_ids[:, start + 1 :]
|
| 243 |
+
mask = labels[:, start + 1 :].ne(-100)
|
| 244 |
+
token_logps = logits[:, :-1].float().log_softmax(-1).gather(-1, targets.unsqueeze(-1)).squeeze(-1)
|
| 245 |
+
return -(token_logps * mask).sum().to(logits.dtype) / mask.sum()
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def coordinate_weight(row: dict[str, Any], ground_weight: float) -> float:
|
| 249 |
+
component = str(row.get("source_ref", {}).get("component") or "")
|
| 250 |
+
return ground_weight if component.startswith("ground_") else 1.0
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def box_mask(box: list[float], row: dict[str, Any], grid: torch.Tensor, config: Any) -> torch.Tensor:
|
| 254 |
+
vision = _value(config, "vision_config")
|
| 255 |
+
patch, merge = int(_value(vision, "patch_size", 16)), int(_value(vision, "spatial_merge_size", 2))
|
| 256 |
+
grid = grid.detach().cpu().long()
|
| 257 |
+
height, width = int(grid[1]) // merge, int(grid[2]) // merge
|
| 258 |
+
resized_width, resized_height = int(grid[2]) * patch, int(grid[1]) * patch
|
| 259 |
+
x1, y1, x2, y2 = box
|
| 260 |
+
left, right = sorted((x1 / row["image_width"] * resized_width, x2 / row["image_width"] * resized_width))
|
| 261 |
+
top, bottom = sorted((y1 / row["image_height"] * resized_height, y2 / row["image_height"] * resized_height))
|
| 262 |
+
rows = torch.arange(height)[:, None]
|
| 263 |
+
columns = torch.arange(width)[None, :]
|
| 264 |
+
return (
|
| 265 |
+
(left < (columns + 1) * resized_width / width)
|
| 266 |
+
& (right > columns * resized_width / width)
|
| 267 |
+
& (top < (rows + 1) * resized_height / height)
|
| 268 |
+
& (bottom > rows * resized_height / height)
|
| 269 |
+
).flatten()
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def region_score(scores: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
|
| 273 |
+
selected = scores[mask.to(scores.device)]
|
| 274 |
+
return torch.logsumexp(selected.float(), 0) - math.log(selected.numel())
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
def selection_loss(
|
| 278 |
+
scores: torch.Tensor,
|
| 279 |
+
row: dict[str, Any],
|
| 280 |
+
grid: torch.Tensor,
|
| 281 |
+
config: Any,
|
| 282 |
+
margin: float,
|
| 283 |
+
pair_weight: float,
|
| 284 |
+
) -> torch.Tensor:
|
| 285 |
+
target = box_mask(row["target_bbox"], row, grid, config)
|
| 286 |
+
distractor = box_mask(row["distractor_bbox"], row, grid, config)
|
| 287 |
+
overlap = target & distractor
|
| 288 |
+
target, distractor = target & ~overlap, distractor & ~overlap
|
| 289 |
+
if not target.any() or not distractor.any():
|
| 290 |
+
return scores.sum() * 0
|
| 291 |
+
target_score, distractor_score = region_score(scores, target), region_score(scores, distractor)
|
| 292 |
+
candidates = [target, distractor]
|
| 293 |
+
extras = []
|
| 294 |
+
for index, box in enumerate(row.get("candidate_bboxes", [])):
|
| 295 |
+
mask = box_mask(box, row, grid, config)
|
| 296 |
+
if mask.any() and not (mask & target).any() and not (mask & distractor).any():
|
| 297 |
+
extras.append((float(region_score(scores, mask).detach()), -index, mask))
|
| 298 |
+
extras.sort(reverse=True, key=lambda item: item[:2])
|
| 299 |
+
candidates.extend(item[2] for item in extras[:3])
|
| 300 |
+
listwise = torch.logsumexp(torch.stack([region_score(scores, mask) for mask in candidates]), 0) - target_score
|
| 301 |
+
pair = F.softplus(scores.new_tensor(margin) - target_score + distractor_score)
|
| 302 |
+
return listwise + pair_weight * pair
|
| 303 |
+
|
| 304 |
+
|
| 305 |
+
def warmup_cosine(step: int, warmup: int, total: int) -> float:
|
| 306 |
+
if step < warmup:
|
| 307 |
+
return step / warmup
|
| 308 |
+
if step >= total:
|
| 309 |
+
return 0.0
|
| 310 |
+
return .5 * (1 + math.cos(math.pi * (step - warmup) / (total - warmup)))
|
| 311 |
+
|
| 312 |
+
|
| 313 |
+
def scheduler_for(optimizer: torch.optim.Optimizer, warmup_steps: int, training_steps: int):
|
| 314 |
+
return get_scheduler(
|
| 315 |
+
"cosine",
|
| 316 |
+
optimizer=optimizer,
|
| 317 |
+
num_warmup_steps=warmup_steps,
|
| 318 |
+
num_training_steps=training_steps,
|
| 319 |
+
)
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
def paper_scheduler_for(
|
| 323 |
+
optimizer: torch.optim.Optimizer,
|
| 324 |
+
phase_a_steps: int,
|
| 325 |
+
phase_a_warmup_steps: int,
|
| 326 |
+
phase_a_scheduler_steps: int,
|
| 327 |
+
phase_b_warmup_steps: int,
|
| 328 |
+
phase_b_scheduler_steps: int,
|
| 329 |
+
phase_b_learning_rate: float,
|
| 330 |
+
phase_b_selector_learning_rate: float,
|
| 331 |
+
):
|
| 332 |
+
base_lrs = [group["lr"] for group in optimizer.param_groups]
|
| 333 |
+
target_lrs = [phase_b_learning_rate, phase_b_selector_learning_rate]
|
| 334 |
+
functions = []
|
| 335 |
+
for base, target in zip(base_lrs, target_lrs):
|
| 336 |
+
def schedule(step: int, base=base, target=target):
|
| 337 |
+
if step < phase_a_steps + 1:
|
| 338 |
+
return warmup_cosine(step, phase_a_warmup_steps, phase_a_scheduler_steps)
|
| 339 |
+
return target / base * warmup_cosine(
|
| 340 |
+
step - phase_a_steps,
|
| 341 |
+
phase_b_warmup_steps,
|
| 342 |
+
phase_b_scheduler_steps,
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
functions.append(schedule)
|
| 346 |
+
return torch.optim.lr_scheduler.LambdaLR(optimizer, functions)
|
| 347 |
+
|
| 348 |
+
|
| 349 |
+
def save(
|
| 350 |
+
accelerator: Accelerator,
|
| 351 |
+
model: Any,
|
| 352 |
+
selector: Any,
|
| 353 |
+
optimizer: torch.optim.Optimizer,
|
| 354 |
+
scheduler: torch.optim.lr_scheduler.LRScheduler,
|
| 355 |
+
processor: Any,
|
| 356 |
+
output: Path,
|
| 357 |
+
revision: str,
|
| 358 |
+
completed: int,
|
| 359 |
+
stage: str,
|
| 360 |
+
micro_step: int,
|
| 361 |
+
) -> None:
|
| 362 |
+
atomic = output.name.startswith("step-")
|
| 363 |
+
target = output.with_name(f"{output.name}.incomplete") if atomic else output
|
| 364 |
+
accelerator.wait_for_everyone()
|
| 365 |
+
if accelerator.is_main_process:
|
| 366 |
+
if atomic and target.exists():
|
| 367 |
+
shutil.rmtree(target)
|
| 368 |
+
target.mkdir(parents=True, exist_ok=True)
|
| 369 |
+
(target / "checkpoint_complete").unlink(missing_ok=True)
|
| 370 |
+
unwrapped = accelerator.unwrap_model(model)
|
| 371 |
+
unwrapped.save_pretrained(target, safe_serialization=True)
|
| 372 |
+
config_path = target / "adapter_config.json"
|
| 373 |
+
config = json.loads(config_path.read_text())
|
| 374 |
+
config["revision"] = revision
|
| 375 |
+
config_path.write_text(json.dumps(config, indent=2) + "\n")
|
| 376 |
+
merger = {name: value.detach().cpu() for name, value in unwrapped.named_parameters() if ".visual.merger." in f".{name}"}
|
| 377 |
+
torch.save({"state_dict": merger}, target / "visual_merger.pt")
|
| 378 |
+
head = accelerator.unwrap_model(selector)
|
| 379 |
+
torch.save({"layers": LAYERS, "layer_head_weights": head.layer_head_weights.detach().cpu()}, target / "selection_head.pt")
|
| 380 |
+
torch.save(
|
| 381 |
+
{
|
| 382 |
+
"completed": completed,
|
| 383 |
+
"micro_step": micro_step,
|
| 384 |
+
"stage": stage,
|
| 385 |
+
"optimizer": optimizer.state_dict(),
|
| 386 |
+
"scheduler": scheduler.state_dict(),
|
| 387 |
+
},
|
| 388 |
+
target / "training_state.pt",
|
| 389 |
+
)
|
| 390 |
+
processor.save_pretrained(target)
|
| 391 |
+
accelerator.wait_for_everyone()
|
| 392 |
+
rng = {
|
| 393 |
+
"python": random.getstate(),
|
| 394 |
+
"numpy": np.random.get_state(),
|
| 395 |
+
"torch": torch.get_rng_state(),
|
| 396 |
+
"cuda": torch.cuda.get_rng_state_all(),
|
| 397 |
+
}
|
| 398 |
+
torch.save(rng, target / f"rng_state_rank_{accelerator.process_index}.pt")
|
| 399 |
+
accelerator.wait_for_everyone()
|
| 400 |
+
if accelerator.is_main_process:
|
| 401 |
+
(target / "checkpoint_complete").write_text("complete\n", encoding="utf-8")
|
| 402 |
+
accelerator.wait_for_everyone()
|
| 403 |
+
if accelerator.is_main_process and atomic:
|
| 404 |
+
if output.exists():
|
| 405 |
+
shutil.rmtree(output)
|
| 406 |
+
replace_with_retry(target, output)
|
| 407 |
+
accelerator.wait_for_everyone()
|
| 408 |
+
if accelerator.is_main_process and atomic:
|
| 409 |
+
for previous in output.parent.glob("step-*"):
|
| 410 |
+
if previous != output and (previous / "checkpoint_complete").is_file():
|
| 411 |
+
shutil.rmtree(previous)
|
| 412 |
+
accelerator.wait_for_everyone()
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
def restore(
|
| 416 |
+
checkpoint: Path,
|
| 417 |
+
optimizer: torch.optim.Optimizer,
|
| 418 |
+
scheduler: Any,
|
| 419 |
+
accelerator: Accelerator,
|
| 420 |
+
stage: str,
|
| 421 |
+
accumulation: int,
|
| 422 |
+
) -> tuple[int, int]:
|
| 423 |
+
state = torch.load(checkpoint / "training_state.pt", map_location="cpu", weights_only=False)
|
| 424 |
+
optimizer.load_state_dict(state["optimizer"])
|
| 425 |
+
scheduler.load_state_dict(state["scheduler"])
|
| 426 |
+
rng = torch.load(
|
| 427 |
+
checkpoint / f"rng_state_rank_{accelerator.process_index}.pt",
|
| 428 |
+
map_location="cpu",
|
| 429 |
+
weights_only=False,
|
| 430 |
+
)
|
| 431 |
+
random.setstate(rng["python"])
|
| 432 |
+
np.random.set_state(rng["numpy"])
|
| 433 |
+
torch.set_rng_state(rng["torch"])
|
| 434 |
+
torch.cuda.set_rng_state_all(rng["cuda"])
|
| 435 |
+
completed = int(state["completed"])
|
| 436 |
+
saved_stage = state.get("stage")
|
| 437 |
+
micro_step = int(state.get("micro_step", completed * accumulation)) if saved_stage == stage else 0
|
| 438 |
+
return completed, micro_step
|
| 439 |
+
|
| 440 |
+
|
| 441 |
+
def main() -> None:
|
| 442 |
+
signal.signal(signal.SIGUSR1, request_preemption)
|
| 443 |
+
parser = argparse.ArgumentParser(description="Train SelectGround on local paired and replay JSONL files.")
|
| 444 |
+
parser.add_argument("--model", choices=("8b", "30b"), default="8b")
|
| 445 |
+
parser.add_argument("--data", type=Path, required=True)
|
| 446 |
+
parser.add_argument("--output", type=Path, required=True)
|
| 447 |
+
parser.add_argument("--checkpoint", type=Path)
|
| 448 |
+
parser.add_argument("--initialize-from", type=Path)
|
| 449 |
+
parser.add_argument("--stage", choices=("main", "refinement"), default="main")
|
| 450 |
+
parser.add_argument("--pairs-file", type=Path)
|
| 451 |
+
parser.add_argument("--replay-file", type=Path)
|
| 452 |
+
parser.add_argument("--steps", type=int, required=True)
|
| 453 |
+
parser.add_argument("--gpus", type=int, default=4)
|
| 454 |
+
parser.add_argument("--accumulation", type=int, default=32)
|
| 455 |
+
parser.add_argument("--learning-rate", type=float, default=5e-5)
|
| 456 |
+
parser.add_argument("--selector-learning-rate", type=float, default=1e-4)
|
| 457 |
+
parser.add_argument("--aux-weight", type=float, default=0.1)
|
| 458 |
+
parser.add_argument("--ground-coordinate-weight", type=float, default=1.0)
|
| 459 |
+
parser.add_argument("--margin", type=float, default=0.3)
|
| 460 |
+
parser.add_argument("--pair-weight", type=float, default=0.5)
|
| 461 |
+
parser.add_argument("--warmup-steps", type=int, default=10)
|
| 462 |
+
parser.add_argument("--scheduler-steps", type=int)
|
| 463 |
+
parser.add_argument("--paper-two-stage", action="store_true")
|
| 464 |
+
parser.add_argument("--phase-a-steps", type=int)
|
| 465 |
+
parser.add_argument("--phase-b-warmup-steps", type=int, default=10)
|
| 466 |
+
parser.add_argument("--phase-b-scheduler-steps", type=int, default=25)
|
| 467 |
+
parser.add_argument("--phase-b-learning-rate", type=float, default=1e-6)
|
| 468 |
+
parser.add_argument("--phase-b-selector-learning-rate", type=float, default=1e-4)
|
| 469 |
+
parser.add_argument("--holdout-fraction", type=float, default=0.0)
|
| 470 |
+
parser.add_argument("--max-pixels", type=int, default=8847360)
|
| 471 |
+
parser.add_argument("--seed", type=int, default=SEED)
|
| 472 |
+
parser.add_argument("--save-every", type=int, default=25)
|
| 473 |
+
args = parser.parse_args()
|
| 474 |
+
if args.checkpoint is not None and args.initialize_from is not None:
|
| 475 |
+
raise ValueError("Use only one of --checkpoint and --initialize-from")
|
| 476 |
+
if (args.pairs_file is None) != (args.replay_file is None):
|
| 477 |
+
raise ValueError("--pairs-file and --replay-file must be used together")
|
| 478 |
+
if args.paper_two_stage and args.phase_a_steps is None:
|
| 479 |
+
raise ValueError("--paper-two-stage requires --phase-a-steps")
|
| 480 |
+
recipe = RECIPES[args.model]
|
| 481 |
+
accelerator = Accelerator(
|
| 482 |
+
gradient_accumulation_steps=args.accumulation,
|
| 483 |
+
kwargs_handlers=[DistributedDataParallelKwargs(find_unused_parameters=False)],
|
| 484 |
+
)
|
| 485 |
+
if accelerator.num_processes != args.gpus:
|
| 486 |
+
raise ValueError(f"Expected {args.gpus} processes, got {accelerator.num_processes}")
|
| 487 |
+
set_seed(args.seed + accelerator.process_index)
|
| 488 |
+
data = args.data
|
| 489 |
+
pair_file, replay_file = stage_files(args.stage)
|
| 490 |
+
pairs_path = args.pairs_file or data / "data" / pair_file
|
| 491 |
+
replay_path = args.replay_file or data / "data" / replay_file
|
| 492 |
+
pairs = read_rows(pairs_path)
|
| 493 |
+
replay = read_rows(replay_path)
|
| 494 |
+
if args.stage == "main" and args.holdout_fraction > 0:
|
| 495 |
+
random.Random(args.seed).shuffle(pairs)
|
| 496 |
+
pairs = pairs[max(1, round(args.holdout_fraction * len(pairs))) :]
|
| 497 |
+
seed_offset = 1000 if args.stage == "main" else 3000
|
| 498 |
+
pair_seed, replay_seed = args.seed + seed_offset + 1, args.seed + seed_offset + 1001
|
| 499 |
+
pair_loader, replay_loader = loader(pairs, data, pair_seed), loader(replay, data, replay_seed)
|
| 500 |
+
|
| 501 |
+
processor = AutoProcessor.from_pretrained(
|
| 502 |
+
recipe["base"], revision=recipe["revision"], min_pixels=3136, max_pixels=args.max_pixels
|
| 503 |
+
)
|
| 504 |
+
base_config = AutoConfig.from_pretrained(recipe["base"], revision=recipe["revision"])
|
| 505 |
+
model = AutoModelForImageTextToText.from_pretrained(
|
| 506 |
+
recipe["base"], revision=recipe["revision"], config=base_config,
|
| 507 |
+
dtype=torch.bfloat16, attn_implementation="sdpa"
|
| 508 |
+
)
|
| 509 |
+
source_checkpoint = args.checkpoint or args.initialize_from
|
| 510 |
+
if source_checkpoint is None:
|
| 511 |
+
model = get_peft_model(model, LoraConfig(
|
| 512 |
+
r=64,
|
| 513 |
+
lora_alpha=128,
|
| 514 |
+
lora_dropout=.05,
|
| 515 |
+
target_modules=["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"],
|
| 516 |
+
task_type="CAUSAL_LM",
|
| 517 |
+
))
|
| 518 |
+
else:
|
| 519 |
+
import transformers.integrations.tensor_parallel as tensor_parallel
|
| 520 |
+
|
| 521 |
+
if not hasattr(tensor_parallel, "EmbeddingParallel"):
|
| 522 |
+
tensor_parallel.EmbeddingParallel = type("EmbeddingParallel", (), {})
|
| 523 |
+
model = PeftModel.from_pretrained(model, source_checkpoint, is_trainable=True)
|
| 524 |
+
load_visual_merger(model, source_checkpoint)
|
| 525 |
+
for parameter in model.parameters():
|
| 526 |
+
if parameter.requires_grad:
|
| 527 |
+
parameter.data = parameter.data.to(torch.bfloat16)
|
| 528 |
+
model.gradient_checkpointing_enable(gradient_checkpointing_kwargs={"use_reentrant": False})
|
| 529 |
+
model.enable_input_require_grads()
|
| 530 |
+
model.config.use_cache = False
|
| 531 |
+
config = _find_config(model)
|
| 532 |
+
heads = int(_value(_value(config, "text_config", config), "num_attention_heads"))
|
| 533 |
+
selector = HeadSelector(heads)
|
| 534 |
+
if source_checkpoint is not None:
|
| 535 |
+
head = torch.load(source_checkpoint / "selection_head.pt", map_location="cpu", weights_only=False)
|
| 536 |
+
selector.layer_head_weights.data.copy_(head["layer_head_weights"])
|
| 537 |
+
optimizer = torch.optim.AdamW([
|
| 538 |
+
{"params": [parameter for parameter in model.parameters() if parameter.requires_grad], "lr": args.learning_rate},
|
| 539 |
+
{"params": selector.parameters(), "lr": args.selector_learning_rate},
|
| 540 |
+
], weight_decay=0.0)
|
| 541 |
+
if args.paper_two_stage:
|
| 542 |
+
scheduler = paper_scheduler_for(
|
| 543 |
+
optimizer,
|
| 544 |
+
phase_a_steps=args.phase_a_steps,
|
| 545 |
+
phase_a_warmup_steps=args.warmup_steps,
|
| 546 |
+
phase_a_scheduler_steps=args.scheduler_steps or args.steps,
|
| 547 |
+
phase_b_warmup_steps=args.phase_b_warmup_steps,
|
| 548 |
+
phase_b_scheduler_steps=args.phase_b_scheduler_steps,
|
| 549 |
+
phase_b_learning_rate=args.phase_b_learning_rate,
|
| 550 |
+
phase_b_selector_learning_rate=args.phase_b_selector_learning_rate,
|
| 551 |
+
)
|
| 552 |
+
else:
|
| 553 |
+
scheduler = scheduler_for(optimizer, args.warmup_steps, args.scheduler_steps or args.steps)
|
| 554 |
+
model, selector, optimizer, pair_loader, replay_loader = accelerator.prepare(
|
| 555 |
+
model, selector, optimizer, pair_loader, replay_loader
|
| 556 |
+
)
|
| 557 |
+
model.train()
|
| 558 |
+
selector.train()
|
| 559 |
+
iterators = [iter(pair_loader), iter(replay_loader)]
|
| 560 |
+
completed, micro_step = (
|
| 561 |
+
restore(args.checkpoint, optimizer, scheduler, accelerator, args.stage, args.accumulation)
|
| 562 |
+
if args.checkpoint
|
| 563 |
+
else (0, 0)
|
| 564 |
+
)
|
| 565 |
+
if micro_step:
|
| 566 |
+
for skipped in range(micro_step):
|
| 567 |
+
index = 0 if skipped % 2 == 1 else 1
|
| 568 |
+
_, iterators[index] = next_row((pair_loader, replay_loader)[index], iterators[index])
|
| 569 |
+
target = args.steps
|
| 570 |
+
optimizer.zero_grad(set_to_none=True)
|
| 571 |
+
while completed < target:
|
| 572 |
+
active_loaders, active_iterators = (pair_loader, replay_loader), iterators
|
| 573 |
+
competitor_paired = micro_step % 2 == 1
|
| 574 |
+
index = 0 if competitor_paired else 1
|
| 575 |
+
row, active_iterators[index] = next_row(active_loaders[index], active_iterators[index])
|
| 576 |
+
with accelerator.accumulate(model, selector):
|
| 577 |
+
inputs, labels, query = encode(processor, row, accelerator.device)
|
| 578 |
+
visual = torch.nonzero(inputs["input_ids"][0] == int(_value(config, "image_token_id")), as_tuple=False).flatten()
|
| 579 |
+
keep = int(labels.ne(-100).sum()) + 1
|
| 580 |
+
context = Attention(model, query, visual) if competitor_paired else nullcontext()
|
| 581 |
+
with context as attention:
|
| 582 |
+
output = model(**inputs, use_cache=False, logits_to_keep=keep)
|
| 583 |
+
if competitor_paired:
|
| 584 |
+
scores = selector(attention.ordered())
|
| 585 |
+
selection_term = selection_loss(
|
| 586 |
+
scores,
|
| 587 |
+
row,
|
| 588 |
+
inputs["image_grid_thw"][0],
|
| 589 |
+
config,
|
| 590 |
+
margin=args.margin,
|
| 591 |
+
pair_weight=args.pair_weight,
|
| 592 |
+
)
|
| 593 |
+
else:
|
| 594 |
+
selection_term = output.logits.sum() * 0
|
| 595 |
+
coord_loss = coordinate_loss(output.logits, inputs["input_ids"], labels)
|
| 596 |
+
coord_scale = coordinate_weight(row, args.ground_coordinate_weight)
|
| 597 |
+
loss = coord_scale * coord_loss + args.aux_weight * selection_term
|
| 598 |
+
accelerator.backward(loss)
|
| 599 |
+
if accelerator.sync_gradients:
|
| 600 |
+
accelerator.clip_grad_norm_(list(model.parameters()) + list(selector.parameters()), 1.0)
|
| 601 |
+
optimizer.step()
|
| 602 |
+
scheduler.step()
|
| 603 |
+
optimizer.zero_grad(set_to_none=True)
|
| 604 |
+
micro_step += 1
|
| 605 |
+
if accelerator.sync_gradients:
|
| 606 |
+
completed += 1
|
| 607 |
+
if accelerator.is_main_process:
|
| 608 |
+
print(f"step={completed} loss={float(loss):.4f} coord={float(coord_loss):.4f} coord_scale={coord_scale:.2f} selection={float(selection_term):.4f}", flush=True)
|
| 609 |
+
if args.save_every > 0 and completed < target and completed % args.save_every == 0:
|
| 610 |
+
save(
|
| 611 |
+
accelerator,
|
| 612 |
+
model,
|
| 613 |
+
selector,
|
| 614 |
+
optimizer,
|
| 615 |
+
scheduler,
|
| 616 |
+
processor,
|
| 617 |
+
args.output / "checkpoints" / f"step-{completed}",
|
| 618 |
+
recipe["revision"],
|
| 619 |
+
completed,
|
| 620 |
+
args.stage,
|
| 621 |
+
micro_step,
|
| 622 |
+
)
|
| 623 |
+
if PREEMPT_REQUESTED:
|
| 624 |
+
save(
|
| 625 |
+
accelerator,
|
| 626 |
+
model,
|
| 627 |
+
selector,
|
| 628 |
+
optimizer,
|
| 629 |
+
scheduler,
|
| 630 |
+
processor,
|
| 631 |
+
args.output / "checkpoints" / f"step-{completed}",
|
| 632 |
+
recipe["revision"],
|
| 633 |
+
completed,
|
| 634 |
+
args.stage,
|
| 635 |
+
micro_step,
|
| 636 |
+
)
|
| 637 |
+
raise SystemExit(85)
|
| 638 |
+
save(
|
| 639 |
+
accelerator,
|
| 640 |
+
model,
|
| 641 |
+
selector,
|
| 642 |
+
optimizer,
|
| 643 |
+
scheduler,
|
| 644 |
+
processor,
|
| 645 |
+
args.output,
|
| 646 |
+
recipe["revision"],
|
| 647 |
+
completed,
|
| 648 |
+
args.stage,
|
| 649 |
+
micro_step,
|
| 650 |
+
)
|
| 651 |
+
if accelerator.is_main_process:
|
| 652 |
+
run_config = vars(args) | {
|
| 653 |
+
"base_model": recipe["base"],
|
| 654 |
+
"base_revision": recipe["revision"],
|
| 655 |
+
}
|
| 656 |
+
(args.output / "run_config.json").write_text(
|
| 657 |
+
json.dumps(run_config, default=str, indent=2, sort_keys=True) + "\n",
|
| 658 |
+
encoding="utf-8",
|
| 659 |
+
)
|
| 660 |
+
|
| 661 |
+
|
| 662 |
+
if __name__ == "__main__":
|
| 663 |
+
main()
|
training_manifest.json
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema_version": "selectground.release.v2",
|
| 3 |
+
"model": "SelectGround-8B",
|
| 4 |
+
"base_model": "Qwen/Qwen3-VL-8B-Instruct",
|
| 5 |
+
"base_revision": "0c351dd01ed87e9c1b53cbc748cba10e6187ff3b",
|
| 6 |
+
"plain_base_start": true,
|
| 7 |
+
"aggregate": false,
|
| 8 |
+
"method": "SFT plus auxiliary selection loss",
|
| 9 |
+
"training": {
|
| 10 |
+
"stages": 1,
|
| 11 |
+
"steps": 240,
|
| 12 |
+
"seed": 20260819,
|
| 13 |
+
"gpus": 2,
|
| 14 |
+
"gradient_accumulation": 64,
|
| 15 |
+
"effective_global_batch": 128,
|
| 16 |
+
"learning_rate": 0.00003,
|
| 17 |
+
"selector_learning_rate": 0.0001,
|
| 18 |
+
"aux_weight": 0.1,
|
| 19 |
+
"coordinate_weight": 1.0,
|
| 20 |
+
"margin": 0.3,
|
| 21 |
+
"pair_weight": 0.5,
|
| 22 |
+
"warmup_steps": 10,
|
| 23 |
+
"scheduler_steps": 384,
|
| 24 |
+
"holdout_fraction": 0.02,
|
| 25 |
+
"precision": "bf16",
|
| 26 |
+
"attention": "sdpa",
|
| 27 |
+
"lora": {
|
| 28 |
+
"rank": 64,
|
| 29 |
+
"alpha": 128,
|
| 30 |
+
"dropout": 0.05,
|
| 31 |
+
"targets": ["q_proj", "k_proj", "v_proj", "o_proj", "gate_proj", "up_proj", "down_proj"]
|
| 32 |
+
}
|
| 33 |
+
},
|
| 34 |
+
"dataset": {
|
| 35 |
+
"repo": "ruotian/ContrastGround",
|
| 36 |
+
"config": "selectground-8b",
|
| 37 |
+
"pairs": 4942,
|
| 38 |
+
"replay": 4103,
|
| 39 |
+
"source_pairs_sha256": "bd9fcb0197d3799fd9d1a6f1178f3e0adaddd8a88d032939101789b259ac6d68",
|
| 40 |
+
"source_replay_sha256": "e94f589efe8ff197778fe81c33beefd75b59af962d77e17f0fb29596baf03d47"
|
| 41 |
+
},
|
| 42 |
+
"checkpoint_sha256": {
|
| 43 |
+
"adapter_config.json": "6d19205e4597f233d22dfdb37c089d39ef284c6582269f41bd42a58715335c37",
|
| 44 |
+
"adapter_model.safetensors": "6ff35d55e9000af46eb6e134b78c7c0029369bf3ec5fe74d2dfb29f3a09e923c",
|
| 45 |
+
"visual_merger.pt": "125b9b37b243724cee09eb064650a6e14d23f186097738b5144170e870da2fab",
|
| 46 |
+
"selection_head.pt": "e74db8e7fc9344ccc477d66d2439a53e67a646eca57bf1fabc7b790bdb0ab420"
|
| 47 |
+
},
|
| 48 |
+
"direct_accuracy_pct": {
|
| 49 |
+
"screenspot_pro": 65.0853889943074,
|
| 50 |
+
"ui_vision": 37.123840466010655,
|
| 51 |
+
"osworld_g": 69.41176470588235
|
| 52 |
+
}
|
| 53 |
+
}
|