Datasets:
Add verified public availability and human-evaluation guide
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- README.md +1 -1
- release/RefSeg_CA_MVA.pdf +2 -2
- release/RefSeg_CA_R3_Public_Source.zip +2 -2
- source/.gitignore +15 -0
- source/CITATION.cff +19 -0
- source/README.md +47 -0
- source/REPRODUCIBILITY.md +47 -0
- source/SHA256SUMS +134 -0
- source/THIRD_PARTY.md +9 -0
- source/code/analyze_r2.py +134 -0
- source/code/annotate_parser_audit.py +27 -0
- source/code/audit_phase1.py +48 -0
- source/code/build_hf_release.py +104 -0
- source/code/build_latex.py +48 -0
- source/code/download_release_data.py +48 -0
- source/code/figures_r2.py +147 -0
- source/code/figures_r3.py +123 -0
- source/code/generate_rich.py +141 -0
- source/code/infer_r2.py +111 -0
- source/code/package_public_source.py +88 -0
- source/code/package_release.py +82 -0
- source/code/phase1_analyze.py +165 -0
- source/code/phase1_infer.py +131 -0
- source/code/phase1_repair.py +152 -0
- source/code/prepare_d2.py +29 -0
- source/code/prepare_full_natural.py +62 -0
- source/code/prepare_human_passes.py +33 -0
- source/code/prepare_official_masks.py +24 -0
- source/code/prepare_rela.py +45 -0
- source/code/project_paths.py +9 -0
- source/code/publish_hf_release.py +40 -0
- source/code/r2_repair.py +52 -0
- source/code/r3_replay.py +106 -0
- source/code/r3_summarize.py +97 -0
- source/code/rela_engine.py +64 -0
- source/code/score_human_parser_audit.py +33 -0
- source/code/timing_r2.py +36 -0
- source/code/verify_portable_results.py +44 -0
- source/code/verify_rela_metrics.py +42 -0
- source/figures/Fig10_harm_signatures.tex +60 -0
- source/figures/Fig1_framework.tex +40 -0
- source/figures/Fig2_rich_atlas.tex +58 -0
- source/figures/Fig3_paired_render.tex +28 -0
- source/figures/Fig4_corrected_contrasts.tex +40 -0
- source/figures/Fig5_thresholds.tex +28 -0
- source/figures/Fig6_natural_effects.tex +30 -0
- source/figures/Fig7_absence_tradeoff.tex +20 -0
- source/figures/Fig8_rich_performance.tex +28 -0
- source/figures/Fig9_threshold_robustness.tex +56 -0
- source/figures/atlas_manifest.json +82 -0
README.md
CHANGED
|
@@ -42,7 +42,7 @@ The Dataset Viewer has **2,400 image rows**, not 28,800 rows. `commands_json` co
|
|
| 42 |
|
| 43 |
`results/primary-and-review-metrics.tar.gz` contains the exact primary score records and reviewer replay traces. These reproduce the reported metrics without cluster access. They do not replace a pixel-level model rerun.
|
| 44 |
|
| 45 |
-
|
| 46 |
|
| 47 |
## Construction and evaluation
|
| 48 |
|
|
|
|
| 42 |
|
| 43 |
`results/primary-and-review-metrics.tar.gz` contains the exact primary score records and reviewer replay traces. These reproduce the reported metrics without cluster access. They do not replace a pixel-level model rerun.
|
| 44 |
|
| 45 |
+
Browse the [source code and editable manuscript](https://huggingface.co/datasets/Ethosoft/RefSeg-CA/tree/main/source) file by file, or download [RefSeg_CA_R3_Public_Source.zip](release/RefSeg_CA_R3_Public_Source.zip). The current draft is [RefSeg_CA_MVA.pdf](release/RefSeg_CA_MVA.pdf). Code and data are hosted together under the Ethosoft organization on Hugging Face.
|
| 46 |
|
| 47 |
## Construction and evaluation
|
| 48 |
|
release/RefSeg_CA_MVA.pdf
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:44a0bf44fdce2286b73eefab66ab9d4ee568c005015a4b5f2b57bcad122ce25d
|
| 3 |
+
size 2248838
|
release/RefSeg_CA_R3_Public_Source.zip
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:83888adbdba3b70954ce22cf850fcb07b7b873f2e69d3be22c189735f49e249a
|
| 3 |
+
size 233931
|
source/.gitignore
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
build/
|
| 2 |
+
cache/
|
| 3 |
+
assets/
|
| 4 |
+
vendor/
|
| 5 |
+
__pycache__/
|
| 6 |
+
*.pyc
|
| 7 |
+
.env*
|
| 8 |
+
*.token
|
| 9 |
+
data/rich/
|
| 10 |
+
data/natural/
|
| 11 |
+
results/r3/portable/
|
| 12 |
+
*.aux
|
| 13 |
+
*.log
|
| 14 |
+
*.out
|
| 15 |
+
*.blg
|
source/CITATION.cff
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cff-version: 1.2.0
|
| 2 |
+
message: "Cite this unpublished manuscript and research software; no public DOI has been assigned."
|
| 3 |
+
title: "RefSeg-CA: evaluating and repairing command compliance in generalized referring segmentation"
|
| 4 |
+
type: software
|
| 5 |
+
version: "R3-major-revision"
|
| 6 |
+
date-released: "2026-09-08"
|
| 7 |
+
url: "https://huggingface.co/datasets/Ethosoft/RefSeg-CA"
|
| 8 |
+
repository-code: "https://huggingface.co/datasets/Ethosoft/RefSeg-CA/tree/main/source"
|
| 9 |
+
authors:
|
| 10 |
+
- family-names: "Dalar"
|
| 11 |
+
given-names: "Yağız Ekrem"
|
| 12 |
+
- family-names: "Sezer"
|
| 13 |
+
given-names: "Nedim Mutlu"
|
| 14 |
+
- family-names: "Aksoy"
|
| 15 |
+
given-names: "Ömer Faruk"
|
| 16 |
+
- family-names: "Salihoğlu"
|
| 17 |
+
given-names: "Feyzi Arda"
|
| 18 |
+
- family-names: "Öztürk"
|
| 19 |
+
given-names: "Ahmet Rıfat"
|
source/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# RefSeg-CA — R3 research release
|
| 2 |
+
|
| 3 |
+
Evaluating and repairing command compliance in generalized referring segmentation.
|
| 4 |
+
|
| 5 |
+
The release contains the SFAP parser/projection, benchmark generator, inference/evaluation scripts, exact-score replay, Slurm examples, editable TikZ/PGFPlots sources, and a current manuscript. Human validation has **not been conducted**. No acceptance or publication claim is made.
|
| 6 |
+
|
| 7 |
+
## Data and exact metric replay
|
| 8 |
+
|
| 9 |
+
Data repository: https://huggingface.co/datasets/Ethosoft/RefSeg-CA
|
| 10 |
+
|
| 11 |
+
From this directory, with Python 3.9 or newer:
|
| 12 |
+
|
| 13 |
+
```bash
|
| 14 |
+
python code/download_release_data.py
|
| 15 |
+
python code/verify_portable_results.py
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
The lightweight download reconstructs 30 primary table rows and 22 reviewer-requested threshold configurations. It requires no TRUBA connection or model weights. These are derived scores; reproducing inference pixels requires upstream models and inputs.
|
| 19 |
+
|
| 20 |
+
To obtain all 1,200 procedural scenes, both rendering styles, visible-instance maps, and command masks:
|
| 21 |
+
|
| 22 |
+
```bash
|
| 23 |
+
python code/download_release_data.py --synthetic
|
| 24 |
+
```
|
| 25 |
+
|
| 26 |
+
The default data revision is the immutable release tag `r3-data-v1`. Natural images and original gRefCOCO expression text must be obtained from the pinned upstream release; model checkpoint hashes and preparation scripts are under protocol/ and legacy_project/code/.
|
| 27 |
+
|
| 28 |
+
## Manuscript and figures
|
| 29 |
+
|
| 30 |
+
The current PDF is distributed alongside this source archive in the data repository under `release/RefSeg_CA_MVA.pdf`. Install the official Springer Nature LaTeX template and normal TeX Live packages, placing sn-jnl.cls and sn-mathphys-num.bst alongside the manuscript as instructed by Springer. The repository does not redistribute these third-party generated files.
|
| 31 |
+
|
| 32 |
+
```bash
|
| 33 |
+
python code/figures_r3.py
|
| 34 |
+
python code/build_latex.py
|
| 35 |
+
```
|
| 36 |
+
|
| 37 |
+
The synthetic download is required before regenerating image panels. All written figures are monochrome vector graphics; the experimental raster inputs retain their colors.
|
| 38 |
+
|
| 39 |
+
## Human evaluation
|
| 40 |
+
|
| 41 |
+
Read review/HUMAN_VALIDATION_PROTOCOL.md and review/INSAN_DEGERLENDIRMESI_UYGULAMA_KILAVUZU.md. Two independent readers, pre-adjudication agreement, adjudicated semantic labels, and a separate image-aware harm audit are still needed. Automated checks are not human labels.
|
| 42 |
+
|
| 43 |
+
## Provenance and reuse
|
| 44 |
+
|
| 45 |
+
See REPRODUCIBILITY.md, THIRD_PARTY.md, CITATION.cff, and SHA256SUMS. This public deposit establishes accessibility. Authors have not yet selected an additional blanket reuse license for original material; existing per-file third-party terms continue to apply.
|
| 46 |
+
|
| 47 |
+
Browse all source files at https://huggingface.co/datasets/Ethosoft/RefSeg-CA/tree/main/source. This organization-owned Hugging Face source tree is the code host for this release.
|
source/REPRODUCIBILITY.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Reproducibility: R3
|
| 2 |
+
|
| 3 |
+
## Public release, 8 September 2026
|
| 4 |
+
|
| 5 |
+
Code, editable sources, manuscript, procedural images/masks, and exact score records are public at https://huggingface.co/datasets/Ethosoft/RefSeg-CA. Data tag `r3-data-v1` resolves to commit `d5ce7eaa159c8b0a1e81f439b651c0125c0b31e0`. An unauthenticated download into a fresh directory reproduced all 30 primary table rows and 22 sensitivity settings; maximum absolute error was 3.33e-15 in that Python runtime. See protocol/public_download_verification.json.
|
| 6 |
+
|
| 7 |
+
The public download script is `code/download_release_data.py`; add `--synthetic` to reconstruct all procedural image folders. The public natural index preserves IDs, while original natural-expression text and images are obtained from their upstream sources. The fuller author supplement below retains the original natural manifest. Neither package claims completed human validation. The browsable code host is https://huggingface.co/datasets/Ethosoft/RefSeg-CA/tree/main/source, under the Ethosoft organization.
|
| 8 |
+
|
| 9 |
+
## No-cluster metric replay
|
| 10 |
+
|
| 11 |
+
Run `python code/verify_portable_results.py` from this package. It reads six gzip CSV tables under results/r3/portable and both compressed reviewer-replay traces. Thirty primary table rows reproduce within 2.22e-16; all 22 sensitivity means and harm counts pass. The recorded verification is results/r3/portable_verification.json.
|
| 12 |
+
|
| 13 |
+
These are exact derived score records, not score-map caches. They suffice to independently recompute the main metrics but do not independently verify model inference pixels. Full pixel-level reruns require the upstream data/models and inference code below.
|
| 14 |
+
|
| 15 |
+
## Inputs and software
|
| 16 |
+
|
| 17 |
+
- Model/data revisions and file hashes: protocol/asset_manifest.json.
|
| 18 |
+
- ReLA checkpoint identity and preparation: protocol/rela_assets.json, code/prepare_rela.py, code/prepare_d2.py, code/rela_engine.py.
|
| 19 |
+
- Executed package versions: protocol/runtime_versions.json. Hardware-specific Torch wheels must be installed appropriately for a new machine.
|
| 20 |
+
- All 49,492 natural records: results/r3/portable/natural_full_manifest.jsonl.gz.
|
| 21 |
+
- Complete rich query/scene manifests: data/rich_synthetic.jsonl and data/rich_scenes.jsonl.
|
| 22 |
+
- Historical preparation/inference source is bundled under legacy_project/code. Local paths resolve through code/project_paths.py; REFSEG_LEGACY_ROOT can explicitly point to another prepared copy.
|
| 23 |
+
|
| 24 |
+
## Reconstruct images and inference
|
| 25 |
+
|
| 26 |
+
1. Fetch pinned assets with `python legacy_project/code/prepare_assets.py` (checksums verified).
|
| 27 |
+
2. Prepare the historical fit/calibration data with `python legacy_project/code/prepare_data.py` when reproducing that phase.
|
| 28 |
+
3. Prepare full natural inputs and official masks with `python code/prepare_full_natural.py` and `python code/prepare_official_masks.py`.
|
| 29 |
+
4. Generate all 1,200 rich scenes with `python code/generate_rich.py`. The shipped ten example scenes are a preview; the complete generation is deterministic from five pinned seeds.
|
| 30 |
+
5. Use code/infer_r2.py for CLIPSeg/Grounded SAM or native ReLA. The Slurm examples preserve executed settings; adapt only account, partition, paths, and obsolete dependency job IDs for another cluster. Install the pinned models/dependencies before inference.
|
| 31 |
+
6. Run code/r3_replay.py on caches for each of 16 shards per model; run code/r3_summarize.py after all shards complete. A default replay must exactly match the archived primary IoUs before any sensitivity result is accepted.
|
| 32 |
+
|
| 33 |
+
## Executed reviewer jobs
|
| 34 |
+
|
| 35 |
+
- Array 6334005: 32 completed CPU tasks, two interfaces × 16 shards.
|
| 36 |
+
- Summary/export 6334038: completed.
|
| 37 |
+
- Primary accepted records: 1,557 per interface; maximum primary replay IoU discrepancy: zero.
|
| 38 |
+
- Four scopes and eleven operating points are post-review exploratory diagnostics; the R2 primary rule remains unchanged.
|
| 39 |
+
|
| 40 |
+
The raw TRUBA archive path is retained only as provenance: /arf/scratch/egitimg16u1/mcp-workspace/refseg_ca_r2. Portable primary metrics do not need that path.
|
| 41 |
+
|
| 42 |
+
## Archive integrity
|
| 43 |
+
|
| 44 |
+
- portable_primary_results.tar.gz SHA-256: 4dccb64342faa3c96fd50cce8f7bfed6237d196310ad4947b4d88a14c095708a
|
| 45 |
+
- review_replay_records.tar.gz SHA-256: 1df51ae12a48f74f8015b14f637dccd31c103971299a4b4b976e5cb72e4051de
|
| 46 |
+
|
| 47 |
+
A release-wide SHA256SUMS file accompanies the final package. Public repository deposit is complete; a DOI remains unassigned. The public DATA_MANIFEST.json additionally records hashes for each distributed data shard and result archive.
|
source/SHA256SUMS
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
71bf7ed212001f03d9ea352e1c973539bfe2f504b2999afd36af71105e2de78e .gitignore
|
| 2 |
+
7c2d78769a4d32dde25b168e1bcc7d018741d47a981bd73ff8c49328e26a0fc5 CITATION.cff
|
| 3 |
+
3f2fed9d8fdd16eb3e1f6279a1edf59bd8166ac6df2a8340f3e25cbf9bb734da README.md
|
| 4 |
+
2d0c8de7c4066f0543c4ff4ba3558678bd464a92bde8d8f636aaa5afc8c63d9e REPRODUCIBILITY.md
|
| 5 |
+
4543088ba4888edc55f81a9f9192a7667dc7e964530ae2b6e8febff07df90e71 THIRD_PARTY.md
|
| 6 |
+
33c0d54504ec363c41caeae8b6a3ec155d1ea92fe3a8e390a04d6015427bb4eb code/analyze_r2.py
|
| 7 |
+
aa2e8eef7f951febdabc59333df26a9a95fd86b19266432d7a1aa24d2599cd76 code/annotate_parser_audit.py
|
| 8 |
+
4358b9069ed272b4e6621b1280ba84ea9a9087da4de72023fc7f0cbeb839fd01 code/audit_phase1.py
|
| 9 |
+
7f115476e654374378badab4b867781f1729d347e0372fc207d7ac2b62f4e05b code/build_hf_release.py
|
| 10 |
+
e9f0ebe5ea6262a3ab01d3bb26356104411d617415cc6dcfb86f11e106445ae4 code/build_latex.py
|
| 11 |
+
d26ea40c9341e48e3e88f960fc1db12de675e5df36d7ff1c7e5a7b538d95fc14 code/download_release_data.py
|
| 12 |
+
c88c7faf16e90eb223815cfbaec41e4eb2e424ba662173af307eb23b80ccb316 code/figures_r2.py
|
| 13 |
+
71c1f885a51dba5e61cba5725be905441cb3bcf9faf2b0a34d4ba30ce932ca5f code/figures_r3.py
|
| 14 |
+
11932a5c675952e5b708f6f0f04bde93d0c94bb7169f0c13a547cbe512d77445 code/generate_rich.py
|
| 15 |
+
cd980f0c33ddb13c97ce0f41f4cfc52600c3dd2b0cb648469dce91094bb96d60 code/infer_r2.py
|
| 16 |
+
c03eb51e5cbf78b17fdf64d01c6c295aaf3200de8f8a75469b0e0cfd843bdcfb code/package_public_source.py
|
| 17 |
+
ae693f0d5a4451b1f846a9f624d0092269a20c715e0ce840655c4050d782e62c code/package_release.py
|
| 18 |
+
6a294a9b99c1612c88ee2668993b7eed41038f505398d767c463b444dfba78b2 code/phase1_analyze.py
|
| 19 |
+
92408e6897159497cb458b3e73d4b8e9731d2ac5dea8f9be37d42ff440de13ec code/phase1_infer.py
|
| 20 |
+
ecab2dfa0b5a79c4d7b55bd93d3438175e8b42b6dde096c34ce1f22d7cef8f44 code/phase1_repair.py
|
| 21 |
+
23c1613ae2b16130e963819a4655c43077bab5e9927e5ee7c0a4ebc7a88a4678 code/prepare_d2.py
|
| 22 |
+
8a2fe0bdbc8c72e2b33fbfd6689c697266cd8eda14f097f278f84af269939f2b code/prepare_full_natural.py
|
| 23 |
+
bbc9a73c01de25e5322325455124b6afcaee0af4d293b159cc9377d58aba95f7 code/prepare_human_passes.py
|
| 24 |
+
7ded426fb791eb8fd764742aefd7281bfc78a28db01f4630a7d71f6e01ec13d3 code/prepare_official_masks.py
|
| 25 |
+
c6f2512744b481354c77af5ae2f390b4cd07ddf3d9dcf3a3e572a9689b5e0696 code/prepare_rela.py
|
| 26 |
+
94b438c79b53ecc1035bd099b3880cd428c7cfc1069ed52172a1371c3430231d code/project_paths.py
|
| 27 |
+
d680543c9e2638713134f76c4955f867a976102b8d0af3c6099b8bcfdcf52750 code/publish_hf_release.py
|
| 28 |
+
48834716a6689cffea835c9ba57d9b6457094856a9903cca9ee9713005b89156 code/r2_repair.py
|
| 29 |
+
40337207e029ff7896cb702fa1d4fb47718421b97caf3d5013b5d557bb71fcef code/r3_replay.py
|
| 30 |
+
8c728585942b0b7a98b10711a45578e972ce50104bfe60ee8ae12567aa13da29 code/r3_summarize.py
|
| 31 |
+
8688215c04dd3782c1eb0cad2ad8cc5917ada9989434e7be8df8f502995ac641 code/rela_engine.py
|
| 32 |
+
501d8a543fc3c4670daa2613ce65e1535f7d570f46ef3232f1862fe3cd949255 code/score_human_parser_audit.py
|
| 33 |
+
5685979870a403520236fca36173da15774f08d582e95a96ff75b016a63484c4 code/timing_r2.py
|
| 34 |
+
6a15b68352b0354419635f524ec9fca96191502fa6390993cd4dd498c50f0687 code/verify_portable_results.py
|
| 35 |
+
5c892456ba80da8be9403d00df1ee6b9a58d7e5726ffb4b008c3b2b9139351cb code/verify_rela_metrics.py
|
| 36 |
+
e9299bafa2b1370080eab8309a11cbc1181b4661c6bc49283df2f5dd3bf45751 figures/Fig10_harm_signatures.tex
|
| 37 |
+
1b31451b259c67d87300a2b12ce0ca4cbb6b686fd3fc28fb202f70fdc1b255c4 figures/Fig1_framework.tex
|
| 38 |
+
169ca88d0f6c354da707fa4019207cd7bf38808255ddb2b5dd785114acbfe16a figures/Fig2_rich_atlas.tex
|
| 39 |
+
5ec3a6fd14eb9ffc48766e2dee5da42ca7c0fad5fec4bb067cc2c833a4c323e3 figures/Fig3_paired_render.tex
|
| 40 |
+
8215bfccfe95140964c226627c8f03c72981604e79fcbba9f4f9fc3e694ce6c4 figures/Fig4_corrected_contrasts.tex
|
| 41 |
+
7b1a89ef763197051a753f4eb0842c568b3bb1c4cdbd2751631571ac1f2f780c figures/Fig5_thresholds.tex
|
| 42 |
+
0ef37e3f8d61d7bdc57e66593221f1f077ed5c5f07cb7d6060b4b86083c92877 figures/Fig6_natural_effects.tex
|
| 43 |
+
09e7e993d6a2d27cd1f58e5cb75f7590bc2f73835b622363ef4552f8e2261e0d figures/Fig7_absence_tradeoff.tex
|
| 44 |
+
c94932ef59ea26d5bdf4641d4ce8c4500bf1203ba8d23bacded0da8293b44252 figures/Fig8_rich_performance.tex
|
| 45 |
+
f8d70681e55163404b70b5d3fe166584970c9011aefe463be366614fcf16fb64 figures/Fig9_threshold_robustness.tex
|
| 46 |
+
87222306391ef553efc575645b245ce49fa99e2b0adca722d37ca91a4a6c3287 figures/atlas_manifest.json
|
| 47 |
+
adee394c340cf4930b7a52ebe9f258cdb3441f5a9dc4d03a1be3cb29326fa0b0 figures/style.tex
|
| 48 |
+
ce8a4374ad7002ea756dc54fe5f76ed4bb0bab17441572977f5e439f7aeb3bb0 latex/RefSeg_CA_MVA.tex
|
| 49 |
+
fbd1673314c53abff12cbbeb61946c489fde457f0647260742adc27150779fcf latex/design_comparison.tex
|
| 50 |
+
bae1861de78cbece3ea00c0b24533ead98f1caa188907090a56d3275dfea20ff latex/references.bib
|
| 51 |
+
ed88856df0fb8df7de8b960957ddda13dd902705883293e0ab4d48d141e1e35d latex/review_extensions.tex
|
| 52 |
+
6a294a9b99c1612c88ee2668993b7eed41038f505398d767c463b444dfba78b2 legacy_project/code/analyze.py
|
| 53 |
+
8f809efc18f9a61a074f8f67209fd56a29ef325d1d3beb79bf49a9f979034942 legacy_project/code/build_latex.py
|
| 54 |
+
4aa7bf4ccdf57a254dfda70c6ef5ce6e1525c221024bc09f48a5d94dd55de3dd legacy_project/code/export_qualitative.py
|
| 55 |
+
92408e6897159497cb458b3e73d4b8e9731d2ac5dea8f9be37d42ff440de13ec legacy_project/code/infer.py
|
| 56 |
+
1cd6bbe48e19b91086e5a62784747aa052b46609421866fb7d5026545ce6d59b legacy_project/code/make_figures.py
|
| 57 |
+
f2733ab418a360f233a1e6c0f6517090923c076e5f3d1628a19487bb1886f302 legacy_project/code/package_release.py
|
| 58 |
+
6b50adc897f0392fb9028b194d708cb1e509e30eb445ede199b7d2cf8bbf5029 legacy_project/code/pilot.py
|
| 59 |
+
de03cc1aa9d6a83e6108c844e6ffa4fe253ad6ad1222868aead86f508c7746a7 legacy_project/code/prepare_assets.py
|
| 60 |
+
c0d546fa369b72b0710b9645bd30d7d8f0fa4b0ec33c52bfe57a542ed2ee7171 legacy_project/code/prepare_data.py
|
| 61 |
+
ecab2dfa0b5a79c4d7b55bd93d3438175e8b42b6dde096c34ce1f22d7cef8f44 legacy_project/code/repair.py
|
| 62 |
+
393b6b83429ca83291e42e0fb1e98ed5de546c167ce59375ecb81ae0edbefbc4 legacy_project/code/replay_analysis.py
|
| 63 |
+
ddb8d686f88d8672096d674315739a8a1c1854792b120de679fcb0a68a45740d legacy_project/code/test_protocol.py
|
| 64 |
+
3fe7b94c1a0a9e66dca9f1172fe5295f22ab0e314fc47f786d0184c6a9812be3 legacy_project/code/write_results.py
|
| 65 |
+
ae6b23e5957498a6e85624e88864784359427a89a65e7e422a7da7206bf6e136 legacy_project/protocol/asset_manifest.json
|
| 66 |
+
1c94703f12b2580c53b0b199ccae6008bb1ec84a5495feb4117d604b0303c400 legacy_project/results/analysis/calibration.json
|
| 67 |
+
18dfeef104ae9b31933889361bc9d63b14209bad7a979b75721f32f9aa44e098 protocol/HF_DATA_CARD.md
|
| 68 |
+
83dd0a7a86bd9db56fe91d7b53cfdab48649bacd383d3d6fb8b7bf8c571a9393 protocol/R2_ANALYSIS_PLAN.md
|
| 69 |
+
43a49a858276739b2981e508cfdb832dccd054e3e5805fbe731471021c3058fc protocol/R3_REVIEW_ANALYSIS_PLAN.md
|
| 70 |
+
ae6b23e5957498a6e85624e88864784359427a89a65e7e422a7da7206bf6e136 protocol/asset_manifest.json
|
| 71 |
+
ac8123d836a124def2d18fd51b3bf2221dceb5d6de5a05d404b5f96bed534618 protocol/checkpoint_identity.json
|
| 72 |
+
734412cd8557d749da8718a65fadf6bb2e5d4b8900ee0d9b1fd352cc7fa7ff69 protocol/natural_full_manifest.json
|
| 73 |
+
ccf86503063251bafebf6f949b835c9f0ba98fc94c78d331f7af19b54554d75a protocol/public_data_receipt.json
|
| 74 |
+
70c5117628654493737282d81dd610c55e223faa24ea22541d6b802fe98f4228 protocol/public_download_verification.json
|
| 75 |
+
87f55dab94808d88d2f776d05d4e4318dc021a9d175a1d81d9575e7a716964c2 protocol/public_release_receipt.json
|
| 76 |
+
930aed7e6bd8ee7da5a482675fa9b8530b55b72e61f65f6a3bcbf971da550161 protocol/rela_assets.json
|
| 77 |
+
0b57c8e45ce69c590fb405b58efc11b67decdf19049ac14f8b1572c50df3cfaf protocol/rela_reconstruction_lock.json
|
| 78 |
+
e9f85fc23e9f34419eb51ce0c42e5e9c7162231ee7af0dc4939070cfc05df155 protocol/rich_manifest.json
|
| 79 |
+
867c36d6ff741224764daea7ed3cad384ffe684f1b254a57831b0f4ba9edf0d3 protocol/runtime_versions.json
|
| 80 |
+
8c12c6d9ca72f45827afe1a52e6663c306fa68e79c1129b6376f36e66ef46088 protocol/template_source.json
|
| 81 |
+
6969a223c0d914f1f137e648d395819dab9503a09891d4a72cacf3c92276d5b2 requirements-analysis.txt
|
| 82 |
+
25d6921efcf506cc7549c7afd763ef541f04881f5137af9cdd8361bb9b3f7a1a results/analysis/natural_clipseg.json
|
| 83 |
+
3ba875a2f3936cf818d2fa950b2fdf58c9b204c548d9e7e58ee7f842f86847d5 results/analysis/natural_groundedsam.json
|
| 84 |
+
5373058210aa570aad3b4fca0328e34476dea1c204594c723a38d931a43fa984 results/analysis/paper_results.json
|
| 85 |
+
46d0a4eef86b1a2211f81228de49ecd86a8b10da7f739512ba1a0ac168148eec results/analysis/phase1_exact_audit.json
|
| 86 |
+
a571efeb65dc30a9ea0e8bfa7480bc18e5c40c93e3b93fc0625664973a87bbe3 results/analysis/phase1_multiplicity.json
|
| 87 |
+
14b165094edf8e32514e7be429c3a85faefbfc2009834882fe99d415efd9578c results/analysis/phase1_threshold_curves.json
|
| 88 |
+
4cf341064300cc44b9587ad289eb73ddd154961a55d87330c37bed93598278f7 results/analysis/rela_metric_verification.json
|
| 89 |
+
073471415d0f781e0f6e41337b7d1bc7dcb3dfeaf10bbc8b3cc69c9f75838cf8 results/r3/jobs/clipseg_0of16.meta.json
|
| 90 |
+
bc35728a6e664750383d1a0eddb1b841f6cc513f5463b2b7ea6541225c25fc53 results/r3/jobs/clipseg_10of16.meta.json
|
| 91 |
+
844e5b4951ac50efdf76339f7377112d78cbacd96986ca67c12ed48e3d3d630d results/r3/jobs/clipseg_11of16.meta.json
|
| 92 |
+
c410cc527d4c41e5f75b21ce0eac963dd703634fb7ae560e0e656c19b87dff0a results/r3/jobs/clipseg_12of16.meta.json
|
| 93 |
+
4908646fc62898beb27fbe177601f6123032a8f708a808e479b783af7fcf91e1 results/r3/jobs/clipseg_13of16.meta.json
|
| 94 |
+
0a285a15f89b9c11f6802dabdfdfaf04e092e9da7ba0304ac82c64dde5d0e7eb results/r3/jobs/clipseg_14of16.meta.json
|
| 95 |
+
e257ea881b69cb655e95e5da9b79c8841b022e1b7354d65dd6c68687b674d8b7 results/r3/jobs/clipseg_15of16.meta.json
|
| 96 |
+
e215c2aef3ef3c7a4b0bbfa02c2791a59b77f4c33899a8d5b63930faa43c4d82 results/r3/jobs/clipseg_1of16.meta.json
|
| 97 |
+
49c5406cd4a7fa0ccac44bd2429af011546a04901547912b780a6b386d5d9224 results/r3/jobs/clipseg_2of16.meta.json
|
| 98 |
+
41c6f8daad80b522d04538fb2569373fc57faf9638898a3bb94e75b73e72a15d results/r3/jobs/clipseg_3of16.meta.json
|
| 99 |
+
d384e4e97e1ff715627d857c2238c77aaf32ea4ea9047a1c7ab5cd02eb15b058 results/r3/jobs/clipseg_4of16.meta.json
|
| 100 |
+
1e75580137f4a1c8b9473adafc91167f2fcc1d489475055c81203759e53b171a results/r3/jobs/clipseg_5of16.meta.json
|
| 101 |
+
f79a2d7b89961ecdc8799cee21bac1d94cbb49114b554445b74bfec0863e3d25 results/r3/jobs/clipseg_6of16.meta.json
|
| 102 |
+
3ba8acba95300db2cfa550ce96fbf206c2e9ec2b355dd53f8c29c4c6795292ce results/r3/jobs/clipseg_7of16.meta.json
|
| 103 |
+
487a4a4e16ef2157b08763d776fc1694b06a5ea56bf9e04af8bc578ca80b4dc1 results/r3/jobs/clipseg_8of16.meta.json
|
| 104 |
+
67f95f8c1b8f381db6d87f38c3ff183b0e3aaa18bbe1e378a45bd9bb8a00e4cf results/r3/jobs/clipseg_9of16.meta.json
|
| 105 |
+
61a0748b6403d6be46b65c61c4633a48e2be6d38c5431fb52d477611454a9d2a results/r3/jobs/groundedsam_0of16.meta.json
|
| 106 |
+
7efa3b5162ec015da59656aba485ff45a29b9b50604ad23c25e073044c12832a results/r3/jobs/groundedsam_10of16.meta.json
|
| 107 |
+
c3dc4aa877d2c1c126de9abf23288bcaed15aa9562336c857b62ccdf745e97a7 results/r3/jobs/groundedsam_11of16.meta.json
|
| 108 |
+
15113af4e3e61e840e46804c7a49b3114b1e75625ea06a3f9554e2ccf9746d30 results/r3/jobs/groundedsam_12of16.meta.json
|
| 109 |
+
523ad7e4c27d391244a65fdef97dd41412916a8224893d85c54737d0f4655416 results/r3/jobs/groundedsam_13of16.meta.json
|
| 110 |
+
e80dbdcf755e642bae369aa630e6f632e12124774045848ef276daa403727212 results/r3/jobs/groundedsam_14of16.meta.json
|
| 111 |
+
a9aee9410276d2ab954dc82ef68858503a416567e9e842e6b2811a9d05aa5bc0 results/r3/jobs/groundedsam_15of16.meta.json
|
| 112 |
+
b9200f81ee45458d8c8245c0ffbf11b1409e00b72aa265287e5ceb2ae70b4faf results/r3/jobs/groundedsam_1of16.meta.json
|
| 113 |
+
4e7928c9f8a5c62e87d4fb10953d453f7242cd02964a168b603d284a22a7733b results/r3/jobs/groundedsam_2of16.meta.json
|
| 114 |
+
80cc8e8eb6f3a561cc88aff981778266970c43c8a6614ca5eafca0a9a8feb1dd results/r3/jobs/groundedsam_3of16.meta.json
|
| 115 |
+
5f708c0f2fd643866f2b3b596d73690422ae740e05fdf9a9a6ed622bdebf670b results/r3/jobs/groundedsam_4of16.meta.json
|
| 116 |
+
5a0d9694a22eb7d06492cac44c91d7909f697b3e5b21d4f67b5069cbc766da7d results/r3/jobs/groundedsam_5of16.meta.json
|
| 117 |
+
7859bf13a336b38e868d8c4e3d9afccb5fba32e47e3766f267f37ff66e0bef76 results/r3/jobs/groundedsam_6of16.meta.json
|
| 118 |
+
48f70231977f48319419d17c913cb5b25dd8d6948112aad7b49a56898a92fd21 results/r3/jobs/groundedsam_7of16.meta.json
|
| 119 |
+
b51e3b8de27c785ebdc1b63efffc97c32ef2d3df8648187f4ebeb366b524c0f5 results/r3/jobs/groundedsam_8of16.meta.json
|
| 120 |
+
32564512c85c95d7e46e22a89e4790adedf81bf77d57c13e2d6ff191d7e9d93e results/r3/jobs/groundedsam_9of16.meta.json
|
| 121 |
+
5f981eb3145b2b164c4e01fb72ef5d21f53160dda177a85662977147371b614b results/r3/review_results.json
|
| 122 |
+
e47dfaf78edb1eb206051cfe483743929f29639f4b979fd9be56e3c87aab8c11 review/HUMAN_VALIDATION_PROTOCOL.md
|
| 123 |
+
a6e9e9dd9d9320619216ff65b91ff38d24b0ce73da878e18cec6709090aedecb review/INSAN_DEGERLENDIRMESI_UYGULAMA_KILAVUZU.md
|
| 124 |
+
dda2b7af02adc7a68fcb58fe911dda0c4ec1f91a7e276af215be2777b432c2a1 review/Response_to_Major_Revision.md
|
| 125 |
+
8506393c5eb48ede5f37f02078fce5b23b0665ab846c96cb0c7132a71cce51c5 slurm/analyze_all_r2.sbatch
|
| 126 |
+
3c8f3038c74b36d9a1b1273b4517c5ffdd978769fd04e758288b7c4227e87092 slurm/build_public_data.sbatch
|
| 127 |
+
eaf5fa9f45088fc39b2425a4b83f921ec7be9352f062b380d13d7bec6430e9e3 slurm/full_clipseg.sbatch
|
| 128 |
+
c11a0b09d3957fb52d7bd93f62111a980b883cbf990871568b1cdf2beb5627ae slurm/full_groundedsam.sbatch
|
| 129 |
+
8102dab9d2c11b3e086473b6997234b9f95e0acf2c1f146e36dd6922fb7eb2e0 slurm/natural_full_rela.sbatch
|
| 130 |
+
652767c17829c176f1200d5e967268d3bdca97b83cbf5a22433fdb75fd8f3707 slurm/r3_replay.sbatch
|
| 131 |
+
beb0b75252f33793538e7e5f34775cebb1f8ffb167cef5c5f8cd085444c4f622 slurm/r3_summary.sbatch
|
| 132 |
+
6825982e1b431e79bc4503869f62b0945a15b642b00fd3a4f11b4b158cada073 slurm/rich_clipseg.sbatch
|
| 133 |
+
e01c3ff49bef60716a1dc6262235030719ee6e0edebea46d3011a9a384ae7423 slurm/rich_groundedsam.sbatch
|
| 134 |
+
0d9cefe5ec90a54461a47f33b53233e885d42e367593d22df9b62fac6f610b3e slurm/rich_synthetic_rela.sbatch
|
source/THIRD_PARTY.md
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Third-party materials
|
| 2 |
+
|
| 3 |
+
Original natural images and gRefCOCO expression files are not included. Obtain them from https://huggingface.co/datasets/FudanCVL/gRefCOCO at revision 81eede59b3ac070049f597d023c0ff08d1fb80e9 and the image sources referenced by its authors. They retain their original terms.
|
| 4 |
+
|
| 5 |
+
Model weights and ReLA source are downloaded from their authors using the revisions and hashes in protocol/. No model weights are redistributed here.
|
| 6 |
+
|
| 7 |
+
The Springer Nature LaTeX class/bibliography style and standard algorithm packages must be installed from their official distributions. These generated third-party files are omitted from this public source archive. The user-facing manuscript source remains included.
|
| 8 |
+
|
| 9 |
+
This repository adds no blanket license to material owned by others. The project authors have not yet assigned a blanket reuse license to their original code or procedural dataset.
|
source/code/analyze_r2.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Aggregate only complete executed shards; expression-weighted cluster CIs."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json,gzip,collections,csv,math,argparse,hashlib,os
|
| 4 |
+
import numpy as np
|
| 5 |
+
from scipy.stats import binomtest,norm
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1];from project_paths import legacy_root;OLD=legacy_root(ROOT)
|
| 7 |
+
DEST=ROOT/'results/analysis';DEST.mkdir(parents=True,exist_ok=True)
|
| 8 |
+
def readlines(p):
|
| 9 |
+
with (gzip.open(p,'rt') if str(p).endswith('.gz') else p.open()) as f:return [json.loads(s) for s in f]
|
| 10 |
+
def ci_cluster(rows,values,alpha=.05,B=2000):
|
| 11 |
+
groups=collections.defaultdict(list)
|
| 12 |
+
for r,v in zip(rows,values):groups[(r.get('split','test'),r['scene_id'])].append(float(v))
|
| 13 |
+
if not groups:return [None,None]
|
| 14 |
+
strata=collections.defaultdict(list)
|
| 15 |
+
for (s,k),v in groups.items():strata[s].append((sum(v),len(v)))
|
| 16 |
+
rng=np.random.default_rng(77123);sums=np.zeros(B);counts=np.zeros(B)
|
| 17 |
+
for v in strata.values():
|
| 18 |
+
v=np.array(v);idx=rng.integers(0,len(v),(B,len(v)));sums+=v[idx,0].sum(1);counts+=v[idx,1].sum(1)
|
| 19 |
+
return np.quantile(sums/counts,[alpha/2,1-alpha/2]).tolist()
|
| 20 |
+
def describe(rows,variant,key='scores'):
|
| 21 |
+
s=[r[key][variant] for r in rows];pos=[z for r,z in zip(rows,s) if r['target_count']>0];neg=[z for r,z in zip(rows,s) if r['target_count']==0]
|
| 22 |
+
nt=lambda z:z.get('pred_nt',z['empty'])
|
| 23 |
+
return dict(n=len(rows),images=len({r['scene_id'] for r in rows}),positive=len(pos),negative=len(neg),gIoU=float(np.mean([z['iou'] for z in s])),cIoU=sum(z['intersection'] for z in s)/max(1,sum(z['union'] for z in s)),positive_mIoU=float(np.mean([z['iou'] for z in pos])) if pos else None,Nacc=float(np.mean([nt(z) for z in neg])) if neg else None,false_empty=float(np.mean([nt(z) for z in pos])) if pos else None,Pr50=float(np.mean([z['iou']>=.5 for z in pos])) if pos else None)
|
| 24 |
+
def comparison(rows,v,b='frozen',key='scores',alpha=.05):
|
| 25 |
+
d=np.array([r[key][v]['iou']-r[key][b]['iou'] for r in rows]);helped=int((d>1e-12).sum());harmed=int((d< -1e-12).sum());n=helped+harmed
|
| 26 |
+
return dict(n=len(rows),images=len({r['scene_id'] for r in rows}),delta=float(d.mean()) if len(d) else None,ci=ci_cluster(rows,d,alpha),helped=helped,harmed=harmed,tied=len(rows)-n,sign_p=binomtest(helped,n,.5).pvalue if n else 1.,paired_sd=float(d.std(ddof=1)) if len(d)>1 else None,approx_iid_mde80=(norm.ppf(.975)+norm.ppf(.8))*float(d.std(ddof=1))/math.sqrt(len(d)) if len(d)>1 else None)
|
| 27 |
+
def add_calibration(rows,model):
|
| 28 |
+
p=OLD/'results/analysis/calibration.json'
|
| 29 |
+
if not p.exists():return
|
| 30 |
+
params=json.loads(p.read_text())[model]
|
| 31 |
+
if not (OLD/'assets/grefcoco/instances.json').exists():return
|
| 32 |
+
coco=json.loads((OLD/'assets/grefcoco/instances.json').read_text());sizes={i['id']:i['width']*i['height'] for i in coco['images']}
|
| 33 |
+
for r in rows:
|
| 34 |
+
features=np.array(r['features']);features[4]=r['scores']['cacp']['pred_pixels']/sizes[r['image_id']]
|
| 35 |
+
for name in ['source_unconstrained_s11','target_unconstrained_s11','constrained_0.01_s11','constrained_0.025_s11','constrained_0.05_s11','constrained_0.1_s11']:
|
| 36 |
+
p=params[name];fit=p['fit'];coef=np.array(fit['coef']);x=(features-np.array(fit['mean']))/np.array(fit['std']);logit=coef[-1]+float(x@coef[:-1]);prob=1/(1+np.exp(-np.clip(logit,-50,50)));reject=prob>=p['operating_point']['threshold']
|
| 37 |
+
for key in ['scores','official480_scores']:
|
| 38 |
+
base=r[key]['cacp'];z=dict(base)
|
| 39 |
+
if reject:z.update(iou=float(r['target_count']==0),intersection=0,union=base['gt_pixels'],pred_pixels=0,empty=True,pred_nt=True)
|
| 40 |
+
r[key][name]=z
|
| 41 |
+
r.setdefault('added_abstention',{})[name]=bool(reject and not r['scores']['cacp']['empty'] and r['target_count']>0)
|
| 42 |
+
def natural(model,shards):
|
| 43 |
+
paths=[ROOT/'results'/f'natural_full_{model}_{i}of{shards}.jsonl' for i in range(shards)]
|
| 44 |
+
if not all(p.with_name(p.stem+'_meta.json').exists() for p in paths):return None
|
| 45 |
+
rows=[r for p in paths for r in readlines(p)];assert len(rows)==49492 and len({r['id'] for r in rows})==49492
|
| 46 |
+
if model!='rela':add_calibration(rows,model)
|
| 47 |
+
variants=list(rows[0]['scores']);out=dict(records=len(rows),images=len({r['scene_id'] for r in rows}),tables=[],comparisons={},coverage={},cost={})
|
| 48 |
+
for split in ['val','testA','testB','all']:
|
| 49 |
+
subset=[r for r in rows if split=='all' or r['split']==split]
|
| 50 |
+
for key in ['scores','official480_scores']:
|
| 51 |
+
for v in variants:out['tables'].append(dict(split=split,grid=key,variant=v,**describe(subset,v,key)))
|
| 52 |
+
for scope in ['all','old_supported','scope_safe','old_relational','safe_relational','positive','safe_positive']:
|
| 53 |
+
s=[r for r in rows if scope=='all' or (scope=='old_supported' and r['flags'].get('supported')) or (scope=='scope_safe' and r['flags'].get('scope_safe')) or (scope=='old_relational' and r['flags'].get('anchor')) or (scope=='safe_relational' and r['flags'].get('anchor') and r['flags'].get('scope_safe')) or (scope=='positive' and r['target_count']>0) or (scope=='safe_positive' and r['target_count']>0 and r['flags'].get('scope_safe'))]
|
| 54 |
+
out['coverage'][scope]=dict(records=len(s),images=len({r['scene_id'] for r in s}))
|
| 55 |
+
for v in ['anchor_gate','cacp','safe_anchor','source_unconstrained_s11','constrained_0.05_s11']:
|
| 56 |
+
if v in variants and s:out['comparisons'][scope+'/'+v]=comparison(s,v,key='official480_scores')
|
| 57 |
+
out['scope_reasons']=dict(collections.Counter(r['flags'].get('scope_reason','native') for r in rows))
|
| 58 |
+
out['exact_cf']=dict(changed=sum(r['flags'].get('cf_vs_anchor_changed',False) for r in rows),nogate_changed=sum(r['flags'].get('nogate_cf_changed',False) for r in rows))
|
| 59 |
+
out['cost']=dict(total_primary_query_requests=sum(r['primary_query_count'] for r in rows),total_cf_query_requests=sum(r['query_count'] for r in rows),average_primary_requests=float(np.mean([r['primary_query_count'] for r in rows])),average_cf_requests=float(np.mean([r['query_count'] for r in rows])))
|
| 60 |
+
out['added_abstention']={v:sum(r.get('added_abstention',{}).get(v,False) for r in rows)/sum(r['target_count']>0 for r in rows) for v in variants if 's11' in v}
|
| 61 |
+
(DEST/f'natural_{model}.json').write_text(json.dumps(out,indent=2));print('NATURAL',model,out['coverage'],flush=True)
|
| 62 |
+
with gzip.open(DEST/f'natural_{model}_evaluated.jsonl.gz','wt') as f:
|
| 63 |
+
for r in rows:f.write(json.dumps(r)+'\n')
|
| 64 |
+
return out
|
| 65 |
+
def rich(model,shards):
|
| 66 |
+
paths=[ROOT/'results'/f'rich_synthetic_{model}_{i}of{shards}.jsonl' for i in range(shards)]
|
| 67 |
+
if not all(p.with_name(p.stem+'_meta.json').exists() for p in paths):return None
|
| 68 |
+
rows=[r for p in paths for r in readlines(p)];assert len(rows)==28800 and len({r['id'] for r in rows})==28800
|
| 69 |
+
variants=list(rows[0]['scores']);tables=[];curves=[];comparisons={}
|
| 70 |
+
for render in ['flat','rich']:
|
| 71 |
+
for family in ['attribute','relational','multi_target','negative_action','empty_target','paraphrase','primary']:
|
| 72 |
+
s=[r for r in rows if r['render']==render and (r['mode'] in ['attribute','relational','multi_target','empty_target'] if family=='primary' else r['mode']==family)]
|
| 73 |
+
pairs=collections.defaultdict(list)
|
| 74 |
+
for r in s:pairs[r['pair_id']].append(r)
|
| 75 |
+
assert all(len(v)==2 for v in pairs.values())
|
| 76 |
+
for v in variants:
|
| 77 |
+
pc=[dict(scene_id=rr[0]['scene_id'],split='test',pc=float(min(r['scores'][v]['iou'] for r in rr)>=.5)) for rr in pairs.values()]
|
| 78 |
+
tables.append(dict(render=render,family=family,variant=v,PC50=float(np.mean([x['pc'] for x in pc])),PC50_ci=ci_cluster(pc,[x['pc'] for x in pc]),single_Pr50=float(np.mean([r['scores'][v]['iou']>=.5 for r in s])),**describe(s,v)))
|
| 79 |
+
if family=='primary':
|
| 80 |
+
for tau in np.arange(.3,.901,.05):curves.append(dict(render=render,variant=v,tau=float(tau),PC=float(np.mean([min(r['scores'][v]['iou'] for r in rr)>=tau for rr in pairs.values()])),Pr=float(np.mean([r['scores'][v]['iou']>=tau for r in s]))))
|
| 81 |
+
if family=='primary':
|
| 82 |
+
for v in ['anchor_gate','cacp','safe_anchor']:
|
| 83 |
+
if v not in variants:
|
| 84 |
+
continue
|
| 85 |
+
d=[dict(scene_id=rr[0]['scene_id'],split='test',value=float(min(r['scores'][v]['iou'] for r in rr)>=.5)-float(min(r['scores']['frozen']['iou'] for r in rr)>=.5)) for rr in pairs.values()]
|
| 86 |
+
comparisons[render+'/'+v]=dict(delta=float(np.mean([x['value'] for x in d])),ci=ci_cluster(d,[x['value'] for x in d]))
|
| 87 |
+
out=dict(records=len(rows),scenes=1200,tables=tables,curves=curves,comparisons=comparisons)
|
| 88 |
+
(DEST/f'rich_{model}.json').write_text(json.dumps(out,indent=2));print('RICH',model,comparisons,flush=True)
|
| 89 |
+
with gzip.open(DEST/f'rich_{model}_evaluated.jsonl.gz','wt') as f:
|
| 90 |
+
for r in rows:f.write(json.dumps(r)+'\n')
|
| 91 |
+
return out
|
| 92 |
+
def audits():
|
| 93 |
+
out={}
|
| 94 |
+
for model in ['clipseg','groundedsam']:
|
| 95 |
+
paths=list((ROOT/'results').glob(f'phase1_audit_{model}_*of4.jsonl'))
|
| 96 |
+
if len(paths)!=4:continue
|
| 97 |
+
rows=[r for p in paths for r in readlines(p)];out[model]={}
|
| 98 |
+
for scope in ['all','controlled_clean_test','natural_eval']:
|
| 99 |
+
s=[r for r in rows if scope=='all' or (scope=='controlled_clean_test' and r['domain']=='controlled' and r['split']=='test' and r['corruption']=='clean') or (scope=='natural_eval' and r['domain']=='natural' and r['split'] in ('val','testA','testB'))]
|
| 100 |
+
changed=[r for r in s if r['cf_vs_anchor_changed']]
|
| 101 |
+
out[model][scope]=dict(anchor_records=len(s),changed=len(changed),helped=sum(r['delta_iou']>1e-12 for r in changed),harmed=sum(r['delta_iou']< -1e-12 for r in changed),tied=sum(abs(r['delta_iou'])<=1e-12 for r in changed),nogate_changed=sum(r['nogate_cf_changed'] for r in s),reasons=dict(collections.Counter(r['cf_reason'] for r in s)))
|
| 102 |
+
s=[r for r in rows if r['domain']=='controlled' and r['split']=='test' and r['corruption']=='clean'];pairs=collections.defaultdict(list)
|
| 103 |
+
for r in s:pairs[r['pair_id']].append(r)
|
| 104 |
+
keys=list(s[0]['sensitivity']) if s else []
|
| 105 |
+
out[model]['sensitivity']=[dict(setting=k,PC50=float(np.mean([min(r['sensitivity'][k] for r in rr)>=.5 for rr in pairs.values()])),mIoU=float(np.mean([r['sensitivity'][k] for r in s]))) for k in keys]
|
| 106 |
+
(DEST/'phase1_exact_audit.json').write_text(json.dumps(out,indent=2));print('AUDITS',out,flush=True)
|
| 107 |
+
def phase1():
|
| 108 |
+
out={};curves=[]
|
| 109 |
+
for model in ['clipseg','groundedsam']:
|
| 110 |
+
p=OLD/'results/analysis'/f'{model}_evaluated.jsonl.gz'
|
| 111 |
+
if not p.exists():p=p.with_suffix('')
|
| 112 |
+
if not p.exists():continue
|
| 113 |
+
rows=readlines(p);s=[r for r in rows if r['domain']=='controlled' and r['split']=='test' and r['corruption']=='clean' and r['mode'] in ['attribute','relation','quantifier','absence']]
|
| 114 |
+
pairs=collections.defaultdict(list)
|
| 115 |
+
for r in s:pairs[r['pair_id']].append(r)
|
| 116 |
+
assert len(pairs)==3200
|
| 117 |
+
out[model]={}
|
| 118 |
+
for base in ['frozen','global_direction','anchor_gate']:
|
| 119 |
+
rr=[dict(scene_id=v[0]['scene_id'],split=str(v[0]['seed']),value=float(min(r['scores']['cacp']['iou'] for r in v)>=.5)-float(min(r['scores'][base]['iou'] for r in v)>=.5)) for v in pairs.values()]
|
| 120 |
+
out[model][base]=dict(delta=float(np.mean([r['value'] for r in rr])),pointwise_ci=ci_cluster(rr,[r['value'] for r in rr]),simultaneous_ci=ci_cluster(rr,[r['value'] for r in rr],alpha=.05/6))
|
| 121 |
+
for v in ['frozen','global_direction','anchor_gate','cacp']:
|
| 122 |
+
for tau in np.arange(.3,.901,.05):curves.append(dict(model=model,variant=v,tau=float(tau),PC=float(np.mean([min(r['scores'][v]['iou'] for r in rr)>=tau for rr in pairs.values()])),Pr=float(np.mean([r['scores'][v]['iou']>=tau for r in s]))))
|
| 123 |
+
for scope in ['all_natural','supported_natural']:
|
| 124 |
+
ns=[r for r in rows if r['domain']=='natural' and r['split'] in ('val','testA','testB') and (scope=='all_natural' or r['flags']['supported'])]
|
| 125 |
+
out[model][scope]=comparison(ns,'cacp')
|
| 126 |
+
(DEST/'phase1_multiplicity.json').write_text(json.dumps(out,indent=2));(DEST/'phase1_threshold_curves.json').write_text(json.dumps(curves,indent=2));print('PHASE1_STATS_COMPLETE',flush=True)
|
| 127 |
+
if __name__=='__main__':
|
| 128 |
+
ap=argparse.ArgumentParser();ap.add_argument('--part',default='all',choices=['all','natural','rich','audit','phase1']);a=ap.parse_args()
|
| 129 |
+
if a.part in ('all','natural'):
|
| 130 |
+
for m,n in [('clipseg',4),('groundedsam',16),('rela',32)]:natural(m,n)
|
| 131 |
+
if a.part in ('all','rich'):
|
| 132 |
+
for m,n in [('clipseg',4),('groundedsam',12),('rela',16)]:rich(m,n)
|
| 133 |
+
if a.part in ('all','audit'):audits()
|
| 134 |
+
if a.part in ('all','phase1'):phase1()
|
source/code/annotate_parser_audit.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Encode the assistant's text-only inspection; never a human accuracy audit."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import csv,json,collections
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];path=ROOT/'review/parser_audit_122.csv'
|
| 5 |
+
rows=list(csv.DictReader(path.open()))
|
| 6 |
+
labels={
|
| 7 |
+
'exact_cardinality_lost':[3,5,14,18,22,25,26,39,41,43,47,50,52,53,62,63,64,66,70,71,74],
|
| 8 |
+
'decomposition_artifact':[1,2,6,8,13,78,82,83],
|
| 9 |
+
'morphology_or_plurality_artifact':[12,31,94],
|
| 10 |
+
'complex_scope_unverified':[0,15,16,17,19,20,21,23,24,27,28,29,30,32,42,77,79,85,95,102,105,114,115],
|
| 11 |
+
'modifier_scope_retained':[4,9,11,33],
|
| 12 |
+
}
|
| 13 |
+
notes={
|
| 14 |
+
'exact_cardinality_lost':'The plural flag does not enforce the exact number requested by two/both/three. Incidental correct cardinality is not parsing correctness.',
|
| 15 |
+
'decomposition_artifact':'A dangling preposition or adverb remains in the target phrase. The target/anchor boundary is not a clean noun-phrase decomposition.',
|
| 16 |
+
'morphology_or_plurality_artifact':'Naive final-token singularization or the explicit plural-keyword rule changes an inflection or loses implicit plural scope.',
|
| 17 |
+
'complex_scope_unverified':'The expression contains coordination, nested modifiers, ambiguous attachment or multiple spatial constraints; one target/anchor slot does not verify full scope.',
|
| 18 |
+
'modifier_scope_retained':'A modifier remains inside a target/anchor phrase and the outer relation is separable. The new lexical guard conservatively rejects this case.',
|
| 19 |
+
'simple_representable':'The text admits the implemented plural-union or unary-extreme form, or an unambiguous outer relation. This is a text-only judgment, not verification of visual grounding.'
|
| 20 |
+
}
|
| 21 |
+
assigned={i:label for label,ids in labels.items() for i in ids};assert sum(map(len,labels.values()))==len(assigned)
|
| 22 |
+
for i,r in enumerate(rows):
|
| 23 |
+
label=assigned.get(i,'simple_representable');r.update(ai_audit_category=label,ai_audit_note=notes[label],audit_authority='AI assistant; text-only; provisional',human_verdict='',human_notes='')
|
| 24 |
+
with path.open('w') as f:
|
| 25 |
+
w=csv.DictWriter(f,fieldnames=rows[0]);w.writeheader();w.writerows(rows)
|
| 26 |
+
meta=dict(n=len(rows),authority='AI assistant; not independent human adjudication',scope='Original 122 accepted expressions in the 1,800-image Phase 1 natural evaluation; all read as text',counts=dict(collections.Counter(r['ai_audit_category'] for r in rows)),guard_accepted_counts=dict(collections.Counter(r['ai_audit_category'] for r in rows if r['scope_safe']=='True')),precision_reported=False,reason='Several categories require image context and two independent human judgments; no certified parser precision or inter-rater agreement is claimed.')
|
| 27 |
+
(ROOT/'review/parser_audit_summary.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2))
|
source/code/audit_phase1.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact mask replay and post hoc lambda/geometry sensitivity, no new fitting."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse,json,collections,os,time
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import phase1_repair as p
|
| 7 |
+
ROOT=Path(__file__).resolve().parents[1];from project_paths import legacy_root;OLD=legacy_root(ROOT)
|
| 8 |
+
def sweep(q,maps,threshold,base):
|
| 9 |
+
targets=p.components(maps[q.target],threshold);anchors=p.components(maps[q.anchor],threshold)
|
| 10 |
+
if not targets or not anchors:return {(l,g):base for l in [0,.25,.5,1] for g in [0,.015,.03,.06]}
|
| 11 |
+
ac=anchors[0];am=ac['confidence']-(anchors[1]['confidence'] if len(anchors)>1 else 0)
|
| 12 |
+
if am<.05:return {(l,g):base for l in [0,.25,.5,1] for g in [0,.015,.03,.06]}
|
| 13 |
+
key='x' if q.relation in ('left','right') else 'y';sign=1 if q.relation in ('right','below') else -1
|
| 14 |
+
candidates=[(c,sign*(c[key]-ac[key]),float((maps[q.original][c['mask']]-maps[q.opposite][c['mask']]).mean())) for c in targets]
|
| 15 |
+
outputs={}
|
| 16 |
+
for l in [0,.25,.5,1]:
|
| 17 |
+
for g in [0,.015,.03,.06]:
|
| 18 |
+
allowed=sorted([(c['confidence']+l*r,c,r) for c,d,r in candidates if d>=g],key=lambda z:z[0],reverse=True)
|
| 19 |
+
if not allowed or allowed[0][2]<-.05:out=base
|
| 20 |
+
elif not q.plural and allowed[0][0]-(allowed[1][0] if len(allowed)>1 else 0)<.05:out=base
|
| 21 |
+
else:out=p.union([c for _,c,_ in allowed] if q.plural else [allowed[0][1]],base.shape)
|
| 22 |
+
outputs[(l,g)]=out
|
| 23 |
+
return outputs
|
| 24 |
+
def main():
|
| 25 |
+
ap=argparse.ArgumentParser();ap.add_argument('--model',required=True);ap.add_argument('--shard',type=int,default=0);ap.add_argument('--shards',type=int,default=4);a=ap.parse_args()
|
| 26 |
+
manifest=[json.loads(s) for s in (OLD/'data/manifest.jsonl').read_text().splitlines()]
|
| 27 |
+
files=sorted((OLD/'results').glob(f'{a.model}_main_*of'+('2' if a.model=='clipseg' else '8')+'.jsonl'))
|
| 28 |
+
assert len(files)==(2 if a.model=='clipseg' else 8),files
|
| 29 |
+
raw={r['id']:r for f in files for r in (json.loads(s) for s in f.read_text().splitlines())}
|
| 30 |
+
selected=[r for r in manifest if p.parse_query(r['query']).anchor]
|
| 31 |
+
groups=collections.defaultdict(list)
|
| 32 |
+
for r in selected:groups[raw[r['id']]['cache_path']].append(r)
|
| 33 |
+
paths=sorted(groups)[a.shard::a.shards];threshold=.5 if a.model=='clipseg' else .25;n=0;t0=time.time()
|
| 34 |
+
with (ROOT/'results'/f'phase1_audit_{a.model}_{a.shard}of{a.shards}.jsonl').open('w') as out:
|
| 35 |
+
for ix,cache in enumerate(paths):
|
| 36 |
+
z=np.load(OLD/cache);maps={q:z[f'p{i}'].astype(np.float32) for i,q in enumerate(z['texts'].tolist())}
|
| 37 |
+
for r in groups[cache]:
|
| 38 |
+
preds,flags=p.repaired_maps(r['query'],maps,threshold);q=p.parse_query(r['query']);gt=np.asarray(Image.open(OLD/r['gt_path']))>0
|
| 39 |
+
cf=preds['cacp'];ag=preds['anchor_gate'];d=p.score_mask(cf,gt)['iou']-p.score_mask(ag,gt)['iou']
|
| 40 |
+
row={k:r[k] for k in ['id','scene_id','domain','split','mode','pair_id','endpoint','seed','corruption']}
|
| 41 |
+
row.update(model=a.model,query=r['query'],plural=q.plural,cf_vs_anchor_changed=bool((cf!=ag).any()),nogate_cf_changed=bool((preds['anchor_nogate']!=preds['counterfactual_nogate']).any()),delta_iou=d,cf_reason=flags['reason'],cf_iou=p.score_mask(cf,gt)['iou'],anchor_iou=p.score_mask(ag,gt)['iou'])
|
| 42 |
+
if (r['domain']=='controlled' and r['split']=='test' and r['corruption']=='clean') or (r['domain']=='natural' and r['split'] in ('val','testA','testB')):
|
| 43 |
+
sw=sweep(q,maps,threshold,preds['frozen']);assert np.array_equal(sw[(.5,.03)],cf)
|
| 44 |
+
row['sensitivity']={f'{l}/{g}':p.score_mask(m,gt)['iou'] for (l,g),m in sw.items()}
|
| 45 |
+
out.write(json.dumps(row)+'\n');n+=1
|
| 46 |
+
if ix%20==0:print('AUDIT',ix,len(paths),n,round(time.time()-t0,1),flush=True)
|
| 47 |
+
(ROOT/'results'/f'phase1_audit_{a.model}_{a.shard}of{a.shards}_meta.json').write_text(json.dumps(dict(status='COMPLETE',records=n,anchor_records_total=len(selected),all_phase1_records=len(manifest),no_anchor_identity_proven=True,slurm_job_id=os.getenv('SLURM_JOB_ID'),args=vars(a)),indent=2))
|
| 48 |
+
if __name__=='__main__':main()
|
source/code/build_hf_release.py
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build public data artifacts from completed RefSeg-CA experiments.
|
| 2 |
+
|
| 3 |
+
No authentication or publication occurs here. Natural-image pixels and natural
|
| 4 |
+
expression text are reconstructed from their upstream release, not redistributed.
|
| 5 |
+
"""
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import argparse, collections, csv, gzip, hashlib, json, shutil, tarfile
|
| 8 |
+
import pyarrow as pa
|
| 9 |
+
import pyarrow.parquet as pq
|
| 10 |
+
|
| 11 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 12 |
+
SEEDS = [11, 23, 37, 53, 71]
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def digest(path):
|
| 16 |
+
h = hashlib.sha256()
|
| 17 |
+
with path.open('rb') as f:
|
| 18 |
+
for chunk in iter(lambda: f.read(1024 * 1024), b''):
|
| 19 |
+
h.update(chunk)
|
| 20 |
+
return h.hexdigest()
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def write_gz_jsonl(path, rows):
|
| 24 |
+
with gzip.open(path, 'wt', encoding='utf-8') as f:
|
| 25 |
+
for row in rows:
|
| 26 |
+
f.write(json.dumps(row, ensure_ascii=False) + '\n')
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def build(dest):
|
| 30 |
+
for name in ['data', 'archives', 'manifests', 'results', 'release']:
|
| 31 |
+
(dest / name).mkdir(parents=True, exist_ok=True)
|
| 32 |
+
records = [json.loads(s) for s in (ROOT / 'data/rich_synthetic.jsonl').read_text().splitlines()]
|
| 33 |
+
scenes = [json.loads(s) for s in (ROOT / 'data/rich_scenes.jsonl').read_text().splitlines()]
|
| 34 |
+
assert len(scenes) == 1200 and len(records) == 28800
|
| 35 |
+
groups = collections.defaultdict(list)
|
| 36 |
+
for r in records:
|
| 37 |
+
groups[(r['scene_id'], r['render'])].append(r)
|
| 38 |
+
image_type = pa.struct([('bytes', pa.binary()), ('path', pa.string())])
|
| 39 |
+
features = {
|
| 40 |
+
'scene_id': {'dtype': 'string', '_type': 'Value'},
|
| 41 |
+
'seed': {'dtype': 'int64', '_type': 'Value'},
|
| 42 |
+
'render': {'dtype': 'string', '_type': 'Value'},
|
| 43 |
+
'image': {'_type': 'Image'}, 'instance_map': {'_type': 'Image'},
|
| 44 |
+
'commands_json': {'dtype': 'string', '_type': 'Value'},
|
| 45 |
+
}
|
| 46 |
+
schema = pa.schema([
|
| 47 |
+
('scene_id', pa.string()), ('seed', pa.int64()), ('render', pa.string()),
|
| 48 |
+
('image', image_type), ('instance_map', image_type), ('commands_json', pa.string())
|
| 49 |
+
], metadata={b'huggingface': json.dumps({'info': {'features': features}}).encode()})
|
| 50 |
+
for seed in SEEDS:
|
| 51 |
+
batch = []
|
| 52 |
+
selected = sorted([s for s in scenes if s['seed'] == seed], key=lambda s: s['scene_id'])
|
| 53 |
+
assert len(selected) == 240
|
| 54 |
+
for scene in selected:
|
| 55 |
+
sid = scene['scene_id']; sd = ROOT / 'data/rich' / sid
|
| 56 |
+
for render in ['flat', 'rich']:
|
| 57 |
+
qs = groups[(sid, render)]
|
| 58 |
+
assert len(qs) == 12
|
| 59 |
+
commands = [{k: q[k] for k in ['id', 'mode', 'pair_id', 'endpoint', 'query', 'target_instance_ids']} for q in qs]
|
| 60 |
+
batch.append(dict(scene_id=sid, seed=seed, render=render,
|
| 61 |
+
image={'bytes': (sd / (render + '.png')).read_bytes(), 'path': sid + '/' + render + '.png'},
|
| 62 |
+
instance_map={'bytes': (sd / 'instances.png').read_bytes(), 'path': sid + '/instances.png'},
|
| 63 |
+
commands_json=json.dumps(commands)))
|
| 64 |
+
pq.write_table(pa.Table.from_pylist(batch, schema=schema), dest / 'data' / f'seed-{seed}.parquet', compression='zstd')
|
| 65 |
+
with tarfile.open(dest / 'archives' / f'rich-seed-{seed}.tar.gz', 'w:gz', compresslevel=4) as archive:
|
| 66 |
+
for scene in selected:
|
| 67 |
+
sd = ROOT / 'data/rich' / scene['scene_id']
|
| 68 |
+
assert len(list(sd.glob('*.png'))) == 15
|
| 69 |
+
for p in sorted(sd.glob('*.png')):
|
| 70 |
+
archive.add(p, arcname=p.relative_to(ROOT).as_posix(), recursive=False)
|
| 71 |
+
print(json.dumps({'seed': seed, 'viewer_rows': len(batch), 'scenes': len(selected)}), flush=True)
|
| 72 |
+
write_gz_jsonl(dest / 'manifests/rich_synthetic.jsonl.gz', records)
|
| 73 |
+
write_gz_jsonl(dest / 'manifests/rich_scenes.jsonl.gz', scenes)
|
| 74 |
+
with gzip.open(ROOT / 'results/r3/portable/natural_full_manifest.jsonl.gz', 'rt') as f:
|
| 75 |
+
natural = [json.loads(s) for s in f]
|
| 76 |
+
write_gz_jsonl(dest / 'manifests/natural_index.jsonl.gz', [{k: v for k, v in r.items() if k != 'query'} for r in natural])
|
| 77 |
+
scratch = dest / '_metric_staging'
|
| 78 |
+
(scratch / 'results/r3/portable').mkdir(parents=True, exist_ok=True)
|
| 79 |
+
(scratch / 'results/analysis').mkdir(parents=True, exist_ok=True)
|
| 80 |
+
for p in (ROOT / 'results/r3/portable').glob('*_primary.csv.gz'):
|
| 81 |
+
shutil.copy2(p, scratch / 'results/r3/portable' / p.name)
|
| 82 |
+
for model in ['clipseg', 'groundedsam']:
|
| 83 |
+
with gzip.open(ROOT / 'results/r3' / f'{model}_replay.jsonl.gz', 'rt') as f:
|
| 84 |
+
rows = [json.loads(s) for s in f]
|
| 85 |
+
write_gz_jsonl(scratch / 'results/r3' / f'{model}_replay.jsonl.gz', [{k: v for k, v in r.items() if k != 'query'} for r in rows])
|
| 86 |
+
for rel in ['results/r3/review_results.json', 'results/analysis/paper_results.json']:
|
| 87 |
+
shutil.copy2(ROOT / rel, scratch / rel)
|
| 88 |
+
with tarfile.open(dest / 'results/primary-and-review-metrics.tar.gz', 'w:gz') as archive:
|
| 89 |
+
for p in sorted(scratch.rglob('*')):
|
| 90 |
+
if p.is_file(): archive.add(p, arcname=p.relative_to(scratch).as_posix(), recursive=False)
|
| 91 |
+
shutil.rmtree(scratch)
|
| 92 |
+
report = dict(version='R3', scenes=1200, rendered_images=2400, command_image_records=28800,
|
| 93 |
+
natural_expressions_scored=49492, viewer_rows=2400, seeds=SEEDS,
|
| 94 |
+
renderer='deterministic Pillow raster renderer', human_validation='not conducted',
|
| 95 |
+
natural_pixels_and_expression_text='retrieve from the pinned upstream release')
|
| 96 |
+
report['files'] = {p.relative_to(dest).as_posix(): {'bytes': p.stat().st_size, 'sha256': digest(p)}
|
| 97 |
+
for p in sorted(dest.rglob('*')) if p.is_file() and p.name != 'DATA_MANIFEST.json'}
|
| 98 |
+
(dest / 'DATA_MANIFEST.json').write_text(json.dumps(report, indent=2))
|
| 99 |
+
print(json.dumps({'status': 'BUILT', 'files': len(report['files']), 'bytes': sum(v['bytes'] for v in report['files'].values())}), flush=True)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
if __name__ == '__main__':
|
| 103 |
+
ap = argparse.ArgumentParser(); ap.add_argument('--output', type=Path, default=ROOT / 'release_public')
|
| 104 |
+
build(ap.parse_args().output)
|
source/code/build_latex.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Compile vector figures and the unmodified Springer Nature journal template.
|
| 2 |
+
Uses an existing TeX installation; the fallback only creates a local format/map
|
| 3 |
+
when a workspace runtime has TeX sources but no configured format database.
|
| 4 |
+
"""
|
| 5 |
+
from pathlib import Path
|
| 6 |
+
import os,subprocess,argparse,shutil
|
| 7 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 8 |
+
def environment():
|
| 9 |
+
env=os.environ.copy()
|
| 10 |
+
tmp=ROOT/'build/tmp';tmp.mkdir(parents=True,exist_ok=True);env['TMPDIR']=str(tmp)
|
| 11 |
+
if subprocess.run(['kpsewhich','article.cls'],capture_output=True,text=True).stdout.strip():return env
|
| 12 |
+
tex=Path('/usr/share/texlive/texmf-dist')
|
| 13 |
+
if not (tex/'tex/latex/base/article.cls').exists():raise RuntimeError('Install a standard TeX Live distribution with pgfplots, standalone and Springer dependencies')
|
| 14 |
+
aux=ROOT/'build/texlocal';aux.mkdir(parents=True,exist_ok=True)
|
| 15 |
+
env.update(TEXMF=str(tex),TEXMFVAR=str(aux),TEXMFCONFIG=str(aux),TEXFORMATS=str(aux)+'//:',TEXFONTMAPS=str(aux)+'//:'+str(tex/'fonts/map')+'//:')
|
| 16 |
+
if not (aux/'pdflatex.fmt').exists():
|
| 17 |
+
run(['pdftex','-ini','-interaction=batchmode','-halt-on-error','-jobname=pdflatex','-progname=pdflatex','-output-directory='+str(aux),'-etex','pdflatex.ini'],ROOT,env)
|
| 18 |
+
maps=tex/'fonts/map/dvips';files=list((maps/'amsfonts').glob('*.map'))+[maps/'helvetic/uhv.map',maps/'psnfss/psnfss.map']
|
| 19 |
+
(aux/'pdftex.map').write_text('\n'.join(f.read_text() for f in files))
|
| 20 |
+
return env
|
| 21 |
+
def run(cmd,cwd,env):
|
| 22 |
+
p=subprocess.run(cmd,cwd=cwd,env=env,capture_output=True,text=True)
|
| 23 |
+
if p.returncode:
|
| 24 |
+
print(p.stdout[-4000:]);print(p.stderr[-1000:])
|
| 25 |
+
if cmd[0]=='pdflatex':
|
| 26 |
+
log=Path(cwd)/Path(cmd[-1]).with_suffix('.log')
|
| 27 |
+
if log.exists():print(log.read_text(errors='replace')[-5000:])
|
| 28 |
+
raise RuntimeError('Command failed: '+' '.join(cmd))
|
| 29 |
+
return p
|
| 30 |
+
def main():
|
| 31 |
+
a=argparse.ArgumentParser();a.add_argument('--figures-only',action='store_true');a.add_argument('--manuscript-only',action='store_true');args=a.parse_args();env=environment()
|
| 32 |
+
figout=ROOT/'build/verified_figures';figout.mkdir(parents=True,exist_ok=True)
|
| 33 |
+
for f in ([] if args.manuscript_only else sorted((ROOT/'figures').glob('Fig*.tex'))):
|
| 34 |
+
run(['pdflatex','-interaction=nonstopmode','-halt-on-error','-output-directory='+str(figout),f.name],f.parent,env)
|
| 35 |
+
import fitz
|
| 36 |
+
pdf=figout/f.with_suffix('.pdf').name
|
| 37 |
+
with fitz.open(pdf) as doc:assert doc.page_count==1,f.name
|
| 38 |
+
shutil.copy2(pdf,f.with_suffix('.pdf'));print('Compiled',f.name,flush=True)
|
| 39 |
+
# Keep the journal-facing PDF as the canonical vector artifact.
|
| 40 |
+
# EPS conversion is intentionally omitted: the available Poppler
|
| 41 |
+
# wrapper is not reliable in this runtime.
|
| 42 |
+
main=ROOT/'latex/RefSeg_CA_MVA.tex'
|
| 43 |
+
if not args.figures_only and main.exists():
|
| 44 |
+
run(['pdflatex','-interaction=nonstopmode','-halt-on-error',main.name],main.parent,env)
|
| 45 |
+
run(['bibtex',main.stem],main.parent,env)
|
| 46 |
+
for _ in range(2):run(['pdflatex','-interaction=nonstopmode','-halt-on-error',main.name],main.parent,env)
|
| 47 |
+
print('Compiled manuscript',flush=True)
|
| 48 |
+
if __name__=='__main__':main()
|
source/code/download_release_data.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download and verify public RefSeg-CA artifacts using Python's standard library."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse, gzip, hashlib, json, shutil, tarfile, urllib.request
|
| 4 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 5 |
+
REPO = 'Ethosoft/RefSeg-CA'
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def fetch(base, name, cache, manifest):
|
| 9 |
+
out = cache / name; out.parent.mkdir(parents=True, exist_ok=True)
|
| 10 |
+
expected = manifest['files'][name]['sha256']
|
| 11 |
+
if not out.exists() or hashlib.sha256(out.read_bytes()).hexdigest() != expected:
|
| 12 |
+
tmp = out.with_suffix(out.suffix + '.part')
|
| 13 |
+
with urllib.request.urlopen(base + '/' + name, timeout=120) as r, tmp.open('wb') as f:
|
| 14 |
+
shutil.copyfileobj(r, f)
|
| 15 |
+
assert hashlib.sha256(tmp.read_bytes()).hexdigest() == expected, name + ': checksum mismatch'
|
| 16 |
+
tmp.replace(out)
|
| 17 |
+
return out
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def extract(path, dest):
|
| 21 |
+
with tarfile.open(path) as archive:
|
| 22 |
+
for m in archive.getmembers():
|
| 23 |
+
target = (dest / m.name).resolve()
|
| 24 |
+
if not m.isfile() or not target.is_relative_to(dest.resolve()):
|
| 25 |
+
raise ValueError('Unsafe archive member: ' + m.name)
|
| 26 |
+
target.parent.mkdir(parents=True, exist_ok=True)
|
| 27 |
+
with archive.extractfile(m) as source, target.open('wb') as out:
|
| 28 |
+
shutil.copyfileobj(source, out)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def main():
|
| 32 |
+
ap = argparse.ArgumentParser(); ap.add_argument('--revision', default='r3-data-v1')
|
| 33 |
+
ap.add_argument('--synthetic', action='store_true'); a = ap.parse_args()
|
| 34 |
+
base = f'https://huggingface.co/datasets/{REPO}/resolve/{a.revision}'
|
| 35 |
+
with urllib.request.urlopen(base + '/DATA_MANIFEST.json', timeout=60) as r: manifest = json.load(r)
|
| 36 |
+
cache = ROOT / 'build/downloads'; cache.mkdir(parents=True, exist_ok=True)
|
| 37 |
+
extract(fetch(base, 'results/primary-and-review-metrics.tar.gz', cache, manifest), ROOT)
|
| 38 |
+
for name in ['rich_synthetic', 'rich_scenes']:
|
| 39 |
+
p = fetch(base, 'manifests/' + name + '.jsonl.gz', cache, manifest)
|
| 40 |
+
out = ROOT / 'data' / (name + '.jsonl'); out.parent.mkdir(parents=True, exist_ok=True)
|
| 41 |
+
with gzip.open(p, 'rb') as r, out.open('wb') as f: shutil.copyfileobj(r, f)
|
| 42 |
+
if a.synthetic:
|
| 43 |
+
for seed in manifest['seeds']:
|
| 44 |
+
extract(fetch(base, f'archives/rich-seed-{seed}.tar.gz', cache, manifest), ROOT)
|
| 45 |
+
print(json.dumps({'status': 'DOWNLOADED_AND_VERIFIED', 'revision': a.revision, 'synthetic_images': a.synthetic}))
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
if __name__ == '__main__': main()
|
source/code/figures_r2.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Editable publication figures: TikZ layouts and PGFPlots data graphics."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json,shutil,math
|
| 4 |
+
from PIL import Image
|
| 5 |
+
import numpy as np
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1];F=ROOT/'figures';A=ROOT/'results/analysis';OLD=ROOT.parent/'RefSeg_Scale_MVA'
|
| 7 |
+
def esc(s):return str(s).replace('_',r'\_').replace('%',r'\%').replace('&',r'\&')
|
| 8 |
+
def write(name,body):
|
| 9 |
+
(F/(name+'.tex')).write_text('\\documentclass[tikz,border=1.5pt]{standalone}\n\\input{style}\n\\begin{document}\n'+body+'\n\\end{document}\n')
|
| 10 |
+
def atlas():
|
| 11 |
+
scenes=[json.loads(s) for s in (ROOT/'data/rich_scenes.jsonl').read_text().splitlines()]
|
| 12 |
+
families=['attribute','relational','multi_target','negative_action','empty_target'];names=['ATTRIBUTE','RELATION','TARGET SET','ACTION','ABSENCE'];colors=['teal','violet','ochre','rose','ink']
|
| 13 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-108) rectangle (164,8);',r'\node[anchor=west,font=\sffamily\bfseries\fontsize{10}{12}\selectfont] at (0,5) {A richer test of the same five command regimes};']
|
| 14 |
+
selections=[]
|
| 15 |
+
for j,(family,name,color) in enumerate(zip(families,names,colors)):
|
| 16 |
+
x=j*33
|
| 17 |
+
lines.append(r'\fill[%s] (%s,0) rectangle (%s,-1);'%(color,x,x+31))
|
| 18 |
+
lines.append(r'\node[anchor=north,font=\sffamily\bfseries\fontsize{7.5}{9}\selectfont,text=%s] at (%s,-2) {%s};'%(color,x+15.5,name))
|
| 19 |
+
for i in [0,1]:
|
| 20 |
+
scene=scenes[(j+5*i)%len(scenes)];sid=scene['scene_id'];pair=next(p for p in scene['pairs'] if p[0]==family);endpoint=1 if family in ['negative_action','empty_target'] else i
|
| 21 |
+
query=pair[1][endpoint];count=len(pair[2][endpoint]);y=-10-i*49
|
| 22 |
+
rgb=ROOT/'data/rich'/sid/'rich.png';namefile=f'atlas_{i}_{j}.png';shutil.copy2(rgb,F/'assets'/namefile)
|
| 23 |
+
lines.append(r'\node[anchor=north west,inner sep=0] at (%s,%s) {\includegraphics[width=31mm]{assets/%s}};'%(x,y,namefile))
|
| 24 |
+
lines.append(r'\draw[rule,line width=.3pt] (%s,%s) rectangle (%s,%s);'%(x,y,x+31,y-31))
|
| 25 |
+
lines.append(r'\node[anchor=south east,fill=white,inner sep=.7mm,font=\sffamily\bfseries\fontsize{7}{8}\selectfont] at (%s,%s) {$|G|=%s$};'%(x+30.5,y-30.5,count))
|
| 26 |
+
lines.append(r'\node[anchor=north west,text width=30mm,align=left,font=\sffamily\fontsize{7.3}{8.8}\selectfont] at (%s,%s) {\textbf{%s}\enspace %s};'%(x,y-33,chr(97+j+5*i),esc(query)))
|
| 27 |
+
selections.append(dict(panel=chr(97+j+5*i),scene_id=sid,family=family,query=query,target_count=count,raster=str(rgb.relative_to(ROOT))))
|
| 28 |
+
lines.append(r'\end{tikzpicture}');write('Fig2_rich_atlas','\n'.join(lines));(F/'atlas_manifest.json').write_text(json.dumps(selections,indent=2))
|
| 29 |
+
def paired_render():
|
| 30 |
+
scenes=[json.loads(s) for s in (ROOT/'data/rich_scenes.jsonl').read_text().splitlines()];selected=[scenes[3],scenes[6],scenes[8]]
|
| 31 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (-2,-13) rectangle (164,108);']
|
| 32 |
+
for j,title in enumerate(['Flat surface','Rich surface','Shared target mask']):lines.append(r'\node[anchor=south,font=\sffamily\bfseries\fontsize{8}{10}\selectfont] at (%s,100) {%s};'%(24+j*51,title))
|
| 33 |
+
for i,scene in enumerate(selected):
|
| 34 |
+
y=98-i*35;sid=scene['scene_id'];query=scene['pairs'][1][1][0]
|
| 35 |
+
for j,kind in enumerate(['flat','rich','relational_0']):
|
| 36 |
+
src=ROOT/'data/rich'/sid/(kind+'.png');dst=F/'assets'/f'paired_{i}_{kind}.png'
|
| 37 |
+
im=Image.open(src)
|
| 38 |
+
if j==2:
|
| 39 |
+
mask=np.asarray(im)>0;a=np.full((*mask.shape,3),246,np.uint8);a[mask]=[20,125,131];im=Image.fromarray(a)
|
| 40 |
+
im.save(dst);x=8+j*51
|
| 41 |
+
lines.append(r'\node[anchor=north west,inner sep=0] at (%s,%s) {\includegraphics[width=31mm]{assets/%s}};'%(x,y,dst.name))
|
| 42 |
+
if j<2:lines.append(r'\draw[link,draw=muted] (%s,%s)--(%s,%s);'%(x+33,y-15.5,x+46,y-15.5))
|
| 43 |
+
lines.append(r'\node[anchor=west,text width=150mm,font=\sffamily\fontsize{7.6}{9}\selectfont] at (0,%s) {\textbf{%s}\enspace %s};'%(y-33,chr(97+i),esc(query)))
|
| 44 |
+
lines.append(r'\end{tikzpicture}');write('Fig3_paired_render','\n'.join(lines))
|
| 45 |
+
def method():
|
| 46 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-11) rectangle (164,88);',r'\fill[paper,rounded corners=1.5mm] (0,63) rectangle (164,88);',r'\node[anchor=west,font=\sffamily\bfseries\fontsize{10}{12}\selectfont] at (4,82) {RefSeg-CA: three questions for one output};']
|
| 47 |
+
for x,title,sub,col in [(4,'MASK QUALITY','Is the returned region correct?','teal'),(59,'COMMAND COMPLIANCE','Does the output obey the instruction?','violet'),(115,'RESPONSIVENESS','Does a changed request stay correct?','ochre')]:
|
| 48 |
+
lines.append(r'\node[anchor=west,text=%s,font=\sffamily\bfseries\fontsize{7.8}{9}\selectfont] at (%s,75) {%s};'%(col,x,title))
|
| 49 |
+
lines.append(r'\node[anchor=north west,text width=47mm,align=left,font=\sffamily\fontsize{8}{10}\selectfont] at (%s,72) {%s};'%(x,sub))
|
| 50 |
+
boxes=[(0,43,28,'RGB + expression','Frozen interface','ink'),(34,43,29,'Scope guard',r'Target\\anchor\\relation','violet'),(70,43,28,'Predicted geometry','Eligible target components','teal'),(106,43,27,'Decision gates','Union or select; else fallback','teal'),(140,43,24,'Output mask','Action rule','ink')]
|
| 51 |
+
for i,(x,y,w,title,sub,col) in enumerate(boxes):
|
| 52 |
+
lines.append(r'\node[box,draw=%s!55,fill=%s!4,minimum width=%s mm,minimum height=23mm,text width=%s mm,anchor=north west,inner sep=1.5mm] (b%s) at (%s,%s) {\textbf{%s}\\[1.3mm]%s};'%(col,col,w,w-3,i,x,y,title,sub))
|
| 53 |
+
if i:lines.append(r'\draw[link,draw=teal] (b%s.east)--(b%s.west);'%(i-1,i))
|
| 54 |
+
lines.append(r'\node[anchor=west,text=teal,font=\sffamily\bfseries\fontsize{8}{10}\selectfont] at (0,53) {SCOPE-FILTERED ANCHOR PROJECTION};')
|
| 55 |
+
lines.append(r'\node[anchor=east,text=muted] at (164,53) {1--3 unique queries; no labels at inference};')
|
| 56 |
+
lines.append(r'\draw[route,draw=muted,dashed] (b1.south)--(48.5,14)-|(b4.south);')
|
| 57 |
+
lines.append(r'\node[fill=white,text=muted,inner sep=.7mm] at (92,14) {unsupported / ambiguous: preserve full-query output};')
|
| 58 |
+
lines.append(r'\node[box,draw=ochre!50,fill=ochre!4,anchor=north west,text width=73mm,inner sep=2mm] at (0,7) {\textbf{Counterfactual audit}\quad Opposite relation, residual score and veto; retained as a measured ablation};')
|
| 59 |
+
lines.append(r'\node[box,draw=rose!50,fill=rose!4,anchor=north east,text width=73mm,inner sep=2mm] at (164,7) {\textbf{Separate absence decision}\quad Fit and calibrate on disjoint images; expose positive-mask losses};')
|
| 60 |
+
lines.append(r'\end{tikzpicture}');write('Fig1_framework','\n'.join(lines))
|
| 61 |
+
def multiplicity():
|
| 62 |
+
data=json.loads((A/'phase1_multiplicity.json').read_text());lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-14) rectangle (163,78);']
|
| 63 |
+
contrasts=[('frozen','CACP $-$ frozen'),('global_direction','CACP $-$ global rule'),('anchor_gate','CACP $-$ anchor only')]
|
| 64 |
+
for panel,(model,label) in enumerate([('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')]):
|
| 65 |
+
dx=panel*83;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,73) {%s\enspace %s};'%(dx,chr(97+panel),label))
|
| 66 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=55mm,height=57mm,xmin=-2,xmax=29,ymin=-.5,ymax=2.7,ytick=\empty,axis y line=none,axis x line=bottom,xlabel={Paired-correctness change (pp)},xmajorgrids,xtick={0,10,20}]'%(dx+20))
|
| 67 |
+
lines.append(r'\addplot[muted,dashed] coordinates {(0,-.5)(0,2.7)};')
|
| 68 |
+
for j,(key,title) in enumerate(contrasts):
|
| 69 |
+
z=data[model][key];y=2-j;lo,hi=[v*100 for v in z['simultaneous_ci']];d=z['delta']*100;color='rose' if key=='anchor_gate' else 'teal'
|
| 70 |
+
lines.append(r'\addplot[%s,line width=2.4pt,opacity=.22] coordinates {(%.6f,%s)(%.6f,%s)};'%(color,lo,y,hi,y))
|
| 71 |
+
lines.append(r'\addplot[%s,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(%.6f,%s) += (%.6f,0) -= (%.6f,0)};'%(color,d,y,hi-d,d-lo))
|
| 72 |
+
lines.append(r'\node[anchor=south west,font=\sffamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,%s) {%s};'%(y+.18,title))
|
| 73 |
+
lines.append(r'\node[anchor=north,font=\sffamily\bfseries\fontsize{8}{10}\selectfont,text=%s] at (axis cs:%.6f,%s) {%+.2f};'%(color,d,y-.13,d))
|
| 74 |
+
lines.append(r'\end{axis}')
|
| 75 |
+
lines.append(r'\node[anchor=west,text=muted] at (0,-13) {Six contrasts; image-cluster bootstrap with Bonferroni-adjusted intervals};');lines.append(r'\end{tikzpicture}');write('Fig4_corrected_contrasts','\n'.join(lines))
|
| 76 |
+
def thresholds():
|
| 77 |
+
data=json.loads((A/'phase1_threshold_curves.json').read_text());lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]']
|
| 78 |
+
styles=[('frozen','muted','dashed'),('global_direction','ochre','densely dotted'),('anchor_gate','teal','solid'),('cacp','violet','dashdotted')]
|
| 79 |
+
for j,(model,label) in enumerate([('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')]):
|
| 80 |
+
dx=j*82;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,61) {%s};'%(dx,label))
|
| 81 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=64mm,height=48mm,xmin=.3,xmax=.9,ymin=0,ymax=65,xlabel={IoU threshold $\tau$},ylabel={Correct (\%%)},ymajorgrids,xtick={.3,.5,.7,.9}]'%(dx+10))
|
| 82 |
+
for v,col,sty in styles:
|
| 83 |
+
s=[r for r in data if r['model']==model and r['variant']==v]
|
| 84 |
+
coord=' '.join('(%.3f,%.5f)'%(r['tau'],r['PC']*100) for r in s)
|
| 85 |
+
lines.append(r'\addplot[%s,%s,line width=1pt] coordinates {'%(col,sty)+coord+'};')
|
| 86 |
+
s=[r for r in data if r['model']==model and r['variant']=='anchor_gate'];coords=' '.join('(%.3f,%.5f)'%(r['tau'],r['Pr']*100) for r in s)
|
| 87 |
+
lines.append(r'\addplot[teal,dashed,opacity=.5,line width=.8pt] coordinates {'+coords+'};');lines.append(r'\end{axis}')
|
| 88 |
+
lines.append(r'\node[anchor=west,font=\sffamily\fontsize{7.8}{9}\selectfont] at (0,-17) {\textcolor{muted}{Frozen}\quad\textcolor{ochre}{Global rule}\quad\textcolor{teal}{Anchor only}\quad\textcolor{violet}{CACP}\quad Pale dashed: anchor single-expression accuracy};');lines.append(r'\end{tikzpicture}');write('Fig5_thresholds','\n'.join(lines))
|
| 89 |
+
def natural_effects():
|
| 90 |
+
vals=[('CLIPSeg',.1081337,.0772914,.1403822,3.43722,2.371,4.474),
|
| 91 |
+
('Grounded SAM',.0715455,.0349176,.1077133,2.27420,1.184,3.308)]
|
| 92 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',
|
| 93 |
+
r'\path[use as bounding box] (0,-13) rectangle (164,67);',
|
| 94 |
+
r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (0,62) {a\enspace Coverage funnel};',
|
| 95 |
+
r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (83,62) {b\enspace SFAP effect};']
|
| 96 |
+
funnel=[('All expressions',49492,'ink'),('Old grammar',2809,'ochre'),('Scope accepted',1557,'violet'),('Simple relations',382,'teal')]
|
| 97 |
+
for i,(lab,n,col) in enumerate(funnel):
|
| 98 |
+
y=48-i*13;w=70*(n/49492)**.34
|
| 99 |
+
lines.append(r'\fill[%s!13,rounded corners=.7mm] (0,%s) rectangle (%s,%s);'%(col,y,w,y+8))
|
| 100 |
+
lines.append(r'\draw[%s,line width=.55pt,rounded corners=.7mm] (0,%s) rectangle (%s,%s);'%(col,y,w,y+8))
|
| 101 |
+
lines.append(r'\node[anchor=west,font=\sffamily\fontsize{7.5}{9}\selectfont] at (2,%s) {%s};'%(y+4,lab))
|
| 102 |
+
lines.append(r'\node[anchor=east,font=\sffamily\bfseries\fontsize{7.5}{9}\selectfont,text=%s] at (78,%s) {%s};'%(col,y+4,f'{n:,}'))
|
| 103 |
+
lines.append(r'\begin{axis}[journal,at={(88mm,0mm)},anchor=south west,width=72mm,height=52mm,xmin=0,xmax=5.1,ymin=-.5,ymax=3.6,ytick=\empty,axis y line=none,axis x line=bottom,xlabel={gIoU change (percentage points)},xmajorgrids]')
|
| 104 |
+
for j,(m,p,plo,phi,a,alo,ahi) in enumerate(vals):
|
| 105 |
+
for y,v,lo,hi,col in [(j,p,plo,phi,'muted'),(j+2,a,alo,ahi,'teal')]:
|
| 106 |
+
lines.append(r'\addplot[%s,line width=3pt,opacity=.18] coordinates {(%.6f,%s)(%.6f,%s)};'%(col,lo,y,hi,y))
|
| 107 |
+
lines.append(r'\addplot[%s,mark=*,mark size=2pt] coordinates {(%.6f,%s)};'%(col,v,y))
|
| 108 |
+
for y,lab in enumerate(['Grounded SAM pooled','CLIPSeg pooled','Grounded SAM accepted','CLIPSeg accepted']):
|
| 109 |
+
lines.append(r'\node[anchor=east,font=\sffamily\fontsize{6.8}{8}\selectfont,text=ink] at (axis cs:5.0,%s) {%s};'%(y+.20,lab))
|
| 110 |
+
lines.append(r'\end{axis}')
|
| 111 |
+
lines.append(r'\node[anchor=west,text=muted,font=\sffamily\fontsize{7.3}{9}\selectfont] at (0,-11) {All 49,492 expressions; accepted subset selected by text only. Intervals resample images.};')
|
| 112 |
+
lines.append(r'\end{tikzpicture}');write('Fig6_natural_effects','\n'.join(lines))
|
| 113 |
+
def absence_tradeoff():
|
| 114 |
+
data=[('CLIPSeg','Frozen',71.158,28.397,26.686,'muted'),('CLIPSeg','Source',88.051,22.376,56.089,'rose'),('CLIPSeg',r'5\% bound',73.449,28.468,27.833,'teal'),
|
| 115 |
+
('Grounded SAM','Frozen',15.333,53.308,.712,'muted'),('Grounded SAM','Source',29.702,45.132,20.146,'rose'),('Grounded SAM',r'5\% bound',16.215,53.342,.788,'teal')]
|
| 116 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-14) rectangle (164,67);']
|
| 117 |
+
for panel,model in enumerate(['CLIPSeg','Grounded SAM']):
|
| 118 |
+
dx=panel*82;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,62) {%s};'%(dx,model))
|
| 119 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=68mm,height=49mm,xmin=0,xmax=100,ymin=0,ymax=60,xlabel={No-target accuracy (\%%)},ylabel={Positive mIoU (\%%)},xmajorgrids,ymajorgrids]'%(dx+8))
|
| 120 |
+
for m,rule,x,y,fe,col in data:
|
| 121 |
+
if m!=model:continue
|
| 122 |
+
anch='north east' if rule=='Frozen' else 'south west'
|
| 123 |
+
shift='yshift=-1mm' if rule=='Frozen' else 'yshift=1mm'
|
| 124 |
+
lines.append(r'\addplot[%s,only marks,mark=*,mark size=2.6pt] coordinates {(%.4f,%.4f)} node[anchor=%s,%s,font=\sffamily\fontsize{7}{8}\selectfont,text=%s] {%s};'%(col,x,y,anch,shift,col,rule))
|
| 125 |
+
lines.append(r'\end{axis}')
|
| 126 |
+
lines.append(r'\node[anchor=west,text=muted,font=\sffamily\fontsize{7.3}{9}\selectfont] at (0,-12) {Moving right can erase positive masks: source calibration raises N-acc but sharply lowers positive mIoU.};')
|
| 127 |
+
lines.append(r'\end{tikzpicture}');write('Fig7_absence_tradeoff','\n'.join(lines))
|
| 128 |
+
def rich_performance():
|
| 129 |
+
panels=[('Flat',[('CLIPSeg',4.5208,17.4792),('Grounded SAM',.0833,8.0),('ReLA',5.8542,None)]),
|
| 130 |
+
('Rich',[('CLIPSeg',3.2708,9.0),('Grounded SAM',.5,17.3333),('ReLA',7.3958,None)])]
|
| 131 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]',r'\path[use as bounding box] (0,-14) rectangle (164,68);']
|
| 132 |
+
for j,(title,rows) in enumerate(panels):
|
| 133 |
+
dx=j*82;lines.append(r'\node[anchor=west,font=\sffamily\bfseries\fontsize{9}{11}\selectfont] at (%s,63) {%s render};'%(dx,title))
|
| 134 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=68mm,height=52mm,xmin=0,xmax=20,ymin=-.5,ymax=2.6,ytick=\empty,xlabel={PC$_{0.5}$ (\%%)},xmajorgrids]'%(dx+8))
|
| 135 |
+
for y,(model,frozen,sfap) in enumerate(rows[::-1]):
|
| 136 |
+
lines.append(r'\node[anchor=east,font=\sffamily\fontsize{7.2}{9}\selectfont] at (axis cs:19.6,%s) {%s};'%(y+.18,model))
|
| 137 |
+
if sfap is None:
|
| 138 |
+
lines.append(r'\addplot[violet,only marks,mark=diamond*,mark size=2.7pt] coordinates {(%.5f,%s)};'%(frozen,y))
|
| 139 |
+
else:
|
| 140 |
+
lines.append(r'\addplot[muted,line width=2.6pt,opacity=.2] coordinates {(%.5f,%s)(%.5f,%s)};'%(frozen,y,sfap,y))
|
| 141 |
+
lines.append(r'\addplot[muted,only marks,mark=*,mark size=2pt] coordinates {(%.5f,%s)};'%(frozen,y))
|
| 142 |
+
lines.append(r'\addplot[teal,only marks,mark=*,mark size=2.8pt] coordinates {(%.5f,%s)};'%(sfap,y))
|
| 143 |
+
lines.append(r'\end{axis}')
|
| 144 |
+
lines.append(r'\node[anchor=west,font=\sffamily\fontsize{7.3}{9}\selectfont,text=muted] at (0,-12) {Gray: frozen\quad Teal: SFAP\quad Violet diamond: trained ReLA native output.};')
|
| 145 |
+
lines.append(r'\end{tikzpicture}');write('Fig8_rich_performance','\n'.join(lines))
|
| 146 |
+
if __name__=='__main__':
|
| 147 |
+
atlas();paired_render();method();multiplicity();thresholds();natural_effects();absence_tradeoff();rich_performance()
|
source/code/figures_r3.py
ADDED
|
@@ -0,0 +1,123 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Sparse journal figures: vector mathematics and measured evidence only."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json
|
| 4 |
+
import figures_r2 as old
|
| 5 |
+
ROOT=Path(__file__).resolve().parents[1];F=ROOT/'figures'
|
| 6 |
+
def write(name,body):old.write(name,body)
|
| 7 |
+
def framework():
|
| 8 |
+
write('Fig1_framework',r'''
|
| 9 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 10 |
+
\path[use as bounding box] (0,-3) rectangle (164,57);
|
| 11 |
+
\node[anchor=west,font=\bfseries\small] at (0,54) {(a) Scope and projection};
|
| 12 |
+
\node[anchor=west,font=\bfseries\small] at (99,54) {(b) Spatial eligibility};
|
| 13 |
+
\node (q) at (4,34) {$I,q$};
|
| 14 |
+
\node[draw,rectangle,minimum width=14mm,minimum height=10mm] (f) at (28,34) {$f_{\theta}$};
|
| 15 |
+
\node (p) at (54,34) {$P_q,P_t,P_a$};
|
| 16 |
+
\node[draw,rectangle,minimum width=15mm,minimum height=10mm] (proj) at (80,34) {$\Pi_r$};
|
| 17 |
+
\draw[link] (q)--(f);
|
| 18 |
+
\draw[link] (f)--(p);
|
| 19 |
+
\draw[link] (p)--(proj);
|
| 20 |
+
\node[font=\small] at (28,43) {$\theta$ fixed};
|
| 21 |
+
\node (guard) at (28,16) {$S(q)\in\{0,1\}$};
|
| 22 |
+
\draw[link] (q.south)|-(guard.west);
|
| 23 |
+
\draw[link] (guard.north)--node[right,font=\scriptsize] {$S=1$}(f.south);
|
| 24 |
+
\draw[link,dashed] (guard.east)--(80,16)--(proj.south);
|
| 25 |
+
\node[font=\scriptsize,fill=white,inner sep=1pt] at (57,16) {fallback $M_q$};
|
| 26 |
+
\node[anchor=west,font=\scriptsize] at (0,0) {$\widehat M=\Pi_r(P_q,P_t,P_a)$ if $S(q)\land V$; otherwise $M_q$.};
|
| 27 |
+
\draw[rule] (95,3)--(95,49);
|
| 28 |
+
\draw[->,line width=.5pt] (103,8)--(162,8) node[below] {$x$};
|
| 29 |
+
\draw[->,line width=.5pt] (103,8)--(103,46) node[left] {$y$};
|
| 30 |
+
\fill[black!7] (131,9) rectangle (159,44);
|
| 31 |
+
\draw[dashed,muted] (131,8)--(131,46);
|
| 32 |
+
\node[anchor=south,font=\scriptsize] at (131,46) {$x_A+\epsilon_g$};
|
| 33 |
+
\draw[fill=black!15,line width=.6pt] (117,25) circle (3.8);
|
| 34 |
+
\node at (117,25) {$A$};
|
| 35 |
+
\draw[line width=.6pt] (111,37) ellipse (4 and 2.4);
|
| 36 |
+
\node[above] at (111,39) {$C_1$};
|
| 37 |
+
\draw[teal,fill=teal!14,line width=.8pt] (141,32) ellipse (4.5 and 3);
|
| 38 |
+
\draw[teal,fill=teal!14,line width=.8pt] (150,18) ellipse (4 and 2.8);
|
| 39 |
+
\node[above] at (141,35) {$C_2$};
|
| 40 |
+
\node[above] at (150,21) {$C_3$};
|
| 41 |
+
\draw[link] (121,25)--(136,31);
|
| 42 |
+
\node[anchor=north,font=\small] at (132,3) {$\mathcal E_{\rightarrow}=\{C_2,C_3\}$};
|
| 43 |
+
\end{tikzpicture}''')
|
| 44 |
+
def coverage(data):
|
| 45 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]']
|
| 46 |
+
for j,(model,title) in enumerate([('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')]):
|
| 47 |
+
x=j*82
|
| 48 |
+
lines.append(r'\node[anchor=west,font=\bfseries\small] at (%s,50) {%s};'%(x,title))
|
| 49 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=64mm,height=40mm,xmin=0,xmax=6,ymin=-.02,ymax=.2,xlabel={Accepted expressions (\%%)},ylabel={$\Delta$gIoU (pp)},axis lines=left,xtick={0,1,2,3,4,5,6}]'%(x+10))
|
| 50 |
+
coords=' '.join('(%.5f,%.6f)'%(z['coverage']*100,z['delta']*100) for z in data[model]['coverage'])
|
| 51 |
+
lines.append(r'\addplot[teal,line width=.8pt,mark=*] coordinates {'+coords+'};')
|
| 52 |
+
for z,label in zip(data[model]['coverage'],['R$_s$','R','S','L']):
|
| 53 |
+
v=z['delta']*100;lo,hi=[v*100 for v in z['ci']];xx=z['coverage']*100
|
| 54 |
+
lines.append(r'\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(%.6f,%.6f) += (0,%.6f) -= (0,%.6f)};'%(xx,v,hi-v,v-lo))
|
| 55 |
+
anchor='north east' if label.startswith('R$_s') else 'south west'
|
| 56 |
+
shift=-.004 if label.startswith('R$_s') else .003
|
| 57 |
+
lines.append(r'\node[anchor=%s,font=\scriptsize] at (axis cs:%.5f,%.6f) {%s};'%(anchor,xx+.02,v+shift,label))
|
| 58 |
+
lines.append(r'\end{axis}')
|
| 59 |
+
lines.append(r'\end{tikzpicture}');write('Fig6_natural_effects','\n'.join(lines))
|
| 60 |
+
def sensitivity(data):
|
| 61 |
+
names=['primary','anchor_margin_0.02','anchor_margin_0.1','target_margin_0.02','target_margin_0.1','geometry_0.01','geometry_0.05','size_factor_0.5','size_factor_2.0','threshold_offset_-0.05','threshold_offset_0.05']
|
| 62 |
+
labels=[r'Primary',r'$\delta_a=.02$',r'$\delta_a=.10$',r'$\delta_t=.02$',r'$\delta_t=.10$',r'$\epsilon_g=.01$',r'$\epsilon_g=.05$',r'$a_{\min}\times.5$',r'$a_{\min}\times2$',r'$t_0-.05$',r'$t_0+.05$']
|
| 63 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]']
|
| 64 |
+
for j,(model,title) in enumerate([('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')]):
|
| 65 |
+
dx=j*82;lines.append(r'\node[anchor=west,font=\bfseries\small] at (%s,76) {%s};'%(dx,title))
|
| 66 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=50mm,height=65mm,xmin=0,xmax=.18,ymin=-.7,ymax=10.7,ytick=\empty,xlabel={$\Delta$gIoU (pp)},axis lines=left,xtick={0,.05,.1,.15}]'%(dx+26))
|
| 67 |
+
table={r['config']:r for r in data[model]['sensitivity']}
|
| 68 |
+
for i,(key,label) in enumerate(zip(names,labels)):
|
| 69 |
+
z=table[key];y=10-i;v=z['delta']*100;lo,hi=[k*100 for k in z['ci']];col='black' if i==0 else 'teal'
|
| 70 |
+
lines.append(r'\node[anchor=east,font=\scriptsize] at (axis cs:-.005,%s) {%s};'%(y,label))
|
| 71 |
+
lines.append(r'\addplot[%s,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(%.6f,%s) += (%.6f,0) -= (%.6f,0)};'%(col,v,y,hi-v,v-lo))
|
| 72 |
+
lines.append(r'\end{axis}')
|
| 73 |
+
lines.append(r'\end{tikzpicture}');write('Fig9_threshold_robustness','\n'.join(lines))
|
| 74 |
+
def harm(data):
|
| 75 |
+
keys=['harmed','plural_union','already_correct','correct_to_incorrect','boundary_sensitive','component_filter_sensitive']
|
| 76 |
+
labels=['Any IoU loss','Plural union','Initially correct','Crossed below .5','Geometry sensitive','Size-filter sensitive']
|
| 77 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]']
|
| 78 |
+
for j,(model,title) in enumerate([('clipseg','CLIPSeg'),('groundedsam','Grounded SAM')]):
|
| 79 |
+
dx=j*82;lines.append(r'\node[anchor=west,font=\bfseries\small] at (%s,61) {%s};'%(dx,title))
|
| 80 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=42mm,height=51mm,xmin=0,xmax=600,ymin=-.6,ymax=5.7,ytick=\empty,xlabel={Expressions},axis lines=left,xtick={0,200,400,600}]'%(dx+38))
|
| 81 |
+
for i,(key,label) in enumerate(zip(keys,labels)):
|
| 82 |
+
y=5-i;n=data[model]['harm']['reason_counts']['plural'] if key=='plural_union' else data[model]['harm'][key]
|
| 83 |
+
lines.append(r'\node[anchor=east,font=\scriptsize] at (axis cs:-12,%s) {%s};'%(y,label))
|
| 84 |
+
lines.append(r'\addplot[black!60,line width=.5pt] coordinates {(0,%s)(%s,%s)};'%(y,n,y))
|
| 85 |
+
lines.append(r'\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(%s,%s)};'%(n,y))
|
| 86 |
+
lines.append(r'\node[anchor=south west,font=\scriptsize] at (axis cs:%s,%s) {%s};'%(n,y,n))
|
| 87 |
+
lines.append(r'\end{axis}')
|
| 88 |
+
lines.append(r'\end{tikzpicture}');write('Fig10_harm_signatures','\n'.join(lines))
|
| 89 |
+
def rich_primary():
|
| 90 |
+
lines=[r'\begin{tikzpicture}[x=1mm,y=1mm]']
|
| 91 |
+
for j,(title,rows) in enumerate([('Flat',[('Grounded SAM',.0833,8.0),('CLIPSeg',4.5208,17.4792)]),('Rich',[('Grounded SAM',.5,17.3333),('CLIPSeg',3.2708,9.0)])]):
|
| 92 |
+
dx=j*82;lines.append(r'\node[anchor=west,font=\bfseries\small] at (%s,44) {%s};'%(dx,title))
|
| 93 |
+
lines.append(r'\begin{axis}[journal,at={(%s mm,0mm)},anchor=south west,width=65mm,height=32mm,xmin=0,xmax=21,ymin=-.5,ymax=1.6,ytick=\empty,xlabel={PC$_{.5}$ (\%%)},axis lines=left,xtick={0,5,10,15,20}]'%(dx+10))
|
| 94 |
+
for y,(model,frozen,repaired) in enumerate(rows):
|
| 95 |
+
lines.append(r'\addplot[black!55,line width=.6pt] coordinates {(%.4f,%s)(%.4f,%s)};'%(frozen,y,repaired,y))
|
| 96 |
+
lines.append(r'\addplot[black,only marks,mark=o,mark size=2.3pt] coordinates {(%.4f,%s)};'%(frozen,y))
|
| 97 |
+
lines.append(r'\addplot[black,only marks,mark=*,mark size=2.3pt] coordinates {(%.4f,%s)};'%(repaired,y))
|
| 98 |
+
lines.append(r'\node[anchor=south east,font=\scriptsize] at (axis cs:20.8,%s) {%s};'%(y+.12,model))
|
| 99 |
+
lines.append(r'\end{axis}')
|
| 100 |
+
lines.append(r'\end{tikzpicture}');write('Fig8_rich_performance','\n'.join(lines))
|
| 101 |
+
def monochrome_legend():
|
| 102 |
+
p=F/'Fig5_thresholds.tex';s=p.read_text()
|
| 103 |
+
start=s.index(r'\node[anchor=west,font=\sffamily\fontsize{7.8}{9}\selectfont] at (0,-17)')
|
| 104 |
+
stop=s.index(';',start)+1
|
| 105 |
+
parts=[]
|
| 106 |
+
for x,label,style in [(0,'Frozen','dashed'),(32,'Global','densely dotted'),(64,'Anchor PC','solid'),(100,'CACP','dashdotted'),(130,'Anchor Pr','dashed')]:
|
| 107 |
+
parts.append(r'\draw[black,%s,line width=.75pt] (%s,-17)--(%s,-17);\node[anchor=west,font=\scriptsize] at (%s,-17) {%s};'%(style,x,x+5,x+6,label))
|
| 108 |
+
if label=='Anchor Pr':parts.append(r'\draw[fill=white] (132,-17.6) rectangle (133.2,-16.4);')
|
| 109 |
+
s=s[:start]+'\n'.join(parts)+s[stop:]
|
| 110 |
+
s=s.replace('ymax=65','ymax=80').replace('teal,dashed,opacity=.5,line width=.8pt','teal,dashed,line width=.7pt,mark=square,mark size=1.5pt,mark options={fill=white}')
|
| 111 |
+
p.write_text(s)
|
| 112 |
+
def main():
|
| 113 |
+
(F/'assets').mkdir(parents=True,exist_ok=True)
|
| 114 |
+
old.atlas();old.paired_render();old.multiplicity();old.thresholds();old.absence_tradeoff();old.rich_performance()
|
| 115 |
+
framework();rich_primary();monochrome_legend()
|
| 116 |
+
datafile=ROOT/'results/r3/review_results.json'
|
| 117 |
+
if datafile.exists():
|
| 118 |
+
data=json.loads(datafile.read_text());coverage(data);sensitivity(data);harm(data)
|
| 119 |
+
for p in F.glob('Fig*.tex'):
|
| 120 |
+
s=p.read_text().replace(r'\sffamily',r'\rmfamily')
|
| 121 |
+
s=s.replace(r'\node[anchor=west,font=\rmfamily\bfseries\fontsize{10}{12}\selectfont] at (0,5) {A richer test of the same five command regimes};','')
|
| 122 |
+
p.write_text(s)
|
| 123 |
+
if __name__=='__main__':main()
|
source/code/generate_rich.py
ADDED
|
@@ -0,0 +1,141 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Procedural, paired-render RefSeg-CA scenes with exact visible-instance GT.
|
| 2 |
+
|
| 3 |
+
These are benchmark inputs, not generated illustrations or TikZ drawings.
|
| 4 |
+
Geometry, visibility and query targets are shared between flat/rich images.
|
| 5 |
+
"""
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import argparse,json,math,hashlib,collections
|
| 8 |
+
import numpy as np
|
| 9 |
+
from PIL import Image,ImageDraw,ImageFilter
|
| 10 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 11 |
+
S=384;AA=2
|
| 12 |
+
COLORS={'red':(196,38,56),'blue':(38,87,176),'green':(33,139,91),'yellow':(232,188,35),'purple':(135,64,166),'orange':(223,111,38),'pink':(216,99,150),'brown':(127,83,53),'cyan':(27,160,186),'olive':(117,129,45)}
|
| 13 |
+
SHAPES=['circle','square','triangle','star','cross','ellipse','capsule','heart','diamond','ring','hexagon']
|
| 14 |
+
PLURAL={'ellipse':'ellipses','cross':'crosses','hexagon':'hexagons'}
|
| 15 |
+
def plural(x):return PLURAL.get(x,x+'s')
|
| 16 |
+
|
| 17 |
+
def object_mask(shape,size,angle):
|
| 18 |
+
n=128*AA;m=Image.new('L',(n,n));d=ImageDraw.Draw(m);c=n/2
|
| 19 |
+
x0,y0,x1,y1=[v*AA for v in (28,28,100,100)]
|
| 20 |
+
if shape=='circle':d.ellipse((x0,y0,x1,y1),fill=255)
|
| 21 |
+
elif shape=='ellipse':d.ellipse((20*AA,37*AA,108*AA,91*AA),fill=255)
|
| 22 |
+
elif shape=='square':d.rectangle((x0,y0,x1,y1),fill=255)
|
| 23 |
+
elif shape=='capsule':d.rounded_rectangle((19*AA,40*AA,109*AA,88*AA),radius=24*AA,fill=255)
|
| 24 |
+
elif shape=='ring':
|
| 25 |
+
d.ellipse((x0,y0,x1,y1),fill=255);d.ellipse((45*AA,45*AA,83*AA,83*AA),fill=0)
|
| 26 |
+
elif shape=='cross':
|
| 27 |
+
d.rectangle((49*AA,24*AA,79*AA,104*AA),fill=255);d.rectangle((24*AA,49*AA,104*AA,79*AA),fill=255)
|
| 28 |
+
elif shape=='heart':
|
| 29 |
+
pts=[]
|
| 30 |
+
for t in np.linspace(0,2*math.pi,200):
|
| 31 |
+
x=16*math.sin(t)**3;y=13*math.cos(t)-5*math.cos(2*t)-2*math.cos(3*t)-math.cos(4*t)
|
| 32 |
+
pts.append((c+x*2.4*AA,c-y*2.4*AA))
|
| 33 |
+
d.polygon(pts,fill=255)
|
| 34 |
+
else:
|
| 35 |
+
count={'triangle':3,'star':10,'diamond':4,'hexagon':6}[shape]
|
| 36 |
+
pts=[]
|
| 37 |
+
for j in range(count):
|
| 38 |
+
theta=-math.pi/2+j*2*math.pi/count;r=(43 if shape!='star' or j%2==0 else 20)*AA
|
| 39 |
+
pts.append((c+r*math.cos(theta),c+r*math.sin(theta)))
|
| 40 |
+
d.polygon(pts,fill=255)
|
| 41 |
+
m=m.rotate(angle,resample=Image.Resampling.BICUBIC)
|
| 42 |
+
bbox=m.getbbox();m=m.crop(bbox);width,height=size
|
| 43 |
+
return m.resize((int(width*AA),int(height*AA)),Image.Resampling.LANCZOS)
|
| 44 |
+
|
| 45 |
+
def make_scene(seed,index):
|
| 46 |
+
rng=np.random.default_rng(seed*100000+index)
|
| 47 |
+
for attempt in range(100):
|
| 48 |
+
shape=SHAPES[(index+seed)%len(SHAPES)];color=str(rng.choice(list(COLORS)));other=str(rng.choice([c for c in COLORS if c!=color]))
|
| 49 |
+
ashape=str(rng.choice([s for s in SHAPES if s!=shape]));acolor=str(rng.choice([c for c in COLORS if c not in (color,other)]))
|
| 50 |
+
identities=[(color,shape)]*3+[(other,shape),(acolor,ashape)]
|
| 51 |
+
count=int(rng.integers(9,14))
|
| 52 |
+
while len(identities)<count:
|
| 53 |
+
c=str(rng.choice(list(COLORS)));s=str(rng.choice(SHAPES))
|
| 54 |
+
if (c,s) not in ((color,shape),(other,shape),(acolor,ashape)):identities.append((c,s))
|
| 55 |
+
specs=[];masks=[];ok=True
|
| 56 |
+
for j,(c,s) in enumerate(identities):
|
| 57 |
+
width=int(rng.integers(46,77));height=int(width*rng.uniform(.85,1.18));angle=float(rng.uniform(-165,165))
|
| 58 |
+
mask=object_mask(s,(width,height),angle)
|
| 59 |
+
for trial in range(150):
|
| 60 |
+
x=int(rng.integers(15,S-width-15));y=int(rng.integers(15,S-height-15))
|
| 61 |
+
canvas=Image.new('L',(S*AA,S*AA));canvas.paste(mask,(x*AA,y*AA))
|
| 62 |
+
b=np.asarray(canvas.resize((S,S),Image.Resampling.LANCZOS))>=128
|
| 63 |
+
if all(np.logical_and(b,p).sum()<.22*min(b.sum(),p.sum()) for p in masks):break
|
| 64 |
+
else:ok=False;break
|
| 65 |
+
masks.append(b);specs.append(dict(id=j+1,color=c,shape=s,x=x,y=y,width=width,height=height,angle=angle,texture=str(rng.choice(['solid','stripes','dots','grid','checker','satin'])),texture_phase=int(rng.integers(0,12))))
|
| 66 |
+
if not ok:continue
|
| 67 |
+
owner=np.zeros((S,S),np.uint8)
|
| 68 |
+
for j,b in enumerate(masks):owner[b]=j+1
|
| 69 |
+
fractions=[(owner==j+1).sum()/b.sum() for j,b in enumerate(masks)]
|
| 70 |
+
if min(fractions)<.7:continue
|
| 71 |
+
centroids=[]
|
| 72 |
+
for j in range(count):
|
| 73 |
+
yy,xx=np.nonzero(owner==j+1);centroids.append((float(xx.mean()/S),float(yy.mean()/S)))
|
| 74 |
+
axes=[]
|
| 75 |
+
for ax in [0,1]:
|
| 76 |
+
ds=[centroids[j][ax]-centroids[4][ax] for j in range(3)]
|
| 77 |
+
if min(ds)<-.09 and max(ds)>.09 and min(abs(v) for v in ds)>.045:axes.append(ax)
|
| 78 |
+
if not axes:continue
|
| 79 |
+
axis=axes[index%len(axes)];first,second=('left','right') if axis==0 else ('above','below')
|
| 80 |
+
left=[j+1 for j in range(3) if centroids[j][axis]<centroids[4][axis]];right=[j+1 for j in range(3) if centroids[j][axis]>centroids[4][axis]]
|
| 81 |
+
target=f'{color} {plural(shape)}';atarget=f'{other} {plural(shape)}';anchor=f'{acolor} {ashape}'
|
| 82 |
+
relation=lambda rel:f'segment all {target} '+(f'{rel} of the {anchor}' if axis==0 else f'{rel} the {anchor}')
|
| 83 |
+
missing=next(c for c in COLORS if all((o['color'],o['shape'])!=(c,shape) for o in specs))
|
| 84 |
+
extreme=min(range(3),key=lambda j:centroids[j][0])+1
|
| 85 |
+
pair_specs=[('attribute',[f'segment all {target}',f'segment all {atarget}'],[[1,2,3],[4]]),('relational',[relation(first),relation(second)],[left,right]),('multi_target',[f'segment the leftmost {color} {shape}',f'segment all {target}'],[[extreme],[1,2,3]]),('negative_action',[f'segment all {target}',f'do not segment all {target}'],[[1,2,3],[]]),('empty_target',[f'segment all {target}',f'segment all {missing} {plural(shape)}'],[[1,2,3],[]]),('paraphrase',[f'segment all {target}',f'show every {color} {shape}'],[[1,2,3],[1,2,3]])]
|
| 86 |
+
meta=dict(seed=seed,index=index,objects=specs,visible_fraction=fractions,centroids=centroids,occupancy=float((owner>0).mean()),relation_axis=axis,pairs=pair_specs)
|
| 87 |
+
return meta,owner
|
| 88 |
+
raise RuntimeError((seed,index,'placement_failed'))
|
| 89 |
+
|
| 90 |
+
def render(meta,rich):
|
| 91 |
+
rng=np.random.default_rng(meta['seed']*100000+meta['index']+923471)
|
| 92 |
+
n=S*AA;yy,xx=np.mgrid[:n,:n];base=np.array([(251,249,244),(245,249,248),(249,245,250),(246,248,253)][meta['index']%4],float)
|
| 93 |
+
if rich:
|
| 94 |
+
noise=rng.normal(0,1.15,(n,n));shade=(xx/n-.5)*1.3+(yy/n-.5)*1.8
|
| 95 |
+
arr=np.clip(base[None,None,:]+(noise+shade)[...,None],0,255).astype('uint8')
|
| 96 |
+
else:arr=np.broadcast_to(base.astype('uint8'),(n,n,3)).copy()
|
| 97 |
+
image=Image.fromarray(arr).convert('RGBA')
|
| 98 |
+
if rich and meta['index']%3==0:
|
| 99 |
+
d=ImageDraw.Draw(image)
|
| 100 |
+
for x in range(0,n,20*AA):d.line((x,0,x,n),fill=(192,202,202,20),width=1)
|
| 101 |
+
for y in range(0,n,20*AA):d.line((0,y,n,y),fill=(192,202,202,20),width=1)
|
| 102 |
+
for o in meta['objects']:
|
| 103 |
+
mask=object_mask(o['shape'],(o['width'],o['height']),o['angle']);w,h=mask.size
|
| 104 |
+
if rich:
|
| 105 |
+
shadow=Image.new('RGBA',(n,n));sm=Image.new('L',(n,n));sm.paste(mask,(o['x']*AA+3*AA,o['y']*AA+4*AA));sm=sm.filter(ImageFilter.GaussianBlur(2.2*AA)).point(lambda p:int(p*.24));shadow.putalpha(sm);image=Image.alpha_composite(image,shadow)
|
| 106 |
+
y,x=np.mgrid[:h,:w];rgb=np.array(COLORS[o['color']],float);factor=np.zeros((h,w))
|
| 107 |
+
if rich:
|
| 108 |
+
phase=o['texture_phase']*AA;pattern=o['texture']
|
| 109 |
+
if pattern=='stripes':factor=np.where((x+y+phase)%(12*AA)<3*AA,.28,-.015)
|
| 110 |
+
elif pattern=='dots':factor=np.where(((x+phase)%(15*AA)-7*AA)**2+((y+phase)%(15*AA)-7*AA)**2<(2.4*AA)**2,.42,0.)
|
| 111 |
+
elif pattern=='grid':factor=np.where(((x+phase)%(13*AA)<2*AA)|((y+phase)%(13*AA)<2*AA),-.20,.06)
|
| 112 |
+
elif pattern=='checker':factor=np.where(((x//(11*AA)+y//(11*AA))%2)==0,.20,-.13)
|
| 113 |
+
elif pattern=='satin':factor=.22*np.cos((x+y)/(11*AA))
|
| 114 |
+
factor+=.08*(1-y/max(h,1))-.025+rng.normal(0,.012,(h,w))
|
| 115 |
+
pixels=np.where(factor[...,None]>=0,rgb+(255-rgb)*factor[...,None],rgb*(1+factor[...,None]))
|
| 116 |
+
tile=Image.fromarray(np.clip(pixels,0,255).astype('uint8')).convert('RGBA')
|
| 117 |
+
# A thin inset contour increases legibility without becoming GT area.
|
| 118 |
+
inner=mask.filter(ImageFilter.MinFilter(3));edge=(np.asarray(mask,dtype=float)-np.asarray(inner,dtype=float))/255
|
| 119 |
+
a=np.asarray(tile).copy();a[...,:3]=(a[...,:3]*(1-.22*edge[...,None])).astype('uint8');tile=Image.fromarray(a);tile.putalpha(mask)
|
| 120 |
+
image.alpha_composite(tile,(o['x']*AA,o['y']*AA))
|
| 121 |
+
return image.convert('RGB').resize((S,S),Image.Resampling.LANCZOS)
|
| 122 |
+
|
| 123 |
+
def main():
|
| 124 |
+
ap=argparse.ArgumentParser();ap.add_argument('--per-seed',type=int,default=240);ap.add_argument('--seeds',type=int,nargs='+',default=[11,23,37,53,71]);a=ap.parse_args()
|
| 125 |
+
dest=ROOT/'data/rich';dest.mkdir(parents=True,exist_ok=True);rows=[];scenes=[]
|
| 126 |
+
for seed in a.seeds:
|
| 127 |
+
for index in range(a.per_seed):
|
| 128 |
+
meta,owner=make_scene(seed,index);sid=f'r{seed}_{index:04d}';meta['scene_id']=sid;scenes.append(meta)
|
| 129 |
+
sd=dest/sid;sd.mkdir(exist_ok=True);Image.fromarray(owner).save(sd/'instances.png')
|
| 130 |
+
for style in ['flat','rich']:
|
| 131 |
+
ip=sd/f'{style}.png';render(meta,style=='rich').save(ip)
|
| 132 |
+
for family,queries,targets in meta['pairs']:
|
| 133 |
+
for endpoint,(query,ids) in enumerate(zip(queries,targets)):
|
| 134 |
+
gp=sd/f'{family}_{endpoint}.png';gt=np.isin(owner,ids)
|
| 135 |
+
if not gp.exists():Image.fromarray(gt.astype('uint8')*255).save(gp)
|
| 136 |
+
rows.append(dict(id=f'{sid}_{style}_{family}_{endpoint}',scene_id=sid,domain='rich_synthetic',split='test',mode=family,pair_id=f'{sid}_{style}_{family}',endpoint=endpoint,target_count=len(ids),query=query,image_path=str(ip.relative_to(ROOT)),gt_path=str(gp.relative_to(ROOT)),seed=seed,corruption=style,template='scene_graph',render=style,object_count=len(meta['objects']),occupancy=meta['occupancy'],target_instance_ids=ids))
|
| 137 |
+
if index%40==0:print('SCENE',sid,'records',len(rows),flush=True)
|
| 138 |
+
p=ROOT/'data/rich_synthetic.jsonl';p.write_text(''.join(json.dumps(r)+'\n' for r in rows));(ROOT/'data/rich_scenes.jsonl').write_text(''.join(json.dumps(r)+'\n' for r in scenes))
|
| 139 |
+
meta=dict(scenes=len(scenes),images=2*len(scenes),records=len(rows),args=vars(a),manifest_sha256=hashlib.sha256(p.read_bytes()).hexdigest(),mean_objects=float(np.mean([len(s['objects']) for s in scenes])),min_visible_fraction=min(min(s['visible_fraction']) for s in scenes),mean_occupancy=float(np.mean([s['occupancy'] for s in scenes])),renderer='Pillow procedural raster; no image generation model; common instance masks across render styles')
|
| 140 |
+
(ROOT/'protocol/rich_manifest.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True)
|
| 141 |
+
if __name__=='__main__':main()
|
source/code/infer_r2.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image-grouped R2 inference, label-isolated inference and official metrics."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse, json, time, os, hashlib, collections, sys, platform
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
+
from project_paths import legacy_root;OLD=legacy_root(ROOT)
|
| 8 |
+
sys.path.insert(0,str(OLD/'code'))
|
| 9 |
+
from infer import ClipSeg,GroundedSam
|
| 10 |
+
import phase1_repair as p1
|
| 11 |
+
from r2_repair import repair,primary_plan
|
| 12 |
+
|
| 13 |
+
def official_score(pred,gt,pred_nt,gt_nt=None):
|
| 14 |
+
z=p1.score_mask(pred,gt);is_nt=not gt.any() if gt_nt is None else gt_nt
|
| 15 |
+
if is_nt:
|
| 16 |
+
z['iou']=float(pred_nt);z['intersection']=0
|
| 17 |
+
if pred_nt:z['union']=0
|
| 18 |
+
elif pred_nt or z['union']==0:z['intersection']=0;z['iou']=0.
|
| 19 |
+
z['pred_nt']=bool(pred_nt)
|
| 20 |
+
return z
|
| 21 |
+
|
| 22 |
+
def main():
|
| 23 |
+
ap=argparse.ArgumentParser();ap.add_argument('--model',required=True,choices=['clipseg','groundedsam','rela']);ap.add_argument('--manifest',default='natural_full');ap.add_argument('--shard',type=int,default=0);ap.add_argument('--shards',type=int,default=1);ap.add_argument('--limit',type=int,default=0);ap.add_argument('--frozen-only',action='store_true');ap.add_argument('--device',choices=['cpu','cuda'],default='cuda');a=ap.parse_args()
|
| 24 |
+
import torch
|
| 25 |
+
torch.set_num_threads(4);torch.manual_seed(20260906);np.random.seed(20260906)
|
| 26 |
+
def sync():
|
| 27 |
+
if a.device=='cuda':torch.cuda.synchronize()
|
| 28 |
+
device_name=torch.cuda.get_device_name(0) if a.device=='cuda' else platform.processor()+' CPU; 4 torch threads'
|
| 29 |
+
rows=[json.loads(s) for s in (ROOT/'data'/f'{a.manifest}.jsonl').read_text().splitlines()]
|
| 30 |
+
groups=collections.defaultdict(list)
|
| 31 |
+
for r in rows:groups[r['image_path']].append(r)
|
| 32 |
+
paths=sorted(groups)[a.shard::a.shards]
|
| 33 |
+
if a.limit:paths=paths[:a.limit]
|
| 34 |
+
if a.model=='rela':
|
| 35 |
+
from rela_engine import ReLA
|
| 36 |
+
engine=ReLA(device=a.device)
|
| 37 |
+
else:engine=ClipSeg() if a.model=='clipseg' else GroundedSam()
|
| 38 |
+
name=f'{a.manifest}_{a.model}_{a.shard}of{a.shards}'+('_pilot' if a.limit else '')
|
| 39 |
+
cache=ROOT/'cache'/a.model;cache.mkdir(parents=True,exist_ok=True)
|
| 40 |
+
result=ROOT/'results'/f'{name}.jsonl';tf=ROOT/'results'/f'{name}_timings.jsonl'
|
| 41 |
+
done=set()
|
| 42 |
+
if result.exists():
|
| 43 |
+
lines=result.read_text().splitlines()
|
| 44 |
+
parsed=[]
|
| 45 |
+
for line in lines:
|
| 46 |
+
try:parsed.append(json.loads(line))
|
| 47 |
+
except json.JSONDecodeError:break
|
| 48 |
+
result.write_text(''.join(json.dumps(x)+'\n' for x in parsed));done={r['id'] for r in parsed}
|
| 49 |
+
tstart=time.time();processed=0;inference_s=0;newq=0
|
| 50 |
+
print('READY',name,'images',len(paths),'device',device_name,flush=True)
|
| 51 |
+
with result.open('a') as out,tf.open('a') as timing:
|
| 52 |
+
for ix,path in enumerate(paths):
|
| 53 |
+
group=[r for r in groups[path] if r['id'] not in done]
|
| 54 |
+
if not group:continue
|
| 55 |
+
image=Image.open(ROOT/path).convert('RGB');texts=[]
|
| 56 |
+
for r in group:
|
| 57 |
+
q,plan=p1.query_plan(r['query']);texts.extend([r['query'] if a.model=='rela' else q.original] if a.frozen_only else plan)
|
| 58 |
+
texts=list(dict.fromkeys(texts));allmaps={};allnt={};allofficial={};elapsed=0.;queried=0
|
| 59 |
+
for start in range(0,len(texts),12):
|
| 60 |
+
batch=texts[start:start+12]
|
| 61 |
+
digest=hashlib.sha256((path+'\n'+'\n'.join(batch)).encode()).hexdigest()[:24];cp=cache/(digest+'.npz')
|
| 62 |
+
if cp.exists():
|
| 63 |
+
z=np.load(cp);assert z['texts'].tolist()==batch
|
| 64 |
+
maps={q:z[f'p{i}'].astype(np.float32) for i,q in enumerate(batch)}
|
| 65 |
+
nt={q:bool(z['nt'][i]) for i,q in enumerate(batch)} if 'nt' in z else {}
|
| 66 |
+
native_masks={q:z[f'o{i}'].astype(bool) for i,q in enumerate(batch)} if 'o0' in z else {}
|
| 67 |
+
else:
|
| 68 |
+
sync();t0=time.perf_counter();maps,stats=engine.predict(image,batch);sync();seconds=time.perf_counter()-t0
|
| 69 |
+
elapsed+=seconds;queried+=len(batch)
|
| 70 |
+
maps={q:maps[q].astype(np.float16).astype(np.float32) for q in batch};nt=stats.get('nt',{})
|
| 71 |
+
native_masks=stats.get('official_masks',{})
|
| 72 |
+
assert all(np.isfinite(v).all() and 0<=v.min()<=v.max()<=1 for v in maps.values())
|
| 73 |
+
arrays={f'p{i}':maps[q].astype(np.float16) for i,q in enumerate(batch)}
|
| 74 |
+
if nt:arrays['nt']=np.array([nt[q] for q in batch])
|
| 75 |
+
if native_masks:arrays.update({f'o{i}':native_masks[q] for i,q in enumerate(batch)})
|
| 76 |
+
tmp=cp.with_suffix('.partial.npz');np.savez_compressed(tmp,texts=np.array(batch),**arrays);tmp.replace(cp)
|
| 77 |
+
allmaps.update(maps);allnt.update(nt);allofficial.update(native_masks)
|
| 78 |
+
inference_s+=elapsed;newq+=queried
|
| 79 |
+
gt_cache={}
|
| 80 |
+
for r in group:
|
| 81 |
+
# Labels are opened only after all image/text predictions above.
|
| 82 |
+
if r['gt_path'] not in gt_cache:gt_cache[r['gt_path']]=np.asarray(Image.open(ROOT/r['gt_path']))>0
|
| 83 |
+
gt=gt_cache[r['gt_path']];q=p1.parse_query(r['query']);original_key=r['query'] if a.model=='rela' and a.frozen_only else q.original
|
| 84 |
+
if a.frozen_only:
|
| 85 |
+
raw=allmaps[original_key]>=engine.threshold
|
| 86 |
+
preds={'frozen':raw};flags={}
|
| 87 |
+
else:preds,flags=repair(r['query'],allmaps,engine.threshold)
|
| 88 |
+
if a.model=='rela':
|
| 89 |
+
# Preserve the trained no-target head. Native raw mask has
|
| 90 |
+
# no connected-component filtering in the official model.
|
| 91 |
+
preds['frozen']=allmaps[original_key]>=.5
|
| 92 |
+
nt=allnt.get(original_key,not preds['frozen'].any())
|
| 93 |
+
scores={k:official_score(v,gt,nt if k=='frozen' else not v.any()) for k,v in preds.items()}
|
| 94 |
+
row={k:v for k,v in r.items() if k not in ('gt_path','image_path')}
|
| 95 |
+
row.update(model=a.model,flags=flags,scores=scores,query_count=len(p1.query_plan(r['query'])[1]),primary_query_count=len(primary_plan(r['query'])),features=p1.visual_features(allmaps[original_key],preds.get('safe_anchor',preds['frozen']),engine.threshold))
|
| 96 |
+
if a.frozen_only:row.update(query_count=1,primary_query_count=1)
|
| 97 |
+
if r['domain']=='natural_full':
|
| 98 |
+
key=f"official_{r['ref_id']}"
|
| 99 |
+
if key not in gt_cache:gt_cache[key]=np.asarray(Image.open(ROOT/'data/natural/masks_official480'/f"ref_{r['ref_id']}.png"))>0
|
| 100 |
+
ogt=gt_cache[key];oscores={}
|
| 101 |
+
for variant,pred in preds.items():
|
| 102 |
+
opred=allofficial[original_key] if a.model=='rela' and variant=='frozen' else np.asarray(Image.fromarray(pred).resize((480,480),Image.Resampling.NEAREST))
|
| 103 |
+
oscores[variant]=official_score(opred,ogt,nt if variant=='frozen' else not pred.any(),r['target_count']==0)
|
| 104 |
+
row['official480_scores']=oscores
|
| 105 |
+
if a.model=='rela':row['native_nt']=nt
|
| 106 |
+
out.write(json.dumps(row)+'\n');processed+=1
|
| 107 |
+
out.flush();timing.write(json.dumps(dict(image_path=path,records=len(group),unique_queries=len(texts),queries_executed=queried,forward_seconds=elapsed))+'\n');timing.flush()
|
| 108 |
+
if ix%10==0:print(json.dumps(dict(image=ix+1,of=len(paths),records=processed,forward_seconds=inference_s,wall=time.time()-tstart)),flush=True)
|
| 109 |
+
meta=dict(status='COMPLETE',model=a.model,manifest=a.manifest,records_total=len({json.loads(s)['id'] for s in result.read_text().splitlines()}),records_this_run=processed,images=len(paths),new_queries=newq,forward_seconds=inference_s,wall_seconds=time.time()-tstart,gpu=device_name,torch=torch.__version__,python=platform.python_version(),slurm_job_id=os.getenv('SLURM_JOB_ID'),args=vars(a),manifest_sha256=hashlib.sha256((ROOT/'data'/f'{a.manifest}.jsonl').read_bytes()).hexdigest(),code_sha256={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in (ROOT/'code').glob('*.py')})
|
| 110 |
+
(ROOT/'results'/f'{name}_meta.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True)
|
| 111 |
+
if __name__=='__main__':main()
|
source/code/package_public_source.py
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Stage a source repository without credentials, upstream data, or vendored TeX."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib,json,shutil,zipfile
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 5 |
+
DEST=ROOT.parent/'publish/RefSeg-CA'
|
| 6 |
+
README='''# RefSeg-CA — R3 research release
|
| 7 |
+
|
| 8 |
+
Evaluating and repairing command compliance in generalized referring segmentation.
|
| 9 |
+
|
| 10 |
+
The release contains the SFAP parser/projection, benchmark generator, inference/evaluation scripts, exact-score replay, Slurm examples, editable TikZ/PGFPlots sources, and a current manuscript. Human validation has **not been conducted**. No acceptance or publication claim is made.
|
| 11 |
+
|
| 12 |
+
## Data and exact metric replay
|
| 13 |
+
|
| 14 |
+
Data repository: https://huggingface.co/datasets/Ethosoft/RefSeg-CA
|
| 15 |
+
|
| 16 |
+
From this directory, with Python 3.9 or newer:
|
| 17 |
+
|
| 18 |
+
```bash
|
| 19 |
+
python code/download_release_data.py
|
| 20 |
+
python code/verify_portable_results.py
|
| 21 |
+
```
|
| 22 |
+
|
| 23 |
+
The lightweight download reconstructs 30 primary table rows and 22 reviewer-requested threshold configurations. It requires no TRUBA connection or model weights. These are derived scores; reproducing inference pixels requires upstream models and inputs.
|
| 24 |
+
|
| 25 |
+
To obtain all 1,200 procedural scenes, both rendering styles, visible-instance maps, and command masks:
|
| 26 |
+
|
| 27 |
+
```bash
|
| 28 |
+
python code/download_release_data.py --synthetic
|
| 29 |
+
```
|
| 30 |
+
|
| 31 |
+
The default data revision is the immutable release tag `r3-data-v1`. Natural images and original gRefCOCO expression text must be obtained from the pinned upstream release; model checkpoint hashes and preparation scripts are under protocol/ and legacy_project/code/.
|
| 32 |
+
|
| 33 |
+
## Manuscript and figures
|
| 34 |
+
|
| 35 |
+
The current PDF is distributed alongside this source archive in the data repository under `release/RefSeg_CA_MVA.pdf`. Install the official Springer Nature LaTeX template and normal TeX Live packages, placing sn-jnl.cls and sn-mathphys-num.bst alongside the manuscript as instructed by Springer. The repository does not redistribute these third-party generated files.
|
| 36 |
+
|
| 37 |
+
```bash
|
| 38 |
+
python code/figures_r3.py
|
| 39 |
+
python code/build_latex.py
|
| 40 |
+
```
|
| 41 |
+
|
| 42 |
+
The synthetic download is required before regenerating image panels. All written figures are monochrome vector graphics; the experimental raster inputs retain their colors.
|
| 43 |
+
|
| 44 |
+
## Human evaluation
|
| 45 |
+
|
| 46 |
+
Read review/HUMAN_VALIDATION_PROTOCOL.md and review/INSAN_DEGERLENDIRMESI_UYGULAMA_KILAVUZU.md. Two independent readers, pre-adjudication agreement, adjudicated semantic labels, and a separate image-aware harm audit are still needed. Automated checks are not human labels.
|
| 47 |
+
|
| 48 |
+
## Provenance and reuse
|
| 49 |
+
|
| 50 |
+
See REPRODUCIBILITY.md, THIRD_PARTY.md, CITATION.cff, and SHA256SUMS. This public deposit establishes accessibility. Authors have not yet selected an additional blanket reuse license for original material; existing per-file third-party terms continue to apply.
|
| 51 |
+
|
| 52 |
+
Browse all source files at https://huggingface.co/datasets/Ethosoft/RefSeg-CA/tree/main/source. This organization-owned Hugging Face source tree is the code host for this release.
|
| 53 |
+
'''
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def main():
|
| 57 |
+
DEST.mkdir(parents=True,exist_ok=True)
|
| 58 |
+
patterns=['code/*.py','legacy_project/code/*.py','legacy_project/protocol/*.json',
|
| 59 |
+
'legacy_project/results/analysis/*.json','protocol/*.json','protocol/*.md',
|
| 60 |
+
'results/analysis/*.json','results/r3/review_results.json','results/r3/jobs/*.json',
|
| 61 |
+
'figures/*.tex','figures/*.json','latex/*.tex','latex/*.bib','slurm/*.sbatch']
|
| 62 |
+
selected=set()
|
| 63 |
+
for pattern in patterns:selected.update(ROOT.glob(pattern))
|
| 64 |
+
for p in selected:
|
| 65 |
+
out=DEST/p.relative_to(ROOT);out.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(p,out)
|
| 66 |
+
for rel in ['CITATION.cff','REPRODUCIBILITY.md','requirements-analysis.txt',
|
| 67 |
+
'review/HUMAN_VALIDATION_PROTOCOL.md','review/INSAN_DEGERLENDIRMESI_UYGULAMA_KILAVUZU.md',
|
| 68 |
+
'review/Response_to_Major_Revision.md']:
|
| 69 |
+
out=DEST/rel;out.parent.mkdir(parents=True,exist_ok=True);shutil.copy2(ROOT/rel,out)
|
| 70 |
+
(DEST/'README.md').write_text(README)
|
| 71 |
+
(DEST/'THIRD_PARTY.md').write_text('''# Third-party materials
|
| 72 |
+
|
| 73 |
+
Original natural images and gRefCOCO expression files are not included. Obtain them from https://huggingface.co/datasets/FudanCVL/gRefCOCO at revision 81eede59b3ac070049f597d023c0ff08d1fb80e9 and the image sources referenced by its authors. They retain their original terms.
|
| 74 |
+
|
| 75 |
+
Model weights and ReLA source are downloaded from their authors using the revisions and hashes in protocol/. No model weights are redistributed here.
|
| 76 |
+
|
| 77 |
+
The Springer Nature LaTeX class/bibliography style and standard algorithm packages must be installed from their official distributions. These generated third-party files are omitted from this public source archive. The user-facing manuscript source remains included.
|
| 78 |
+
|
| 79 |
+
This repository adds no blanket license to material owned by others. The project authors have not yet assigned a blanket reuse license to their original code or procedural dataset.
|
| 80 |
+
''')
|
| 81 |
+
(DEST/'.gitignore').write_text('build/\ncache/\nassets/\nvendor/\n__pycache__/\n*.pyc\n.env*\n*.token\ndata/rich/\ndata/natural/\nresults/r3/portable/\n*.aux\n*.log\n*.out\n*.blg\n')
|
| 82 |
+
files=sorted(p for p in DEST.rglob('*') if p.is_file() and '.git' not in p.parts and p.name!='SHA256SUMS')
|
| 83 |
+
(DEST/'SHA256SUMS').write_text(''.join(hashlib.sha256(p.read_bytes()).hexdigest()+' '+p.relative_to(DEST).as_posix()+'\n' for p in files))
|
| 84 |
+
archive=ROOT.parent/'RefSeg_CA_R3_Public_Source.zip'
|
| 85 |
+
with zipfile.ZipFile(archive,'w',zipfile.ZIP_DEFLATED,compresslevel=6) as z:
|
| 86 |
+
for p in files+[DEST/'SHA256SUMS']:z.write(p,'RefSeg-CA/'+p.relative_to(DEST).as_posix())
|
| 87 |
+
print(json.dumps({'source_root':str(DEST),'archive':str(archive),'files':len(files)+1,'bytes':archive.stat().st_size,'sha256':hashlib.sha256(archive.read_bytes()).hexdigest()}))
|
| 88 |
+
if __name__=='__main__':main()
|
source/code/package_release.py
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Package the reviewed R3 manuscript, editable source, and exact evidence."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import hashlib
|
| 4 |
+
import json
|
| 5 |
+
import shutil
|
| 6 |
+
import zipfile
|
| 7 |
+
|
| 8 |
+
ROOT = Path(__file__).resolve().parents[1]
|
| 9 |
+
EXCLUDED_DIRS = {'build', '__pycache__', 'logs'}
|
| 10 |
+
EXCLUDED_SUFFIXES = {'.aux', '.log', '.blg', '.out', '.eps', '.pyc', '.synctex.gz'}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
def included(path):
|
| 14 |
+
rel = path.relative_to(ROOT)
|
| 15 |
+
return (path.is_file() and not any(part in EXCLUDED_DIRS for part in rel.parts)
|
| 16 |
+
and path.suffix not in EXCLUDED_SUFFIXES
|
| 17 |
+
and rel.as_posix() != 'latex/RefSeg_CA_MVA.pdf'
|
| 18 |
+
and rel.name != 'SHA256SUMS')
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def sha256(path):
|
| 22 |
+
return hashlib.sha256(path.read_bytes()).hexdigest()
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def main():
|
| 26 |
+
validation = json.loads((ROOT / 'results/r3/final_validation.json').read_text())
|
| 27 |
+
assert validation['metric_replay'] == 'PASS'
|
| 28 |
+
assert validation['overfull_boxes'] == validation['undefined_references'] == 0
|
| 29 |
+
shutil.copy2(ROOT / 'latex/RefSeg_CA_MVA.pdf', ROOT / 'RefSeg_CA_MVA.pdf')
|
| 30 |
+
shutil.copy2(ROOT / 'build/Fig1_framework_checked.png', ROOT / 'Preview_Fig1.png')
|
| 31 |
+
|
| 32 |
+
files = sorted(p for p in ROOT.rglob('*') if included(p))
|
| 33 |
+
sums = ROOT / 'SHA256SUMS'
|
| 34 |
+
sums.write_text(''.join(f'{sha256(p)} {p.relative_to(ROOT).as_posix()}\n' for p in files))
|
| 35 |
+
complete = ROOT.parent / 'RefSeg_CA_R3_Complete_Package.zip'
|
| 36 |
+
with zipfile.ZipFile(complete, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
| 37 |
+
for path in files + [sums]:
|
| 38 |
+
archive.write(path, 'RefSeg_CA_R3/' + path.relative_to(ROOT).as_posix())
|
| 39 |
+
|
| 40 |
+
kit = ROOT.parent / 'RefSeg_CA_R3_Human_Validation_Kit.zip'
|
| 41 |
+
with zipfile.ZipFile(kit, 'w', compression=zipfile.ZIP_DEFLATED, compresslevel=6) as archive:
|
| 42 |
+
for reader in ['A', 'B']:
|
| 43 |
+
archive.write(ROOT / f'review/human/parser_annotator_{reader}.csv',
|
| 44 |
+
f'annotator_{reader}/parser_annotator_{reader}.csv')
|
| 45 |
+
archive.write(ROOT / 'review/HUMAN_VALIDATION_PROTOCOL.md',
|
| 46 |
+
f'annotator_{reader}/HUMAN_VALIDATION_PROTOCOL.md')
|
| 47 |
+
for name in ['parser_sampling_key.json', 'annotator_metadata.json',
|
| 48 |
+
'clipseg_harm_annotation.csv', 'groundedsam_harm_annotation.csv']:
|
| 49 |
+
archive.write(ROOT / 'review/human' / name, 'coordinator/' + name)
|
| 50 |
+
archive.write(ROOT / 'code/score_human_parser_audit.py', 'coordinator/score_human_parser_audit.py')
|
| 51 |
+
archive.write(ROOT / 'code/prepare_human_passes.py', 'coordinator/prepare_human_passes.py')
|
| 52 |
+
archive.write(ROOT / 'review/HUMAN_VALIDATION_PROTOCOL.md', 'coordinator/HUMAN_VALIDATION_PROTOCOL.md')
|
| 53 |
+
archive.write(ROOT / 'review/INSAN_DEGERLENDIRMESI_UYGULAMA_KILAVUZU.md', 'INSAN_DEGERLENDIRMESI_UYGULAMA_KILAVUZU.md')
|
| 54 |
+
for reader in ['A', 'B']:
|
| 55 |
+
for name in ['pass1_semantics', 'pass2_decomposition']:
|
| 56 |
+
archive.write(ROOT / f'review/human/passes/{reader}_{name}.csv', f'annotator_{reader}/{reader}_{name}.csv')
|
| 57 |
+
archive.writestr('README_TR.md', '''# Bağımsız insan doğrulaması — koordinatör paketi
|
| 58 |
+
|
| 59 |
+
Bu çalışmanın insan değerlendirmesi henüz yapılmadı. Boş formlar sonuç değildir.
|
| 60 |
+
|
| 61 |
+
1. A ve B için önce yalnızca pass1_semantics dosyasını ve protokolü dağıtın. İlk geçiş kilitlendikten sonra aynı okuyucunun pass2_decomposition dosyasını verin. Tüm ZIP dosyasını okuyuculara göndermeyin. Birleşik parser_annotator formları koordinatör içindir.
|
| 62 |
+
2. coordinator klasörünü siz saklayın. Örnekleme anahtarı, diğer okuyucunun formu ve önceki makine etiketleri bağımsız etiketleme sırasında paylaşılmamalı.
|
| 63 |
+
3. Okuyucuların gerçek uzmanlık bilgilerini ve tarihleri kaydedin. 600 ifadenin üç temel alanını bağımsız doldurmalarını isteyin.
|
| 64 |
+
4. Önce bağımsız anlaşmayı hesaplayın; sonra anlaşmazlıkları gerekçeli uzlaştırın. Orijinal formları değiştirmeyin.
|
| 65 |
+
5. Tam proje paketindeki review/human dizinine tamamlanan formları yerleştirin ve protokoldeki komutu çalıştırın. Puanlayıcı boş veya U etiketleriyle doğruluk sonucu üretmez.
|
| 66 |
+
|
| 67 |
+
İki zarar formunda toplam 120 örnek vardır. Nedensel etiketleme için özgün görüntü ve tam/hedef/çapa/onarılmış/referans maskeleri ayrıca hazırlanmalıdır. Bu kit, görüntü incelemesinin yerine geçmez. İnsan etiketlerinden sonra örnekleme yapısını gözeten belirsizlik aralıkları ve uzlaştırılmış hata örnekleri rapora eklenmelidir.
|
| 68 |
+
''')
|
| 69 |
+
|
| 70 |
+
for archive_path in [complete, kit]:
|
| 71 |
+
with zipfile.ZipFile(archive_path) as archive:
|
| 72 |
+
assert archive.testzip() is None
|
| 73 |
+
count = len(archive.infolist())
|
| 74 |
+
print(json.dumps({'path': str(archive_path), 'files': count,
|
| 75 |
+
'bytes': archive_path.stat().st_size, 'sha256': sha256(archive_path)}))
|
| 76 |
+
print(json.dumps({'pdf': str(ROOT / 'RefSeg_CA_MVA.pdf'),
|
| 77 |
+
'sha256': sha256(ROOT / 'RefSeg_CA_MVA.pdf'),
|
| 78 |
+
'pages': validation['pages']}))
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
if __name__ == '__main__':
|
| 82 |
+
main()
|
source/code/phase1_analyze.py
ADDED
|
@@ -0,0 +1,165 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Image-paired summaries and calibration with explicit finite-sample limits.
|
| 2 |
+
|
| 3 |
+
The bound concerns ADDITIONAL false abstention from an already nonempty CACP
|
| 4 |
+
mask. It does not bound total false-empty errors and does not survive arbitrary
|
| 5 |
+
train-to-test distribution shift. All tested thresholds share a Bonferroni bound.
|
| 6 |
+
"""
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import argparse,json,collections,csv,gzip,hashlib
|
| 9 |
+
import numpy as np
|
| 10 |
+
from scipy.optimize import minimize
|
| 11 |
+
from scipy.special import expit
|
| 12 |
+
from scipy.stats import beta
|
| 13 |
+
ROOT=Path(__file__).resolve().parents[1];OUT=ROOT/'results/analysis'
|
| 14 |
+
SEEDS=[11,23,37];GRID=np.r_[np.arange(.025,1.001,.025),1.001]
|
| 15 |
+
FAMILY_SIZE=40*2*3*2 # thresholds x positive strata x fits x backbones
|
| 16 |
+
|
| 17 |
+
def fit_logistic(rows,seed):
|
| 18 |
+
x=np.array([r['features'] for r in rows]);y=np.array([r['target_count']==0 for r in rows],float)
|
| 19 |
+
rng=np.random.RandomState(seed);idx=np.concatenate([rng.choice(np.flatnonzero(y==v),int((y==v).sum()),replace=True) for v in [0,1]])
|
| 20 |
+
x=x[idx];y=y[idx];mu=x.mean(0);sd=x.std(0);sd[sd<1e-8]=1.;z=np.c_[(x-mu)/sd,np.ones(len(x))]
|
| 21 |
+
w=np.where(y==1,.5/max((y==1).mean(),1e-6),.5/max((y==0).mean(),1e-6))
|
| 22 |
+
def objective(b):
|
| 23 |
+
v=z@b;loss=np.mean(w*(np.logaddexp(0,v)-y*v))+.01*np.dot(b[:-1],b[:-1])
|
| 24 |
+
grad=z.T@(w*(expit(v)-y))/len(y);grad[:-1]+=.02*b[:-1]
|
| 25 |
+
return loss,grad
|
| 26 |
+
opt=minimize(objective,np.zeros(z.shape[1]),jac=True,method='L-BFGS-B',options={'maxiter':1000,'ftol':1e-12})
|
| 27 |
+
if not opt.success:raise RuntimeError('Logistic fit failed: '+opt.message)
|
| 28 |
+
return dict(mean=mu.tolist(),std=sd.tolist(),coef=opt.x.tolist(),n=len(y),seed=seed,objective=float(opt.fun))
|
| 29 |
+
|
| 30 |
+
def probability(rows,fit):
|
| 31 |
+
x=np.array([r['features'] for r in rows]);return expit(np.c_[(x-np.array(fit['mean']))/np.array(fit['std']),np.ones(len(x))]@np.array(fit['coef']))
|
| 32 |
+
|
| 33 |
+
def cp_upper(k,n,alpha):
|
| 34 |
+
if n==0:return 1.
|
| 35 |
+
return 1. if k==n else float(beta.ppf(1-alpha,k+1,n-k))
|
| 36 |
+
|
| 37 |
+
def operating_table(rows,fit):
|
| 38 |
+
iid_images=len({r['scene_id'] for r in rows})==len(rows)
|
| 39 |
+
p=probability(rows,fit);y=np.array([r['target_count']==0 for r in rows]);base=np.array([r['scores']['cacp']['empty'] for r in rows]);counts=np.array([r['target_count'] for r in rows]);out=[]
|
| 40 |
+
for t in GRID:
|
| 41 |
+
reject=p>=t;empty=base|reject;additional=reject&~base;groups={}
|
| 42 |
+
for name,sel in [('one',counts==1),('multi',counts>1)]:
|
| 43 |
+
n=int(sel.sum());k=int((additional&sel).sum())
|
| 44 |
+
groups[name]={'n':n,'k':k,'upper':(0. if t>1 else cp_upper(k,n,.05/FAMILY_SIZE)) if iid_images else None}
|
| 45 |
+
acc0=float(empty[y].mean()) if y.any() else 0.;far=float(empty[~y].mean()) if (~y).any() else 0.
|
| 46 |
+
out.append({'threshold':float(t),'no_target_accuracy':acc0,'false_empty':far,'additional_false_abstention':float(additional[~y].mean()),'balanced_accuracy':.5*(acc0+1-far),'groups':groups,'worst_upper':max(g['upper'] for g in groups.values()) if iid_images else None})
|
| 47 |
+
return out
|
| 48 |
+
|
| 49 |
+
def add_calibration(rows):
|
| 50 |
+
params={};curve=[]
|
| 51 |
+
for seed in SEEDS:
|
| 52 |
+
for domain in ['controlled','natural']:
|
| 53 |
+
train=[r for r in rows if r['domain']==domain and r['split']=='fit' and r['mode']!='action']
|
| 54 |
+
cal=[r for r in rows if r['domain']==domain and r['split']=='cal' and r['mode']!='action']
|
| 55 |
+
fit=fit_logistic(train,seed);table=operating_table(cal,fit)
|
| 56 |
+
uncon=max(table,key=lambda x:(x['balanced_accuracy'],x['threshold']))
|
| 57 |
+
variants={('source_unconstrained' if domain=='controlled' else 'target_unconstrained'):uncon}
|
| 58 |
+
if domain=='natural':
|
| 59 |
+
for eps in [.01,.025,.05,.10]:
|
| 60 |
+
allowed=[x for x in table if x['worst_upper']<=eps]
|
| 61 |
+
variants[f'constrained_{eps:g}']=max(allowed,key=lambda x:(x['no_target_accuracy'],-x['additional_false_abstention'],x['threshold']))
|
| 62 |
+
curve.extend(dict(seed=seed,**x) for x in table)
|
| 63 |
+
scores=probability(rows,fit)
|
| 64 |
+
for variant,point in variants.items():
|
| 65 |
+
name=f'{variant}_s{seed}';t=point['threshold'];params[name]={'fit':fit,'operating_point':point,'calibration_domain':domain}
|
| 66 |
+
for r,pr in zip(rows,scores):
|
| 67 |
+
base=r['scores']['cacp'];reject=bool(pr>=t)
|
| 68 |
+
# Explicit action semantics are already handled by CACP.
|
| 69 |
+
val=dict(base)
|
| 70 |
+
if reject:val.update(iou=1. if r['target_count']==0 else 0.,intersection=0,union=base['gt_pixels'],pred_pixels=0,empty=True)
|
| 71 |
+
val['additional_abstention']=reject and not base['empty'];r['scores'][name]=val
|
| 72 |
+
if domain=='natural' and seed==11:r['absence_probability']=float(pr)
|
| 73 |
+
return params,curve
|
| 74 |
+
|
| 75 |
+
def cluster_ci(values,keys,strata=None,reps=2000):
|
| 76 |
+
vals=np.asarray(values,float);groups=collections.defaultdict(list)
|
| 77 |
+
for i,k in enumerate(keys):groups[k].append(i)
|
| 78 |
+
ids=list(groups);arr=np.array([vals[groups[k]].mean(0) for k in ids])
|
| 79 |
+
if strata is None:labels=np.zeros(len(ids),int)
|
| 80 |
+
else:labels=np.array([str(strata[groups[k][0]]) for k in ids])
|
| 81 |
+
rng=np.random.RandomState(20260906);boot=np.zeros((reps,)+arr.shape[1:]);n=0
|
| 82 |
+
for label in sorted(set(labels)):
|
| 83 |
+
a=arr[labels==label];draw=rng.randint(0,len(a),size=(reps,len(a)));boot+=a[draw].sum(axis=1);n+=len(a)
|
| 84 |
+
boot/=n
|
| 85 |
+
return arr.mean(axis=0),np.quantile(boot,.025,axis=0),np.quantile(boot,.975,axis=0),len(arr)
|
| 86 |
+
|
| 87 |
+
def summarize(rows,methods):
|
| 88 |
+
summaries=[]
|
| 89 |
+
def emit(name,rr,metric,threshold=.5):
|
| 90 |
+
if not rr:return
|
| 91 |
+
if metric=='pc':
|
| 92 |
+
pairs=collections.defaultdict(list)
|
| 93 |
+
for r in rr:pairs[r['pair_id']].append(r)
|
| 94 |
+
assert all(len(x)==2 for x in pairs.values())
|
| 95 |
+
data=[];keys=[];strata=[]
|
| 96 |
+
for pp in pairs.values():
|
| 97 |
+
data.append([float(all(r['scores'][m]['iou']>=threshold for r in pp)) for m in methods]);keys.append(pp[0]['scene_id']);strata.append(pp[0]['seed'])
|
| 98 |
+
else:
|
| 99 |
+
data=[];keys=[];strata=[]
|
| 100 |
+
for r in rr:
|
| 101 |
+
data.append([float(r['scores'][m]['empty']) if metric in ['no_target_accuracy','false_empty'] else float(r['scores'][m].get('additional_abstention',False)) if metric=='additional_false_abstention' else r['scores'][m]['iou'] for m in methods]);keys.append(r['scene_id']);strata.append(r['seed'] if r['domain']=='controlled' else r['split']+'_'+r['mode'])
|
| 102 |
+
data=np.array(data);mean,lo,hi,n=cluster_ci(data,keys,strata)
|
| 103 |
+
delta,dlo,dhi,_=cluster_ci(data-data[:,[methods.index('frozen')]],keys,strata)
|
| 104 |
+
for i,m in enumerate(methods):summaries.append(dict(population=name,metric=('PC50' if threshold==.5 else 'PC70') if metric=='pc' else metric,method=m,estimate=float(mean[i]),lo=float(lo[i]),hi=float(hi[i]),gain=float(delta[i]),gain_lo=float(dlo[i]),gain_hi=float(dhi[i]),clusters=n,units=len(data)))
|
| 105 |
+
controlled=[r for r in rows if r['domain']=='controlled' and r['split']=='test']
|
| 106 |
+
clean=[r for r in controlled if r['corruption']=='clean']
|
| 107 |
+
primary=[r for r in clean if r['mode'] in ['attribute','relation','quantifier','absence']]
|
| 108 |
+
emit('controlled_primary',primary,'pc');emit('controlled_primary',primary,'pc',.7)
|
| 109 |
+
for family in ['attribute','relation','quantifier','action','absence','paraphrase']:
|
| 110 |
+
emit('family_'+family,[r for r in clean if r['mode']==family],'pc')
|
| 111 |
+
for template in ['seen','held']:emit('template_'+template,[r for r in primary if r['template']==template],'pc')
|
| 112 |
+
stress_ids={r['scene_id'] for r in controlled if r['corruption']!='clean'}
|
| 113 |
+
for corruption in ['clean','blur','noise','dim']:
|
| 114 |
+
rr=[r for r in controlled if r['corruption']==corruption and r['scene_id'] in stress_ids and r['mode'] in ['attribute','relation','quantifier','absence']]
|
| 115 |
+
emit('stress_'+corruption,rr,'pc')
|
| 116 |
+
for name,rr in [('controlled_clean',clean),('natural_test',[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB']])]+[(s,[r for r in rows if r['domain']=='natural' and r['split']==s]) for s in ['val','testA','testB']]:
|
| 117 |
+
emit(name,rr,'gIoU');emit(name,[r for r in rr if r['target_count']>0],'positive_mIoU');emit(name,[r for r in rr if r['target_count']==0],'no_target_accuracy');emit(name,[r for r in rr if r['target_count']>0],'false_empty');emit(name,[r for r in rr if r['target_count']>0],'additional_false_abstention')
|
| 118 |
+
for mode in ['zero','one','multi']:
|
| 119 |
+
rr=[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB'] and r['mode']==mode]
|
| 120 |
+
emit('natural_'+mode,rr,'gIoU')
|
| 121 |
+
return summaries
|
| 122 |
+
|
| 123 |
+
def main():
|
| 124 |
+
a=argparse.ArgumentParser();a.add_argument('--model',choices=['clipseg','groundedsam']);args=a.parse_args();OUT.mkdir(parents=True,exist_ok=True)
|
| 125 |
+
models=[args.model] if args.model else ['clipseg','groundedsam'];allsummary=[];allparam={};allcurves=[];metadata={}
|
| 126 |
+
main_methods=['frozen','action_only','largest','global_direction','target_only','anchor_nogate','anchor_gate','counterfactual_nogate','cacp','source_unconstrained_s11','target_unconstrained_s11','constrained_0.05_s11']
|
| 127 |
+
for model in models:
|
| 128 |
+
shards=2 if model=='clipseg' else 8
|
| 129 |
+
files=sorted((ROOT/'results').glob(model+f'_main_*of{shards}.jsonl'));metas=sorted((ROOT/'results').glob(model+f'_main_*of{shards}_meta.json'))
|
| 130 |
+
if len(files)!=shards or len(metas)!=shards:raise RuntimeError('Model runs are incomplete: '+model)
|
| 131 |
+
rows=[json.loads(l) for f in files for l in f.read_text().splitlines()];expected=json.loads((ROOT/'data/dataset_summary.json').read_text())['records']
|
| 132 |
+
assert len(rows)==expected and len({r['id'] for r in rows})==expected
|
| 133 |
+
assert all(json.loads(m.read_text())['status']=='COMPLETE' for m in metas)
|
| 134 |
+
params,curves=add_calibration(rows);allparam[model]=params;allcurves.extend(dict(model=model,**c) for c in curves)
|
| 135 |
+
ss=summarize(rows,main_methods);allsummary.extend(dict(model=model,**s) for s in ss)
|
| 136 |
+
# Seed/tolerance sensitivity is a separate table, not independent evidence.
|
| 137 |
+
sensitivity=[]
|
| 138 |
+
for seed in SEEDS:
|
| 139 |
+
for eps in [.01,.025,.05,.1]:
|
| 140 |
+
name=f'constrained_{eps:g}_s{seed}'
|
| 141 |
+
for pop,sel in [('natural_test',[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB']]),('val',[r for r in rows if r['domain']=='natural' and r['split']=='val'])]:
|
| 142 |
+
pos=[r for r in sel if r['target_count']>0];neg=[r for r in sel if r['target_count']==0]
|
| 143 |
+
sensitivity.append(dict(model=model,seed=seed,tolerance=eps,population=pop,threshold=params[name]['operating_point']['threshold'],cal_upper=params[name]['operating_point']['worst_upper'],positive_iou=float(np.mean([r['scores'][name]['iou'] for r in pos])),no_target_accuracy=float(np.mean([r['scores'][name]['empty'] for r in neg])),false_empty=float(np.mean([r['scores'][name]['empty'] for r in pos])),additional_false_abstention=float(np.mean([r['scores'][name]['additional_abstention'] for r in pos]))))
|
| 144 |
+
(OUT/f'{model}_sensitivity.json').write_text(json.dumps(sensitivity,indent=2))
|
| 145 |
+
# Oracle anchor substitution: diagnostic, not a guaranteed upper bound.
|
| 146 |
+
oracle_rows=[r for r in rows if r['domain']=='controlled'];os=summarize(oracle_rows,['frozen','cacp','oracle_anchor'])
|
| 147 |
+
(OUT/f'{model}_oracle.json').write_text(json.dumps(os,indent=2))
|
| 148 |
+
reasons=collections.Counter(r['flags']['reason'] for r in rows if r['split'] in ['test','testA','testB','val']);bydomain={}
|
| 149 |
+
for domain in ['controlled','natural']:
|
| 150 |
+
rr=[r for r in rows if r['domain']==domain and r['split'] in ['test','testA','testB','val'] and r['corruption']=='clean']
|
| 151 |
+
bydomain[domain]={'n':len(rr),'supported':sum(r['flags']['supported'] for r in rr),'changed':sum(r['flags']['changed'] for r in rr),'harm_iou':sum(r['scores']['cacp']['iou']<r['scores']['frozen']['iou'] for r in rr),'help_iou':sum(r['scores']['cacp']['iou']>r['scores']['frozen']['iou'] for r in rr)}
|
| 152 |
+
metadata[model]={'runs':[json.loads(m.read_text()) for m in metas],'reason_counts':dict(reasons),'coverage':bydomain}
|
| 153 |
+
with gzip.open(OUT/f'{model}_evaluated.jsonl.gz','wt') as f:
|
| 154 |
+
for r in rows:f.write(json.dumps(r)+'\n')
|
| 155 |
+
# Test trade-off curves use the fixed calibration-trained score; no tuning.
|
| 156 |
+
test=[r for r in rows if r['domain']=='natural' and r['split'] in ['testA','testB']]
|
| 157 |
+
curve_test=operating_table(test,params['target_unconstrained_s11']['fit'])
|
| 158 |
+
(OUT/f'{model}_test_curve.json').write_text(json.dumps(curve_test,indent=2))
|
| 159 |
+
print('ANALYZED',model,flush=True)
|
| 160 |
+
(OUT/'summary.json').write_text(json.dumps(allsummary,indent=2))
|
| 161 |
+
with (OUT/'summary.csv').open('w') as f:
|
| 162 |
+
writer=csv.DictWriter(f,fieldnames=list(allsummary[0]));writer.writeheader();writer.writerows(allsummary)
|
| 163 |
+
(OUT/'calibration.json').write_text(json.dumps(allparam,indent=2));(OUT/'calibration_curves.json').write_text(json.dumps(allcurves,indent=2));(OUT/'run_summary.json').write_text(json.dumps(metadata,indent=2))
|
| 164 |
+
(OUT/'statistical_notes.json').write_text(json.dumps({'bootstrap_replicates':2000,'interval':'95% percentile, paired image/scene clusters, stratified by seed or official split and target stratum','multiplicity':'Confidence intervals are descriptive and unadjusted; ablations are not independent replications','calibration_family_size':FAMILY_SIZE,'calibration_alpha':.05,'calibration_scope':'Simultaneous stratum-wise Clopper-Pearson bounds for additional false abstention under independent, identically distributed Bernoulli sampling within each stratum; official train/test shifts are evaluated empirically, not guaranteed','minimum_n_zero_failures':{str(eps):int(np.ceil(np.log(.05/FAMILY_SIZE)/np.log(1-eps))) for eps in [.01,.025,.05,.1]}},indent=2))
|
| 165 |
+
if __name__=='__main__':main()
|
source/code/phase1_infer.py
ADDED
|
@@ -0,0 +1,131 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Frozen GPU inference, image-level caching, and label-isolated CACP evaluation."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse,json,time,os,hashlib,collections,platform
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from repair import query_plan,repaired_maps,visual_features,score_mask
|
| 7 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 8 |
+
|
| 9 |
+
class ClipSeg:
|
| 10 |
+
threshold=.5
|
| 11 |
+
def __init__(self):
|
| 12 |
+
import torch
|
| 13 |
+
from transformers import CLIPSegProcessor,CLIPSegForImageSegmentation
|
| 14 |
+
self.torch=torch;path=ROOT/'assets/models/clipseg'
|
| 15 |
+
self.processor=CLIPSegProcessor.from_pretrained(str(path),local_files_only=True)
|
| 16 |
+
self.model=CLIPSegForImageSegmentation.from_pretrained(str(path),local_files_only=True).eval().cuda()
|
| 17 |
+
def predict(self,image,texts):
|
| 18 |
+
t=self.torch;out={}
|
| 19 |
+
with t.inference_mode():
|
| 20 |
+
for k in range(0,len(texts),8):
|
| 21 |
+
batch=texts[k:k+8]
|
| 22 |
+
inputs=self.processor(text=batch,images=[image]*len(batch),padding=True,truncation=True,return_tensors='pt').to('cuda')
|
| 23 |
+
logits=self.model(**inputs,interpolate_pos_encoding=True).logits
|
| 24 |
+
if logits.ndim==2:logits=logits[None]
|
| 25 |
+
probs=t.nn.functional.interpolate(logits[:,None],size=(image.height,image.width),mode='bilinear',align_corners=False)[:,0].sigmoid()
|
| 26 |
+
for q,p in zip(batch,probs):out[q]=p.float().cpu().numpy()
|
| 27 |
+
return out,{'language_queries':len(texts),'sam_boxes':0,'truncated_boxes':0}
|
| 28 |
+
|
| 29 |
+
class GroundedSam:
|
| 30 |
+
threshold=.25
|
| 31 |
+
def __init__(self):
|
| 32 |
+
import torch
|
| 33 |
+
from transformers import AutoProcessor,AutoModelForZeroShotObjectDetection,SamProcessor,SamModel,GroundingDinoConfig
|
| 34 |
+
self.torch=torch;p=ROOT/'assets/models/groundingdino';s=ROOT/'assets/models/sam'
|
| 35 |
+
self.processor=AutoProcessor.from_pretrained(str(p),local_files_only=True)
|
| 36 |
+
cfg=GroundingDinoConfig.from_pretrained(str(p),local_files_only=True);cfg.disable_custom_kernels=True
|
| 37 |
+
self.model=AutoModelForZeroShotObjectDetection.from_pretrained(str(p),config=cfg,local_files_only=True).eval().cuda()
|
| 38 |
+
self.samproc=SamProcessor.from_pretrained(str(s),local_files_only=True)
|
| 39 |
+
self.sam=SamModel.from_pretrained(str(s),local_files_only=True).eval().cuda()
|
| 40 |
+
def predict(self,image,texts):
|
| 41 |
+
t=self.torch;allboxes=[];detections={};truncated=0;out={}
|
| 42 |
+
with t.inference_mode():
|
| 43 |
+
for k in range(0,len(texts),2):
|
| 44 |
+
batch=texts[k:k+2]
|
| 45 |
+
inputs=self.processor(images=[image]*len(batch),text=[q.strip(' .')+'.' for q in batch],padding=True,truncation=True,return_tensors='pt').to('cuda')
|
| 46 |
+
pred=self.model(**inputs)
|
| 47 |
+
det=self.processor.post_process_grounded_object_detection(pred,inputs.input_ids,box_threshold=.25,text_threshold=.25,target_sizes=[(image.height,image.width)]*len(batch))
|
| 48 |
+
for q,d in zip(batch,det):
|
| 49 |
+
order=d['scores'].argsort(descending=True);truncated+=max(0,len(order)-30);order=order[:30]
|
| 50 |
+
entries=[]
|
| 51 |
+
for box,score in zip(d['boxes'][order].cpu().tolist(),d['scores'][order].cpu().tolist()):
|
| 52 |
+
box=[max(0,min(v,image.width if j%2==0 else image.height)) for j,v in enumerate(box)]
|
| 53 |
+
if box[2]-box[0]<1 or box[3]-box[1]<1:continue
|
| 54 |
+
key=tuple(round(v,1) for v in box)
|
| 55 |
+
if key not in allboxes:allboxes.append(key)
|
| 56 |
+
entries.append((allboxes.index(key),float(score)))
|
| 57 |
+
detections[q]=entries
|
| 58 |
+
masks=[]
|
| 59 |
+
if allboxes:
|
| 60 |
+
ip=self.samproc(images=image,return_tensors='pt').to('cuda')
|
| 61 |
+
emb=self.sam.get_image_embeddings(ip.pixel_values)
|
| 62 |
+
for k in range(0,len(allboxes),16):
|
| 63 |
+
ins=self.samproc(images=image,input_boxes=[[list(b) for b in allboxes[k:k+16]]],return_tensors='pt').to('cuda')
|
| 64 |
+
pr=self.sam(image_embeddings=emb,input_boxes=ins.input_boxes,multimask_output=True)
|
| 65 |
+
chosen=pr.iou_scores[0].argmax(dim=-1)
|
| 66 |
+
low=pr.pred_masks[:,t.arange(len(chosen),device='cuda'),chosen,: ,:][:,:,None]
|
| 67 |
+
# Official postprocessing restores original image resolution.
|
| 68 |
+
full=self.samproc.image_processor.post_process_masks(low,ins.original_sizes,ins.reshaped_input_sizes,binarize=True)[0]
|
| 69 |
+
masks.extend(full[:,0].cpu().numpy().astype(bool))
|
| 70 |
+
for q in texts:
|
| 71 |
+
p=np.zeros((image.height,image.width),np.float32)
|
| 72 |
+
for idx,score in detections[q]:p=np.maximum(p,masks[idx]*score)
|
| 73 |
+
out[q]=p
|
| 74 |
+
return out,{'language_queries':len(texts),'sam_boxes':len(allboxes),'truncated_boxes':truncated}
|
| 75 |
+
|
| 76 |
+
def main():
|
| 77 |
+
p=argparse.ArgumentParser();p.add_argument('--model',choices=['clipseg','groundedsam'],required=True)
|
| 78 |
+
p.add_argument('--shard',type=int,default=0);p.add_argument('--shards',type=int,default=1)
|
| 79 |
+
p.add_argument('--pilot',action='store_true');p.add_argument('--limit',type=int,default=0)
|
| 80 |
+
args=p.parse_args();print('IMPORT_START',vars(args),flush=True)
|
| 81 |
+
import torch,transformers
|
| 82 |
+
torch.set_num_threads(4);torch.manual_seed(20260906);np.random.seed(20260906)
|
| 83 |
+
assert torch.cuda.is_available(),'GPU required: submit with Slurm'
|
| 84 |
+
records=[json.loads(x) for x in (ROOT/'data/manifest.jsonl').read_text().splitlines()]
|
| 85 |
+
if args.pilot:
|
| 86 |
+
# Infrastructure / implementation checks see fit examples only.
|
| 87 |
+
records=[r for r in records if r['split']=='fit']
|
| 88 |
+
records=[r for r in records if (r['domain']=='controlled' and r['scene_id']=='s11_0000') or r['domain']=='natural']
|
| 89 |
+
groups=collections.defaultdict(list)
|
| 90 |
+
for r in records:groups[r['image_path']].append(r)
|
| 91 |
+
selected=sorted(groups)
|
| 92 |
+
if args.pilot:selected=selected[:1]+[x for x in selected if '/natural/' in x][:3]
|
| 93 |
+
elif args.limit:selected=selected[:args.limit]
|
| 94 |
+
selected=selected[args.shard::args.shards]
|
| 95 |
+
suffix=f'{args.model}_{"pilot" if args.pilot else "main"}_{args.shard}of{args.shards}'
|
| 96 |
+
cache=ROOT/'cache'/args.model;cache.mkdir(parents=True,exist_ok=True)
|
| 97 |
+
resultfile=ROOT/'results'/f'{suffix}.jsonl';timingfile=ROOT/'results'/f'{suffix}_timings.jsonl'
|
| 98 |
+
engine=ClipSeg() if args.model=='clipseg' else GroundedSam()
|
| 99 |
+
print('MODEL_READY',torch.cuda.get_device_name(0),'images',len(selected),flush=True)
|
| 100 |
+
started=time.time();nrecord=0;queries=0;gpu_seconds=0;hits=0
|
| 101 |
+
with resultfile.open('w') as result,timingfile.open('w') as timing:
|
| 102 |
+
for index,ipath in enumerate(selected):
|
| 103 |
+
group=groups[ipath];texts=[]
|
| 104 |
+
for r in group:
|
| 105 |
+
_,qs=query_plan(r['query']);texts.extend(qs)
|
| 106 |
+
texts=list(dict.fromkeys(texts));image=Image.open(ROOT/ipath).convert('RGB')
|
| 107 |
+
digest=hashlib.sha256((ipath+'\n'+'\n'.join(texts)).encode()).hexdigest()[:24];cp=cache/(digest+'.npz')
|
| 108 |
+
elapsed=0.;stats={'language_queries':0,'sam_boxes':0,'truncated_boxes':0}
|
| 109 |
+
if cp.exists():
|
| 110 |
+
z=np.load(cp);assert z['texts'].tolist()==texts;maps={q:z[f'p{i}'].astype(np.float32) for i,q in enumerate(texts)};hits+=1
|
| 111 |
+
else:
|
| 112 |
+
torch.cuda.synchronize();t0=time.perf_counter();maps,stats=engine.predict(image,texts);torch.cuda.synchronize();elapsed=time.perf_counter()-t0
|
| 113 |
+
# Quantize identically before both scoring and storage, so replay
|
| 114 |
+
# and initial evaluation see exactly the same cached scores.
|
| 115 |
+
maps={q:maps[q].astype(np.float16).astype(np.float32) for q in texts}
|
| 116 |
+
assert all(np.isfinite(v).all() and v.min()>=0 and v.max()<=1 for v in maps.values())
|
| 117 |
+
tmp=cp.with_suffix('.partial.npz');np.savez_compressed(tmp,texts=np.array(texts),**{f'p{i}':maps[q].astype(np.float16) for i,q in enumerate(texts)});tmp.replace(cp)
|
| 118 |
+
gpu_seconds+=elapsed;queries+=stats['language_queries']
|
| 119 |
+
# Ground truth is loaded only after all model predictions are fixed.
|
| 120 |
+
for r in group:
|
| 121 |
+
gt=np.asarray(Image.open(ROOT/r['gt_path']))>0
|
| 122 |
+
oracle=np.asarray(Image.open(ROOT/r['anchor_gt_path']))>0 if 'anchor_gt_path' in r else None
|
| 123 |
+
preds,flags=repaired_maps(r['query'],maps,engine.threshold,oracle_anchor=oracle)
|
| 124 |
+
row={k:r[k] for k in ['id','scene_id','domain','split','mode','pair_id','endpoint','target_count','seed','template','corruption']}
|
| 125 |
+
row.update(model=args.model,flags=flags,features=visual_features(maps[query_plan(r['query'])[0].original],preds['cacp'],engine.threshold),scores={m:score_mask(pred,gt) for m,pred in preds.items()},cache_path=str(cp.relative_to(ROOT)),query_count=len(query_plan(r['query'])[1]))
|
| 126 |
+
result.write(json.dumps(row)+'\n');nrecord+=1
|
| 127 |
+
timing.write(json.dumps(dict(image_path=ipath,records=len(group),requested_unique_queries=len(texts),cached=elapsed==0,seconds=elapsed,**stats))+'\n');result.flush();timing.flush()
|
| 128 |
+
if index%20==0:print(json.dumps({'image':index+1,'of':len(selected),'records':nrecord,'new_queries':queries,'forward_seconds':round(gpu_seconds,2),'wall_seconds':round(time.time()-started,2)}),flush=True)
|
| 129 |
+
meta={'status':'COMPLETE','model':args.model,'images':len(selected),'records':nrecord,'unique_queries_executed':queries,'cache_hits':hits,'forward_seconds':gpu_seconds,'wall_seconds':time.time()-started,'gpu':torch.cuda.get_device_name(0),'torch':torch.__version__,'transformers':transformers.__version__,'numpy':np.__version__,'python':platform.python_version(),'slurm_job_id':os.getenv('SLURM_JOB_ID'),'node':os.getenv('SLURMD_NODENAME'),'args':vars(args),'manifest_sha256':hashlib.sha256((ROOT/'data/manifest.jsonl').read_bytes()).hexdigest(),'code_sha256':{x:hashlib.sha256((ROOT/'code'/x).read_bytes()).hexdigest() for x in ['infer.py','repair.py']}}
|
| 130 |
+
(ROOT/'results'/f'{suffix}_meta.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True)
|
| 131 |
+
if __name__=='__main__':main()
|
source/code/phase1_repair.py
ADDED
|
@@ -0,0 +1,152 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Counterfactual Anchor-Consistent Projection (CACP).
|
| 2 |
+
|
| 3 |
+
All primary decisions use only query text and predicted maps. The optional
|
| 4 |
+
oracle anchor is isolated and must never be supplied to the primary method.
|
| 5 |
+
Fixed defaults are declared before the evaluation predictions are observed.
|
| 6 |
+
"""
|
| 7 |
+
import re
|
| 8 |
+
from dataclasses import dataclass, asdict
|
| 9 |
+
import numpy as np
|
| 10 |
+
from scipy import ndimage
|
| 11 |
+
|
| 12 |
+
@dataclass(frozen=True)
|
| 13 |
+
class Query:
|
| 14 |
+
original: str
|
| 15 |
+
target: str
|
| 16 |
+
anchor: str = ''
|
| 17 |
+
relation: str = ''
|
| 18 |
+
opposite: str = ''
|
| 19 |
+
plural: bool = False
|
| 20 |
+
negate: bool = False
|
| 21 |
+
supported: bool = False
|
| 22 |
+
|
| 23 |
+
OPPOSITE = {'left':'right','right':'left','above':'below','below':'above'}
|
| 24 |
+
VERBS = r'(?:segment|show|select|find|highlight)'
|
| 25 |
+
IRREGULAR = {'people':'person','men':'man','women':'woman','children':'child'}
|
| 26 |
+
def noun_phrase(s):
|
| 27 |
+
s=re.sub(r'^(?:(?:all|every|both|two|the|a|an)\s+)+','',s.strip())
|
| 28 |
+
words=s.split()
|
| 29 |
+
if not words:return s
|
| 30 |
+
w=words[-1]
|
| 31 |
+
if w in IRREGULAR:words[-1]=IRREGULAR[w]
|
| 32 |
+
elif w.endswith('s') and not w.endswith(('ss','us','is')):words[-1]=w[:-1]
|
| 33 |
+
return ' '.join(words)
|
| 34 |
+
|
| 35 |
+
def parse_query(text):
|
| 36 |
+
q=' '.join(text.lower().strip(' .').split())
|
| 37 |
+
neg=bool(re.match(r"^(?:do not|don't)\s+"+VERBS+r'\b',q))
|
| 38 |
+
cleaned=re.sub(r"^(?:do not|don't)\s+",'',q) if neg else q
|
| 39 |
+
cleaned=re.sub(r'^'+VERBS+r'\s+','',cleaned)
|
| 40 |
+
plural=bool(re.search(r'\b(all|every|both|two|people|men|women|children)\b',cleaned))
|
| 41 |
+
# Only a single explicit relation is supported; nested clauses fall back.
|
| 42 |
+
pat=r'^(.+?)\s+(?:(?:to|on)\s+the\s+)?(left|right)\s+of\s+(.+)$'
|
| 43 |
+
m=re.match(pat,cleaned)
|
| 44 |
+
if not m:m=re.match(r'^(.+?)\s+(above|below)\s+(.+)$',cleaned)
|
| 45 |
+
if m:
|
| 46 |
+
t,rel,a=m.groups()
|
| 47 |
+
if re.search(r'\b(left|right|above|below|that|which)\b',a):
|
| 48 |
+
return Query(q,q,plural=plural,negate=neg)
|
| 49 |
+
opp=re.sub(r'\b'+rel+r'\b',OPPOSITE[rel],q,count=1)
|
| 50 |
+
return Query(q,noun_phrase(t),noun_phrase(a),rel,opp,plural,neg,True)
|
| 51 |
+
m=re.match(r'^(?:the\s+)?(leftmost|rightmost|topmost|bottommost)\s+(.+)$',cleaned)
|
| 52 |
+
if m:return Query(q,noun_phrase(m[2]),relation=m[1],plural=plural,negate=neg,supported=True)
|
| 53 |
+
# Simple imperatives / quantified noun phrases are compositional; preserve
|
| 54 |
+
# unrestricted natural expressions rather than pretending a regex is a parser.
|
| 55 |
+
simple=bool(re.match(r'^'+VERBS+r'\s+',q) or re.match(r'^(all|every|both|two)\s+',cleaned))
|
| 56 |
+
if simple and len(cleaned.split())<=5:
|
| 57 |
+
return Query(q,noun_phrase(cleaned),plural=plural,negate=neg,supported=True)
|
| 58 |
+
return Query(q,q,plural=plural,negate=neg,supported=neg)
|
| 59 |
+
|
| 60 |
+
def query_plan(text):
|
| 61 |
+
q=parse_query(text)
|
| 62 |
+
return q,list(dict.fromkeys([q.original,q.target]+([q.anchor,q.opposite] if q.anchor else [])))
|
| 63 |
+
|
| 64 |
+
def components(prob,threshold):
|
| 65 |
+
lab,n=ndimage.label(prob>=threshold,structure=np.ones((3,3),int))
|
| 66 |
+
sizes=np.bincount(lab.ravel());out=[];h,w=prob.shape
|
| 67 |
+
for i,sl in enumerate(ndimage.find_objects(lab),1):
|
| 68 |
+
if sl is None or sizes[i]<max(16,int(.0002*h*w)):continue
|
| 69 |
+
mask=lab==i;ys,xs=np.nonzero(mask)
|
| 70 |
+
out.append({'mask':mask,'area':int(sizes[i]),'x':float(xs.mean()/w),'y':float(ys.mean()/h),'confidence':float(prob[mask].mean())})
|
| 71 |
+
return sorted(out,key=lambda c:c['confidence'],reverse=True)
|
| 72 |
+
|
| 73 |
+
def union(cs,shape):
|
| 74 |
+
out=np.zeros(shape,bool)
|
| 75 |
+
for c in cs:out|=c['mask']
|
| 76 |
+
return out
|
| 77 |
+
|
| 78 |
+
def native(prob,threshold):return union(components(prob,threshold),prob.shape)
|
| 79 |
+
|
| 80 |
+
def global_component(cs,relation):
|
| 81 |
+
key='x' if relation in ('left','right','leftmost','rightmost') else 'y'
|
| 82 |
+
positive=relation in ('right','rightmost','below','bottommost')
|
| 83 |
+
return sorted(cs,key=lambda c:c[key],reverse=positive)[0]
|
| 84 |
+
|
| 85 |
+
def repaired_maps(text,maps,threshold,oracle_anchor=None):
|
| 86 |
+
q=parse_query(text);p=maps[q.original];base=native(p,threshold);empty=np.zeros_like(base)
|
| 87 |
+
cs=components(p,threshold)
|
| 88 |
+
largest=union([max(cs,key=lambda c:c['area'])],p.shape) if cs else empty
|
| 89 |
+
action=empty if q.negate else base
|
| 90 |
+
global_out=base if q.plural else largest
|
| 91 |
+
if q.relation and cs:global_out=global_component(cs,q.relation)['mask']
|
| 92 |
+
if q.negate:global_out=empty
|
| 93 |
+
pt=maps.get(q.target,p);targets=components(pt,threshold)
|
| 94 |
+
target_out=union(targets,p.shape) if q.supported else base
|
| 95 |
+
if q.negate:target_out=empty
|
| 96 |
+
result={'frozen':base,'action_only':action,'largest':empty if q.negate else largest,
|
| 97 |
+
'global_direction':global_out,'target_only':target_out}
|
| 98 |
+
flags={'supported':q.supported,'relation':q.relation,'anchor':q.anchor,
|
| 99 |
+
'anchor_margin':None,'score_margin':None,'reason':'fallback'}
|
| 100 |
+
def project(use_cf=True,gate=True,oracle=False):
|
| 101 |
+
if q.negate:return empty,'action',None,None
|
| 102 |
+
if not q.supported:return base,'unsupported',None,None
|
| 103 |
+
if not targets:return base,'no_target_proposal',None,None
|
| 104 |
+
if q.relation.endswith('most'):
|
| 105 |
+
return global_component(targets,q.relation)['mask'],'extreme',None,None
|
| 106 |
+
if not q.anchor:
|
| 107 |
+
if q.plural:return union(targets,p.shape),'plural',None,None
|
| 108 |
+
scores=sorted(targets,key=lambda c:c['confidence'],reverse=True)
|
| 109 |
+
margin=scores[0]['confidence']-(scores[1]['confidence'] if len(scores)>1 else 0)
|
| 110 |
+
if gate and margin<.05:return base,'target_ambiguous',None,margin
|
| 111 |
+
return scores[0]['mask'],'singular',None,margin
|
| 112 |
+
anchors=components(maps[q.anchor],threshold)
|
| 113 |
+
if oracle:
|
| 114 |
+
if oracle_anchor is None:return base,'oracle_unavailable',None,None
|
| 115 |
+
anchors=components(oracle_anchor.astype(float),.5)
|
| 116 |
+
if not anchors:return base,'anchor_missing',None,None
|
| 117 |
+
ac=anchors[0];am=ac['confidence']-(anchors[1]['confidence'] if len(anchors)>1 else 0)
|
| 118 |
+
if gate and am<.05:return base,'anchor_ambiguous',am,None
|
| 119 |
+
key='x' if q.relation in ('left','right') else 'y'
|
| 120 |
+
sign=1 if q.relation in ('right','below') else -1
|
| 121 |
+
allowed=[]
|
| 122 |
+
for c in targets:
|
| 123 |
+
distance=sign*(c[key]-ac[key])
|
| 124 |
+
if distance<(.03 if gate else 0):continue
|
| 125 |
+
residual=float((p[c['mask']]-maps[q.opposite][c['mask']]).mean())
|
| 126 |
+
score=c['confidence']+(.5*residual if use_cf else 0)
|
| 127 |
+
allowed.append((score,c,residual))
|
| 128 |
+
if not allowed:return base,'relation_unsatisfied',am,None
|
| 129 |
+
allowed.sort(key=lambda z:z[0],reverse=True)
|
| 130 |
+
sm=allowed[0][0]-(allowed[1][0] if len(allowed)>1 else 0)
|
| 131 |
+
# A confidently contradictory full-query response blocks a repair.
|
| 132 |
+
if use_cf and gate and allowed[0][2]<-.05:return base,'counterfactual_veto',am,sm
|
| 133 |
+
if not q.plural and gate and sm<.05:return base,'assignment_ambiguous',am,sm
|
| 134 |
+
return union([c for _,c,_ in allowed] if q.plural else [allowed[0][1]],p.shape),'projected',am,sm
|
| 135 |
+
result['anchor_nogate']=project(False,False)[0]
|
| 136 |
+
result['anchor_gate']=project(False,True)[0]
|
| 137 |
+
result['counterfactual_nogate']=project(True,False)[0]
|
| 138 |
+
main,reason,am,sm=project(True,True);result['cacp']=main
|
| 139 |
+
if oracle_anchor is not None:result['oracle_anchor']=project(True,True,True)[0]
|
| 140 |
+
flags.update(reason=reason,anchor_margin=am,score_margin=sm,changed=bool(np.any(main!=base)))
|
| 141 |
+
return result,flags
|
| 142 |
+
|
| 143 |
+
def visual_features(prob,mask,threshold):
|
| 144 |
+
p=np.asarray(prob,float);k=max(1,int(p.size*.01));top=np.partition(p.ravel(),p.size-k)[-k:]
|
| 145 |
+
p2=np.clip(p,1e-6,1-1e-6)
|
| 146 |
+
return [float(p.max()),float(top.mean()),float(p.mean()),float(p.std()),float(mask.mean()),
|
| 147 |
+
float((-p2*np.log(p2)-(1-p2)*np.log(1-p2)).mean()),float(np.log1p(len(components(p,threshold))))]
|
| 148 |
+
|
| 149 |
+
def score_mask(pred,gt):
|
| 150 |
+
intersection=int(np.logical_and(pred,gt).sum());union_n=int(np.logical_or(pred,gt).sum())
|
| 151 |
+
return {'iou':intersection/union_n if union_n else 1.,'intersection':intersection,'union':union_n,
|
| 152 |
+
'pred_pixels':int(pred.sum()),'gt_pixels':int(gt.sum()),'empty':not bool(pred.any())}
|
source/code/prepare_d2.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build Detectron2 in the isolated R2 vendor directory on a Slurm CPU node."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import subprocess,urllib.request,zipfile,io,json,os,sysconfig,tarfile
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1];vendor=ROOT/'vendor'
|
| 5 |
+
url='https://download.pytorch.org/whl/cpu/torchvision-0.20.1%2Bcpu-cp39-cp39-linux_x86_64.whl'
|
| 6 |
+
if not (vendor/'torchvision').exists():
|
| 7 |
+
with urllib.request.urlopen(url,timeout=120) as r:blob=r.read()
|
| 8 |
+
zipfile.ZipFile(io.BytesIO(blob)).extractall(vendor)
|
| 9 |
+
print('TORCH_IMPORT',flush=True)
|
| 10 |
+
import torch
|
| 11 |
+
print('TORCH',torch.__version__,torch.cuda.is_available(),flush=True)
|
| 12 |
+
d2=ROOT/'third_party/detectron2-0.6'
|
| 13 |
+
if not (Path(sysconfig.get_path('include'))/'Python.h').exists():
|
| 14 |
+
headers=ROOT/'third_party/Python-3.9.16'
|
| 15 |
+
if not headers.exists():
|
| 16 |
+
with urllib.request.urlopen('https://www.python.org/ftp/python/3.9.16/Python-3.9.16.tgz',timeout=120) as r:blob=r.read()
|
| 17 |
+
with tarfile.open(fileobj=io.BytesIO(blob),mode='r:gz') as archive:archive.extractall(ROOT/'third_party')
|
| 18 |
+
if not (headers/'pyconfig.h').exists():
|
| 19 |
+
subprocess.run(['./configure','--without-ensurepip'],cwd=headers,check=True)
|
| 20 |
+
os.environ['CPATH']=str(headers/'Include')+':'+str(headers)+(':'+os.environ['CPATH'] if os.getenv('CPATH') else '')
|
| 21 |
+
subprocess.run(['python3','-m','pip','install','--target',str(vendor),'--no-deps','--no-build-isolation',str(d2)],check=True)
|
| 22 |
+
# Activate the official PyTorch fallback, which is already implemented in the
|
| 23 |
+
# unmodified MSDeformAttn.forward method. No parameter or numerical rule change.
|
| 24 |
+
repo=ROOT/'third_party/ReLA-3ca955198da8ace68f8980b6fcbada0791cc51c2'
|
| 25 |
+
p=repo/'gres_model/modeling/pixel_decoder/ops/functions/ms_deform_attn_func.py'
|
| 26 |
+
s=p.read_text();needle=' raise ModuleNotFoundError(info_string)'
|
| 27 |
+
if needle in s:p.write_text(s.replace(needle,' MSDA = None # R2: use the repository reference fallback'))
|
| 28 |
+
(ROOT/'protocol/rela_runtime_patch.json').write_text(json.dumps(dict(file=str(p.relative_to(ROOT)),change='Replace import-time error with MSDA=None; existing forward try/except invokes official grid_sample reference implementation',torch=torch.__version__,torchvision='0.20.1+cpu',slurm_job_id=os.getenv('SLURM_JOB_ID')),indent=2))
|
| 29 |
+
print('D2_BUILD_COMPLETE',flush=True)
|
source/code/prepare_full_natural.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Prepare every official gRefCOCO evaluation expression, without subsampling."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json, hashlib, collections, concurrent.futures, urllib.request, time, os
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from pycocotools import mask as cm
|
| 7 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 8 |
+
from project_paths import legacy_root;OLD=legacy_root(ROOT)
|
| 9 |
+
|
| 10 |
+
def main():
|
| 11 |
+
refs=json.loads((OLD/'assets/grefcoco/grefs(unc).json').read_text())
|
| 12 |
+
coco=json.loads((OLD/'assets/grefcoco/instances.json').read_text())
|
| 13 |
+
ims={x['id']:x for x in coco['images']}; anns={x['id']:x for x in coco['annotations']}
|
| 14 |
+
chosen=[r for r in refs if r['split'] in ('val','testA','testB')]
|
| 15 |
+
idir=ROOT/'data/natural/images';mdir=ROOT/'data/natural/masks'
|
| 16 |
+
idir.mkdir(parents=True,exist_ok=True);mdir.mkdir(parents=True,exist_ok=True)
|
| 17 |
+
image_ids=sorted({r['image_id'] for r in chosen})
|
| 18 |
+
def fetch(i):
|
| 19 |
+
name=ims[i]['file_name']; out=idir/name
|
| 20 |
+
if out.exists():return i,'cached'
|
| 21 |
+
candidates=[OLD/'data/natural/images'/name,OLD/'data/natural/images'/f'{i:012d}.jpg']
|
| 22 |
+
for p in candidates:
|
| 23 |
+
if p.exists():out.symlink_to(p);return i,'reused'
|
| 24 |
+
url='https://s3.amazonaws.com/images.cocodataset.org/train2014/'+name
|
| 25 |
+
for attempt in range(4):
|
| 26 |
+
try:
|
| 27 |
+
with urllib.request.urlopen(url,timeout=90) as response:blob=response.read()
|
| 28 |
+
tmp=out.with_suffix('.partial');tmp.write_bytes(blob)
|
| 29 |
+
with Image.open(tmp) as image:image.verify()
|
| 30 |
+
tmp.replace(out);return i,'downloaded'
|
| 31 |
+
except Exception:
|
| 32 |
+
if attempt==3:raise
|
| 33 |
+
time.sleep(2**attempt)
|
| 34 |
+
counts=collections.Counter()
|
| 35 |
+
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as pool:
|
| 36 |
+
for k,(iid,state) in enumerate(pool.map(fetch,image_ids)):
|
| 37 |
+
counts[state]+=1
|
| 38 |
+
if k%100==0:print('IMAGES',k,len(image_ids),dict(counts),flush=True)
|
| 39 |
+
rows=[]; strata=collections.Counter()
|
| 40 |
+
for r in chosen:
|
| 41 |
+
im=ims[r['image_id']];h,w=im['height'],im['width']; gt=np.zeros((h,w),bool)
|
| 42 |
+
aids=[] if r['no_target'] else r['ann_id']
|
| 43 |
+
if not isinstance(aids,list):aids=[aids]
|
| 44 |
+
for aid in aids:
|
| 45 |
+
seg=anns[aid]['segmentation']
|
| 46 |
+
if isinstance(seg,list):z=cm.decode(cm.frPyObjects(seg,h,w))
|
| 47 |
+
elif isinstance(seg['counts'],list):z=cm.decode(cm.frPyObjects(seg,h,w))
|
| 48 |
+
else:z=cm.decode(seg)
|
| 49 |
+
gt|=z.any(axis=2) if z.ndim==3 else z.astype(bool)
|
| 50 |
+
assert bool(gt.any())==bool(aids),(r['ref_id'],aids)
|
| 51 |
+
gp=mdir/f"ref_{r['ref_id']}.png";Image.fromarray(gt.astype('uint8')*255).save(gp)
|
| 52 |
+
for sentence in r['sentences']:
|
| 53 |
+
row=dict(id=f"gref_{r['ref_id']}_{sentence['sent_id']}",scene_id=f"coco_{r['image_id']}",image_id=r['image_id'],ref_id=r['ref_id'],sent_id=sentence['sent_id'],domain='natural_full',split=r['split'],mode='zero' if not aids else 'one' if len(aids)==1 else 'multi',target_count=len(aids),query=sentence['raw'],image_path=str((idir/im['file_name']).relative_to(ROOT)),gt_path=str(gp.relative_to(ROOT)),seed=0,corruption='clean',pair_id=None,endpoint=None,template='official')
|
| 54 |
+
rows.append(row);strata[(r['split'],row['mode'])]+=1
|
| 55 |
+
assert len(rows)==49492 and len({r['id'] for r in rows})==len(rows)
|
| 56 |
+
mp=ROOT/'data/natural_full.jsonl';mp.write_text(''.join(json.dumps(r)+'\n' for r in rows))
|
| 57 |
+
old_rows=[json.loads(s) for s in (OLD/'data/manifest.jsonl').read_text().splitlines()]
|
| 58 |
+
train_ids={int(r['scene_id'].split('_')[-1]) for r in old_rows if r['domain']=='natural' and r['split'] in ('fit','cal')}
|
| 59 |
+
overlap=sorted(train_ids&set(image_ids))
|
| 60 |
+
meta=dict(expressions=len(rows),references=len(chosen),images=len(image_ids),image_fetch=dict(counts),strata={f'{k[0]}/{k[1]}':v for k,v in strata.items()},manifest_sha256=hashlib.sha256(mp.read_bytes()).hexdigest(),old_calibration_image_overlap=overlap,source='FudanCVL/gRefCOCO; official repository-linked release',source_sha256={p.name:hashlib.sha256(p.read_bytes()).hexdigest() for p in [OLD/'assets/grefcoco/grefs(unc).json',OLD/'assets/grefcoco/instances.json']},slurm_job_id=os.getenv('SLURM_JOB_ID'))
|
| 61 |
+
(ROOT/'protocol/natural_full_manifest.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True)
|
| 62 |
+
if __name__=='__main__':main()
|
source/code/prepare_human_passes.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Split reader forms into ordered semantic/decomposition passes; merge complete labels."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse,csv
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 5 |
+
def read(p):
|
| 6 |
+
with p.open(newline='') as f:return list(csv.DictReader(f))
|
| 7 |
+
def write(p,rows,fields):
|
| 8 |
+
p.parent.mkdir(parents=True,exist_ok=True)
|
| 9 |
+
with p.open('w',newline='') as f:
|
| 10 |
+
w=csv.DictWriter(f,fieldnames=fields,extrasaction='ignore');w.writeheader();w.writerows(rows)
|
| 11 |
+
def main():
|
| 12 |
+
ap=argparse.ArgumentParser();ap.add_argument('--merge',choices=['A','B']);a=ap.parse_args()
|
| 13 |
+
home=ROOT/'review/human';dest=home/'passes'
|
| 14 |
+
for reader in ['A','B']:
|
| 15 |
+
original=home/f'parser_annotator_{reader}.csv';rows=read(original)
|
| 16 |
+
p1=dest/f'{reader}_pass1_semantics.csv';p2=dest/f'{reader}_pass2_decomposition.csv'
|
| 17 |
+
if not a.merge:
|
| 18 |
+
if p1.exists() or p2.exists():raise FileExistsError('Pass files already exist; preserve annotations.')
|
| 19 |
+
write(p1,rows,['id','query','representable','ambiguity','note'])
|
| 20 |
+
write(p2,rows,['id','query','proposed_target','proposed_anchor','proposed_relation','proposed_plural','decomposition_correct','error_type','note'])
|
| 21 |
+
elif a.merge==reader:
|
| 22 |
+
aa={r['id']:r for r in read(p1)};bb={r['id']:r for r in read(p2)}
|
| 23 |
+
assert aa.keys()==bb.keys()=={r['id'] for r in rows}
|
| 24 |
+
for r in rows:
|
| 25 |
+
x,y=aa[r['id']],bb[r['id']]
|
| 26 |
+
for k in ['representable','ambiguity']:
|
| 27 |
+
assert x[k] in ['0','1'],f'{r["id"]}: unresolved {k}';r[k]=x[k]
|
| 28 |
+
assert y['decomposition_correct'] in ['0','1'];r['decomposition_correct']=y['decomposition_correct']
|
| 29 |
+
r['error_type']=y['error_type'];r['note']='SEMANTICS: '+x['note']+'; DECOMPOSITION: '+y['note']
|
| 30 |
+
# Keep the supplied and independent source forms intact.
|
| 31 |
+
write(home/f'parser_annotator_{reader}_completed.csv',rows,list(rows[0]))
|
| 32 |
+
print('Prepared passes' if not a.merge else f'Merged completed reader {a.merge}')
|
| 33 |
+
if __name__=='__main__':main()
|
source/code/prepare_official_masks.py
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reproduce ReLA's 480x480 polygon-transform evaluation targets."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json,copy
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from pycocotools import mask as cm
|
| 7 |
+
ROOT=Path(__file__).resolve().parents[1];from project_paths import legacy_root;OLD=legacy_root(ROOT)
|
| 8 |
+
refs=json.loads((OLD/'assets/grefcoco/grefs(unc).json').read_text())
|
| 9 |
+
coco=json.loads((OLD/'assets/grefcoco/instances.json').read_text());ims={x['id']:x for x in coco['images']};anns={x['id']:x for x in coco['annotations']}
|
| 10 |
+
dest=ROOT/'data/natural/masks_official480';dest.mkdir(parents=True,exist_ok=True)
|
| 11 |
+
n=0
|
| 12 |
+
for r in refs:
|
| 13 |
+
if r['split'] not in ('val','testA','testB'):continue
|
| 14 |
+
gt=np.zeros((480,480),bool);im=ims[r['image_id']]
|
| 15 |
+
if not r['no_target']:
|
| 16 |
+
for aid in r['ann_id']:
|
| 17 |
+
if anns[aid].get('iscrowd',0):continue
|
| 18 |
+
seg=anns[aid]['segmentation'];assert isinstance(seg,list),'Official mapper expects polygons'
|
| 19 |
+
polys=[]
|
| 20 |
+
for polygon in seg:
|
| 21 |
+
p=np.asarray(polygon,float).reshape(-1,2);p[:,0]*=480/im['width'];p[:,1]*=480/im['height'];polys.append(p.ravel().tolist())
|
| 22 |
+
z=cm.decode(cm.frPyObjects(polys,480,480));gt|=z.any(axis=2)
|
| 23 |
+
Image.fromarray(gt.astype('uint8')*255).save(dest/f"ref_{r['ref_id']}.png");n+=1
|
| 24 |
+
print('OFFICIAL_MASKS_COMPLETE',n,flush=True)
|
source/code/prepare_rela.py
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Download official ReLA weights and isolated compatibility dependencies."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import json, subprocess, urllib.request, zipfile, io, hashlib, os, sys
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 5 |
+
def main():
|
| 6 |
+
vendor=ROOT/'vendor';vendor.mkdir(exist_ok=True)
|
| 7 |
+
sys.path.insert(0,str(vendor))
|
| 8 |
+
lock=json.loads((ROOT/'protocol/rela_reconstruction_lock.json').read_text())
|
| 9 |
+
(ROOT/'models').mkdir(exist_ok=True);(ROOT/'third_party').mkdir(exist_ok=True)
|
| 10 |
+
repo=ROOT/'third_party'/('ReLA-'+lock['rela_commit'])
|
| 11 |
+
if not repo.exists():
|
| 12 |
+
with urllib.request.urlopen('https://codeload.github.com/'+lock['rela_repository']+'/zip/'+lock['rela_commit'],timeout=120) as r:blob=r.read()
|
| 13 |
+
zipfile.ZipFile(io.BytesIO(blob)).extractall(ROOT/'third_party')
|
| 14 |
+
import importlib.util
|
| 15 |
+
for package,version in [('pip','25.2'),('setuptools','75.8.0'),('wheel','0.45.1')]:
|
| 16 |
+
if importlib.util.find_spec(package) is None:
|
| 17 |
+
with urllib.request.urlopen(f'https://pypi.org/pypi/{package}/{version}/json',timeout=60) as r:meta=json.load(r)
|
| 18 |
+
url=next(x['url'] for x in meta['urls'] if x['filename'].endswith('py3-none-any.whl'))
|
| 19 |
+
with urllib.request.urlopen(url,timeout=120) as r:blob=r.read()
|
| 20 |
+
zipfile.ZipFile(io.BytesIO(blob)).extractall(vendor)
|
| 21 |
+
packages=['gdown==5.2.0','timm==0.6.13','fvcore==0.1.5.post20221221','yacs==0.1.8','iopath==0.1.9','omegaconf==2.3.0','antlr4-python3-runtime==4.9.3','hydra-core==1.3.2','portalocker==2.10.1','termcolor==2.4.0','cloudpickle==3.0.0','tabulate==0.9.0','opencv-python-headless==4.10.0.84','shapely==2.0.6','h5py==3.11.0']
|
| 22 |
+
subprocess.run(['python3','-m','pip','install','--target',str(vendor),'--no-deps',*packages],check=True)
|
| 23 |
+
import gdown
|
| 24 |
+
target=ROOT/'models/gres_swin_tiny.pth'
|
| 25 |
+
if not target.exists() or target.stat().st_size!=650774639:
|
| 26 |
+
gdown.download(id='1VwX3BQy6gaF38P7YL6YeF2m0prgpO-IG',output=str(target),quiet=False)
|
| 27 |
+
assert target.stat().st_size==650774639
|
| 28 |
+
assert hashlib.sha256(target.read_bytes()).hexdigest()==lock['checkpoint_sha256'],'ReLA checkpoint mismatch'
|
| 29 |
+
bert=ROOT/'models/bert-base-uncased';bert.mkdir(exist_ok=True)
|
| 30 |
+
for f in ['config.json','vocab.txt','tokenizer_config.json','tokenizer.json','model.safetensors']:
|
| 31 |
+
p=bert/f
|
| 32 |
+
if not p.exists():urllib.request.urlretrieve('https://huggingface.co/google-bert/bert-base-uncased/resolve/main/'+f,str(p))
|
| 33 |
+
assert hashlib.sha256(p.read_bytes()).hexdigest()==lock['bert_files_sha256'][f],f+' differs from executed BERT asset; obtain the recorded version'
|
| 34 |
+
url='https://codeload.github.com/facebookresearch/detectron2/zip/refs/tags/v0.6'
|
| 35 |
+
d2=ROOT/'third_party/detectron2-0.6'
|
| 36 |
+
if not d2.exists():
|
| 37 |
+
with urllib.request.urlopen(url,timeout=120) as r:blob=r.read()
|
| 38 |
+
zipfile.ZipFile(io.BytesIO(blob)).extractall(ROOT/'third_party')
|
| 39 |
+
# CPU extension suffices for this architecture; MSDeformAttn uses the
|
| 40 |
+
# official repository's PyTorch reference implementation on the GPU.
|
| 41 |
+
if os.getenv('R2_BUILD_D2')=='1':
|
| 42 |
+
subprocess.run(['python3','-m','pip','install','--target',str(vendor),'--no-deps','--no-build-isolation',str(d2)],check=True)
|
| 43 |
+
meta=dict(checkpoint_file=target.name,checkpoint_sha256=hashlib.sha256(target.read_bytes()).hexdigest(),bytes=target.stat().st_size,official_drive_file_id='1VwX3BQy6gaF38P7YL6YeF2m0prgpO-IG',packages=packages,detectron2='v0.6',slurm_job_id=os.getenv('SLURM_JOB_ID'))
|
| 44 |
+
(ROOT/'protocol/rela_assets.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta,indent=2),flush=True)
|
| 45 |
+
if __name__=='__main__':main()
|
source/code/project_paths.py
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Resolve bundled legacy dependencies without hard-coded cluster paths."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import os
|
| 4 |
+
def legacy_root(root):
|
| 5 |
+
if os.getenv('REFSEG_LEGACY_ROOT'):return Path(os.environ['REFSEG_LEGACY_ROOT']).resolve()
|
| 6 |
+
root=Path(root)
|
| 7 |
+
for p in [root/'legacy_project',root.parent/'refseg_scale_20260906',root.parent/'RefSeg_Scale_MVA']:
|
| 8 |
+
if p.exists():return p
|
| 9 |
+
raise FileNotFoundError('Bundled legacy_project missing; set REFSEG_LEGACY_ROOT')
|
source/code/publish_hf_release.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Publish the user-authorized staged release to the Ethosoft organization."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse,hashlib,json,os,sys,zipfile
|
| 4 |
+
os.environ['HF_HUB_DISABLE_PROGRESS_BARS']='1'
|
| 5 |
+
from huggingface_hub import HfApi
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
+
REPO='Ethosoft/RefSeg-CA'
|
| 8 |
+
|
| 9 |
+
def main():
|
| 10 |
+
ap=argparse.ArgumentParser();ap.add_argument('--update-documents',action='store_true')
|
| 11 |
+
ap.add_argument('--publish-source',action='store_true');ap.add_argument('--release-tag');a=ap.parse_args()
|
| 12 |
+
source=ROOT/'release_public'
|
| 13 |
+
manifest=json.loads((source/'DATA_MANIFEST.json').read_text())
|
| 14 |
+
for name,meta in manifest['files'].items():
|
| 15 |
+
p=source/name;assert p.stat().st_size==meta['bytes']
|
| 16 |
+
assert hashlib.sha256(p.read_bytes()).hexdigest()==meta['sha256'],name
|
| 17 |
+
with zipfile.ZipFile(source/'release/RefSeg_CA_R3_Public_Source.zip') as z:assert z.testzip() is None
|
| 18 |
+
assert (source/'release/RefSeg_CA_MVA.pdf').read_bytes().startswith(b'%PDF')
|
| 19 |
+
api=HfApi();identity=api.whoami();assert identity['name']=='nmsofficial'
|
| 20 |
+
assert any(o['name']=='Ethosoft' for o in identity.get('orgs',[]))
|
| 21 |
+
print(json.dumps({'phase':'validated','repo':REPO,'files':len(manifest['files'])}),flush=True)
|
| 22 |
+
api.create_repo(REPO,repo_type='dataset',private=False,exist_ok=True)
|
| 23 |
+
kwargs={}
|
| 24 |
+
if a.update_documents:kwargs['allow_patterns']=['README.md','release/**']+(['source/**'] if a.publish_source else [])
|
| 25 |
+
commit=api.upload_folder(repo_id=REPO,repo_type='dataset',folder_path=source,
|
| 26 |
+
commit_message='R3 public code, data and manuscript' if not a.update_documents else 'Add verified public availability and human-evaluation guide',**kwargs)
|
| 27 |
+
tag=a.release_tag or ('r3-release-v1' if a.update_documents else 'r3-data-v1')
|
| 28 |
+
api.create_tag(REPO,tag=tag,repo_type='dataset',revision=commit.oid,exist_ok=True)
|
| 29 |
+
info=api.repo_info(REPO,repo_type='dataset');assert info.private is False
|
| 30 |
+
receipt=dict(status='PUBLISHED',repo_id=REPO,url='https://huggingface.co/datasets/'+REPO,commit=commit.oid,tag=tag,private=info.private,
|
| 31 |
+
files=len(api.list_repo_files(REPO,repo_type='dataset',revision=commit.oid)))
|
| 32 |
+
out=ROOT/'protocol'/('public_release_receipt.json' if a.update_documents else 'public_data_receipt.json')
|
| 33 |
+
out.write_text(json.dumps(receipt,indent=2));print(json.dumps(receipt),flush=True)
|
| 34 |
+
|
| 35 |
+
if __name__=='__main__':
|
| 36 |
+
try:main()
|
| 37 |
+
except Exception as e:
|
| 38 |
+
# Do not print credentials, request headers, environment, or full tracebacks.
|
| 39 |
+
print(json.dumps({'status':'FAILED','error_type':type(e).__name__,'http_status':getattr(getattr(e,'response',None),'status_code',None)}),flush=True)
|
| 40 |
+
sys.exit(1)
|
source/code/r2_repair.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Scope-filtered anchor projection. Frozen before R2 predictions.
|
| 2 |
+
|
| 3 |
+
The new primary rule removes the unhelpful counterfactual branch and refuses
|
| 4 |
+
clauses whose scope/cardinality cannot be represented by the original parser.
|
| 5 |
+
No test labels, images, or masks enter the syntax guard.
|
| 6 |
+
"""
|
| 7 |
+
import re
|
| 8 |
+
import phase1_repair as p1
|
| 9 |
+
FORBIDDEN=re.compile(r'\b(that|which|who|whose|with|wearing|holding|carrying|standing|sitting|looking|and|or|except|without|behind|between|nearest|closest|not|no)\b')
|
| 10 |
+
EXACT_COUNT=re.compile(r'\b(two|three|four|five|six|seven|eight|nine|ten|[2-9])\b')
|
| 11 |
+
def scope_safe(text):
|
| 12 |
+
q=p1.parse_query(text)
|
| 13 |
+
if q.negate:return True,'explicit_action'
|
| 14 |
+
if not q.supported:return False,'outside_grammar'
|
| 15 |
+
if EXACT_COUNT.search(q.original):return False,'exact_cardinality_unsupported'
|
| 16 |
+
clauses=[q.target]+([q.anchor] if q.anchor else [])
|
| 17 |
+
if any(FORBIDDEN.search(c) or len(c.split())>5 for c in clauses):return False,'nested_or_modified_clause'
|
| 18 |
+
if any(re.search(r'\b(left|right|above|below)\b',c) for c in clauses):return False,'nested_relation'
|
| 19 |
+
return True,'accepted'
|
| 20 |
+
def repair(text,maps,threshold):
|
| 21 |
+
preds,flags=p1.repaired_maps(text,maps,threshold)
|
| 22 |
+
safe,reason=scope_safe(text)
|
| 23 |
+
preds['safe_anchor']=preds['anchor_gate'] if safe else preds['frozen']
|
| 24 |
+
flags.update(scope_safe=safe,scope_reason=reason,cf_vs_anchor_changed=bool((preds['cacp']!=preds['anchor_gate']).any()),nogate_cf_changed=bool((preds['anchor_nogate']!=preds['counterfactual_nogate']).any()),safe_vs_frozen_changed=bool((preds['safe_anchor']!=preds['frozen']).any()))
|
| 25 |
+
return preds,flags
|
| 26 |
+
def primary_plan(text):
|
| 27 |
+
q=p1.parse_query(text);safe,_=scope_safe(text)
|
| 28 |
+
return list(dict.fromkeys([q.original]+([q.target,q.anchor] if safe and q.anchor else [q.target] if safe and not q.negate else [])))
|
| 29 |
+
|
| 30 |
+
def primary_mask(text,maps,threshold):
|
| 31 |
+
"""The primary rule alone, without computing any ablated branches."""
|
| 32 |
+
q=p1.parse_query(text);p=maps[q.original];base=p1.native(p,threshold)
|
| 33 |
+
if q.negate:return base & False
|
| 34 |
+
safe,_=scope_safe(text)
|
| 35 |
+
if not safe:return base
|
| 36 |
+
targets=p1.components(maps.get(q.target,p),threshold)
|
| 37 |
+
if not targets:return base
|
| 38 |
+
if q.relation.endswith('most'):return p1.global_component(targets,q.relation)['mask']
|
| 39 |
+
if not q.anchor:
|
| 40 |
+
if q.plural:return p1.union(targets,p.shape)
|
| 41 |
+
margin=targets[0]['confidence']-(targets[1]['confidence'] if len(targets)>1 else 0)
|
| 42 |
+
return base if margin<.05 else targets[0]['mask']
|
| 43 |
+
anchors=p1.components(maps[q.anchor],threshold)
|
| 44 |
+
if not anchors:return base
|
| 45 |
+
ac=anchors[0];margin=ac['confidence']-(anchors[1]['confidence'] if len(anchors)>1 else 0)
|
| 46 |
+
if margin<.05:return base
|
| 47 |
+
key='x' if q.relation in ('left','right') else 'y';sign=1 if q.relation in ('right','below') else -1
|
| 48 |
+
allowed=[c for c in targets if sign*(c[key]-ac[key])>=.03]
|
| 49 |
+
if not allowed:return base
|
| 50 |
+
margin=allowed[0]['confidence']-(allowed[1]['confidence'] if len(allowed)>1 else 0)
|
| 51 |
+
if not q.plural and margin<.05:return base
|
| 52 |
+
return p1.union(allowed if q.plural else [allowed[0]],p.shape)
|
source/code/r3_replay.py
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Reviewer-requested cache replay; no model fitting or additional language queries.
|
| 2 |
+
|
| 3 |
+
The R2 rule remains primary. All sweeps are post-review diagnostics. GT is used
|
| 4 |
+
only by score(), never by projection(). Each threshold sweep has a matched
|
| 5 |
+
native comparator. Rejected expressions contribute exactly zero paired delta.
|
| 6 |
+
"""
|
| 7 |
+
from pathlib import Path
|
| 8 |
+
import argparse, collections, hashlib, json, os, time
|
| 9 |
+
import numpy as np
|
| 10 |
+
from PIL import Image
|
| 11 |
+
from scipy import ndimage
|
| 12 |
+
import phase1_repair as p1
|
| 13 |
+
from r2_repair import scope_safe
|
| 14 |
+
|
| 15 |
+
ROOT=Path(os.getenv('REFSEG_ROOT',Path(__file__).resolve().parents[1]))
|
| 16 |
+
BASE=dict(anchor_margin=.05,target_margin=.05,geometry=.03,size_factor=1.,threshold_offset=0.)
|
| 17 |
+
CONFIGS={'primary':BASE.copy()}
|
| 18 |
+
for key,values in [('anchor_margin',[.02,.10]),('target_margin',[.02,.10]),('geometry',[.01,.05]),('size_factor',[.5,2.]),('threshold_offset',[-.05,.05])]:
|
| 19 |
+
for v in values:CONFIGS[key+'_'+str(v)]={**BASE,key:v}
|
| 20 |
+
|
| 21 |
+
def components(prob,t,factor):
|
| 22 |
+
lab,n=ndimage.label(prob>=t,structure=np.ones((3,3),int));h,w=prob.shape
|
| 23 |
+
sizes=np.bincount(lab.ravel());out=[];minimum=max(1,int(max(16,int(.0002*h*w))*factor))
|
| 24 |
+
for i,sl in enumerate(ndimage.find_objects(lab),1):
|
| 25 |
+
if sl is None or sizes[i]<minimum:continue
|
| 26 |
+
mask=lab==i;ys,xs=np.nonzero(mask)
|
| 27 |
+
out.append(dict(mask=mask,area=int(sizes[i]),x=float(xs.mean()/w),y=float(ys.mean()/h),confidence=float(prob[mask].mean())))
|
| 28 |
+
return sorted(out,key=lambda c:c['confidence'],reverse=True)
|
| 29 |
+
|
| 30 |
+
def projection(q,cs,shape,cfg):
|
| 31 |
+
base=p1.union(cs[q.original],shape);empty=np.zeros(shape,bool)
|
| 32 |
+
trace=dict(reason='fallback',plural=q.plural,relation=q.relation,anchor_margin=None,target_margin=None,boundary_distance=None)
|
| 33 |
+
def finish(m,why):trace['reason']=why;return m,trace
|
| 34 |
+
if q.negate:return finish(empty,'action')
|
| 35 |
+
ts=cs.get(q.target,cs[q.original]);trace['target_components']=len(ts)
|
| 36 |
+
if not ts:return finish(base,'target_missing')
|
| 37 |
+
if q.relation.endswith('most'):return finish(p1.global_component(ts,q.relation)['mask'],'extreme')
|
| 38 |
+
if not q.anchor:
|
| 39 |
+
if q.plural:return finish(p1.union(ts,shape),'plural')
|
| 40 |
+
tm=ts[0]['confidence']-(ts[1]['confidence'] if len(ts)>1 else 0);trace['target_margin']=tm
|
| 41 |
+
return finish(base,'target_ambiguous') if tm<cfg['target_margin'] else finish(ts[0]['mask'],'singular')
|
| 42 |
+
ac=cs[q.anchor];trace['anchor_components']=len(ac)
|
| 43 |
+
if not ac:return finish(base,'anchor_missing')
|
| 44 |
+
am=ac[0]['confidence']-(ac[1]['confidence'] if len(ac)>1 else 0);trace['anchor_margin']=am
|
| 45 |
+
if am<cfg['anchor_margin']:return finish(base,'anchor_ambiguous')
|
| 46 |
+
key='x' if q.relation in ('left','right') else 'y';sign=1 if q.relation in ('right','below') else -1
|
| 47 |
+
distances=[sign*(c[key]-ac[0][key]) for c in ts]
|
| 48 |
+
trace['boundary_distance']=min(abs(d-cfg['geometry']) for d in distances)
|
| 49 |
+
allowed=[c for c,d in zip(ts,distances) if d>=cfg['geometry']];trace['eligible_components']=len(allowed)
|
| 50 |
+
if not allowed:return finish(base,'relation_unsatisfied')
|
| 51 |
+
tm=allowed[0]['confidence']-(allowed[1]['confidence'] if len(allowed)>1 else 0);trace['target_margin']=tm
|
| 52 |
+
if not q.plural and tm<cfg['target_margin']:return finish(base,'assignment_ambiguous')
|
| 53 |
+
return finish(p1.union(allowed if q.plural else [allowed[0]],shape),'projected')
|
| 54 |
+
|
| 55 |
+
def score(pred,gt,is_nt):
|
| 56 |
+
op=np.asarray(Image.fromarray(pred).resize((480,480),Image.Resampling.NEAREST),bool)
|
| 57 |
+
inter=int((op>).sum());union=int((op|gt).sum());nt=not pred.any()
|
| 58 |
+
return dict(iou=float(nt) if is_nt else inter/union if union and not nt else 0.,intersection=inter if not is_nt else 0,union=0 if is_nt and nt else union,pred_nt=bool(nt))
|
| 59 |
+
|
| 60 |
+
def main():
|
| 61 |
+
ap=argparse.ArgumentParser();ap.add_argument('--model',choices=['clipseg','groundedsam'],required=True);ap.add_argument('--shard',type=int,default=0);ap.add_argument('--shards',type=int,default=16);ap.add_argument('--limit',type=int,default=0);a=ap.parse_args()
|
| 62 |
+
rows=[json.loads(s) for s in (ROOT/'data/natural_full.jsonl').read_text().splitlines()]
|
| 63 |
+
groups=collections.defaultdict(list)
|
| 64 |
+
for r in rows:groups[r['image_path']].append(r)
|
| 65 |
+
paths=[p for p in sorted(groups) if any(scope_safe(r['query'])[0] for r in groups[p])][a.shard::a.shards]
|
| 66 |
+
if a.limit:paths=paths[:a.limit]
|
| 67 |
+
dest=ROOT/'results/r3';dest.mkdir(parents=True,exist_ok=True)
|
| 68 |
+
name=f'{a.model}_{a.shard}of{a.shards}'+('_pilot' if a.limit else '')
|
| 69 |
+
output=dest/(name+'.jsonl');count=0;t0=time.time();native_t=.5 if a.model=='clipseg' else .25
|
| 70 |
+
with output.open('w') as out:
|
| 71 |
+
for idx,path in enumerate(paths):
|
| 72 |
+
group=groups[path];selected=[r for r in group if scope_safe(r['query'])[0]]
|
| 73 |
+
texts=list(dict.fromkeys(q for r in group for q in p1.query_plan(r['query'])[1]))
|
| 74 |
+
needed=set(q for r in selected for q in p1.query_plan(r['query'])[1]);maps={}
|
| 75 |
+
for start in range(0,len(texts),12):
|
| 76 |
+
batch=texts[start:start+12]
|
| 77 |
+
if not needed.intersection(batch):continue
|
| 78 |
+
digest=hashlib.sha256((path+'\n'+'\n'.join(batch)).encode()).hexdigest()[:24]
|
| 79 |
+
cp=ROOT/'cache'/a.model/(digest+'.npz')
|
| 80 |
+
with np.load(cp) as z:
|
| 81 |
+
assert z['texts'].tolist()==batch,(cp,'query mismatch')
|
| 82 |
+
maps.update({q:z[f'p{i}'].astype(np.float32) for i,q in enumerate(batch) if q in needed})
|
| 83 |
+
cc={};gtcache={}
|
| 84 |
+
for r in selected:
|
| 85 |
+
q=p1.parse_query(r['query']);keys=list(dict.fromkeys([q.original,q.target]+([q.anchor] if q.anchor else [])))
|
| 86 |
+
if r['ref_id'] not in gtcache:gtcache[r['ref_id']]=np.asarray(Image.open(ROOT/'data/natural/masks_official480'/f"ref_{r['ref_id']}.png"))>0
|
| 87 |
+
gt=gtcache[r['ref_id']];allres={};tr=None;primary_mask=None
|
| 88 |
+
for nameconf,cfg in CONFIGS.items():
|
| 89 |
+
threshold=native_t+cfg['threshold_offset'];cs={}
|
| 90 |
+
for key in keys:
|
| 91 |
+
ck=(key,threshold,cfg['size_factor'])
|
| 92 |
+
if ck not in cc:cc[ck]=components(maps[key],threshold,cfg['size_factor'])
|
| 93 |
+
cs[key]=cc[ck]
|
| 94 |
+
shape=maps[q.original].shape;base=p1.union(cs[q.original],shape)
|
| 95 |
+
pred,trace=projection(q,cs,shape,cfg)
|
| 96 |
+
allres[nameconf]=dict(frozen=score(base,gt,r['target_count']==0),sfap=score(pred,gt,r['target_count']==0),changed=bool((base!=pred).any()))
|
| 97 |
+
if nameconf=='primary':tr=trace;primary_mask=pred.copy()
|
| 98 |
+
else:allres[nameconf]['different_from_primary']=bool((primary_mask!=pred).any())
|
| 99 |
+
row={k:r[k] for k in ['id','scene_id','split','query','target_count']}
|
| 100 |
+
row.update(model=a.model,trace=tr,configs=allres)
|
| 101 |
+
out.write(json.dumps(row)+'\n');count+=1
|
| 102 |
+
out.flush()
|
| 103 |
+
if idx%10==0:print(json.dumps(dict(image=idx,images=len(paths),records=count,seconds=time.time()-t0)),flush=True)
|
| 104 |
+
meta=dict(status='COMPLETE',records=count,images=len(paths),seconds=time.time()-t0,args=vars(a),configs=CONFIGS,job_id=os.getenv('SLURM_JOB_ID'))
|
| 105 |
+
output.with_suffix('.meta.json').write_text(json.dumps(meta,indent=2));print(json.dumps(meta),flush=True)
|
| 106 |
+
if __name__=='__main__':main()
|
source/code/r3_summarize.py
ADDED
|
@@ -0,0 +1,97 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Coverage, sensitivity and harm diagnostics; exports portable exact score rows."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse,collections,csv,gzip,hashlib,json,os,tarfile
|
| 4 |
+
import numpy as np
|
| 5 |
+
import phase1_repair as p1
|
| 6 |
+
from r2_repair import scope_safe
|
| 7 |
+
ROOT=Path(os.getenv('REFSEG_ROOT',Path(__file__).resolve().parents[1]))
|
| 8 |
+
DEST=ROOT/'results/r3';DEST.mkdir(parents=True,exist_ok=True)
|
| 9 |
+
def read(p):
|
| 10 |
+
with (gzip.open(p,'rt') if str(p).endswith('.gz') else p.open()) as f:return [json.loads(x) for x in f]
|
| 11 |
+
def ci(rows,d):
|
| 12 |
+
groups=collections.defaultdict(lambda:[0.,0])
|
| 13 |
+
for r,x in zip(rows,d):g=groups[r['scene_id']];g[0]+=x;g[1]+=1
|
| 14 |
+
v=np.array(list(groups.values()));rng=np.random.default_rng(31073);vals=[]
|
| 15 |
+
for _ in range(2000):
|
| 16 |
+
z=v[rng.integers(0,len(v),len(v))];vals.append(z[:,0].sum()/z[:,1].sum())
|
| 17 |
+
return np.quantile(vals,[.025,.975]).tolist()
|
| 18 |
+
def compare(rows,d):
|
| 19 |
+
d=np.array(d);return dict(n=len(d),delta=float(d.mean()),ci=ci(rows,d),helped=int((d>1e-12).sum()),harmed=int((d< -1e-12).sum()),tied=int((abs(d)<=1e-12).sum()))
|
| 20 |
+
def predicate(q,safe,level):
|
| 21 |
+
if level=='short_relations':return safe and bool(q.anchor) and max(len(q.target.split()),len(q.anchor.split()))<=3
|
| 22 |
+
if level=='relations':return safe and bool(q.anchor)
|
| 23 |
+
return safe if level=='primary' else q.supported
|
| 24 |
+
def main():
|
| 25 |
+
ap=argparse.ArgumentParser();ap.add_argument('--export-only',action='store_true');a=ap.parse_args()
|
| 26 |
+
result={};native={}
|
| 27 |
+
for model in ['clipseg','groundedsam']:
|
| 28 |
+
rows=read(ROOT/'results/analysis'/('natural_'+model+'_evaluated.jsonl.gz'));native[model]=rows
|
| 29 |
+
coverage=[]
|
| 30 |
+
for level in ['short_relations','relations','primary','legacy']:
|
| 31 |
+
accepted=[predicate(p1.parse_query(r['query']),scope_safe(r['query'])[0],level) for r in rows]
|
| 32 |
+
d=[r['official480_scores']['anchor_gate']['iou']-r['official480_scores']['frozen']['iou'] if yes else 0. for r,yes in zip(rows,accepted)]
|
| 33 |
+
z=compare(rows,d);z.update(scope=level,accepted=sum(accepted),coverage=sum(accepted)/len(rows),conditional_delta=sum(d)/sum(accepted),gIoU=float(np.mean([r['official480_scores']['frozen']['iou'] for r in rows]))+z['delta'])
|
| 34 |
+
z['accepted_tied']=sum(accepted)-z['helped']-z['harmed'];coverage.append(z)
|
| 35 |
+
result[model]=dict(coverage=coverage)
|
| 36 |
+
(DEST/'coverage.json').write_text(json.dumps(result,indent=2))
|
| 37 |
+
if not a.export_only:
|
| 38 |
+
for model,rows in native.items():
|
| 39 |
+
paths=[DEST/f'{model}_{i}of16.jsonl' for i in range(16)]
|
| 40 |
+
assert all(p.with_suffix('.meta.json').exists() for p in paths),'incomplete replay shards'
|
| 41 |
+
replay=[r for p in paths for r in read(p)];assert len(replay)==1557 and len({r['id'] for r in replay})==1557
|
| 42 |
+
orig={r['id']:r for r in rows};byid={r['id']:r for r in replay}
|
| 43 |
+
maxerr=0.
|
| 44 |
+
for r in replay:
|
| 45 |
+
for k,v in [('frozen','frozen'),('sfap','safe_anchor')]:
|
| 46 |
+
maxerr=max(maxerr,abs(r['configs']['primary'][k]['iou']-orig[r['id']]['official480_scores'][v]['iou']))
|
| 47 |
+
assert maxerr<1e-12,('primary replay mismatch',model,maxerr)
|
| 48 |
+
sensitivity=[]
|
| 49 |
+
for c in replay[0]['configs']:
|
| 50 |
+
dd={r['id']:r['configs'][c]['sfap']['iou']-r['configs'][c]['frozen']['iou'] for r in replay}
|
| 51 |
+
full=[dd.get(r['id'],0.) for r in rows];z=compare(rows,full);z.update(config=c,accepted=1557,conditional_delta=sum(full)/1557)
|
| 52 |
+
z['changed']=sum(r['configs'][c]['changed'] for r in replay);sensitivity.append(z)
|
| 53 |
+
harm=[r for r in replay if r['configs']['primary']['sfap']['iou']<r['configs']['primary']['frozen']['iou']-1e-12]
|
| 54 |
+
before=lambda r:r['configs']['primary']['frozen']['iou'];after=lambda r:r['configs']['primary']['sfap']['iou']
|
| 55 |
+
metrics=dict(accepted=1557,harmed=len(harm),harm_fraction_accepted=len(harm)/1557,mean_loss=float(np.mean([before(r)-after(r) for r in harm])),sum_loss=sum(before(r)-after(r) for r in harm),already_correct=sum(before(r)>=.5 for r in harm),correct_to_incorrect=sum(before(r)>=.5 and after(r)<.5 for r in harm),to_empty=sum(r['target_count']>0 and r['configs']['primary']['sfap']['pred_nt'] for r in harm),empty_gt_harmed=sum(r['target_count']==0 for r in harm),plural_flag_mismatch=sum(r['target_count']>1 and not p1.parse_query(r['query']).plural for r in harm),relation_cases=sum(bool(r['trace']['relation']) for r in harm),anchor_cases=sum(bool(p1.parse_query(r['query']).anchor) for r in harm),boundary_sensitive=sum(any(r['configs'][c].get('different_from_primary') for c in ['geometry_0.01','geometry_0.05']) for r in harm),component_filter_sensitive=sum(any(r['configs'][c].get('different_from_primary') for c in ['size_factor_0.5','size_factor_2.0']) for r in harm),threshold_sensitive=sum(any(r['configs'][c].get('different_from_primary') for c in ['threshold_offset_-0.05','threshold_offset_0.05']) for r in harm),reason_counts=dict(collections.Counter(r['trace']['reason'] for r in harm)))
|
| 56 |
+
result[model].update(sensitivity=sensitivity,harm=metrics,primary_replay_max_error=maxerr)
|
| 57 |
+
with gzip.open(DEST/f'{model}_replay.jsonl.gz','wt') as f:
|
| 58 |
+
for r in replay:f.write(json.dumps(r)+'\n')
|
| 59 |
+
cases=sorted(harm,key=lambda r:hashlib.sha256(r['id'].encode()).hexdigest())[:60]
|
| 60 |
+
with (DEST/f'{model}_harm_annotation.csv').open('w',newline='') as f:
|
| 61 |
+
w=csv.writer(f);w.writerow(['id','query','image_id','baseline_iou','sfap_iou','anchor_grounding_error','target_decomposition_error','merged_components','relation_boundary_error','plurality_error','other','evidence_note'])
|
| 62 |
+
for r in cases:w.writerow([r['id'],r['query'],r['scene_id'].split('_')[-1],before(r),after(r)]+['']*7)
|
| 63 |
+
(DEST/'review_results.json').write_text(json.dumps(result,indent=2))
|
| 64 |
+
# Portable primary-record tables contain the exact float and integer scores.
|
| 65 |
+
portable=DEST/'portable';portable.mkdir(exist_ok=True)
|
| 66 |
+
for dataset in ['natural','rich']:
|
| 67 |
+
for model in ['clipseg','groundedsam','rela']:
|
| 68 |
+
rows=read(ROOT/'results/analysis'/f'{dataset}_{model}_evaluated.jsonl.gz')
|
| 69 |
+
key='official480_scores' if dataset=='natural' else 'scores'
|
| 70 |
+
variants=['frozen'] if model=='rela' else ['frozen','safe_anchor' if dataset=='natural' else 'anchor_gate']
|
| 71 |
+
dest=portable/f'{dataset}_{model}_primary.csv.gz'
|
| 72 |
+
with gzip.open(dest,'wt',newline='') as f:
|
| 73 |
+
w=csv.writer(f);w.writerow(['id','scene_id','split','seed','corruption','pair_id','endpoint','template','mode','target_count','variant','iou','intersection','union','pred_nt'])
|
| 74 |
+
for r in rows:
|
| 75 |
+
for v in variants:
|
| 76 |
+
z=r[key][v];w.writerow([r.get(k,'') for k in ['id','scene_id','split','seed','corruption','pair_id','endpoint','template','mode','target_count']]+[v,z['iou'],z['intersection'],z['union'],int(z.get('pred_nt',z['empty']))])
|
| 77 |
+
# Stratified audit; reviewers see query and proposal but not acceptance/outcome.
|
| 78 |
+
manifest=read(ROOT/'data/natural_full.jsonl');strata=collections.defaultdict(list)
|
| 79 |
+
for r in manifest:
|
| 80 |
+
q=p1.parse_query(r['query']);safe=scope_safe(r['query'])[0];strata['accepted' if safe else 'legacy_rejected' if q.supported else 'outside'].append(r)
|
| 81 |
+
rng=np.random.default_rng(913);sample=[];keyrows=[]
|
| 82 |
+
for name,rs in strata.items():
|
| 83 |
+
chosen=rng.choice(len(rs),200,replace=False)
|
| 84 |
+
for j in chosen:
|
| 85 |
+
r=rs[j];q=p1.parse_query(r['query']);keyrows.append(dict(id=r['id'],stratum=name,N=len(rs),n=200,weight=len(rs)/200,accepted=scope_safe(r['query'])[0]))
|
| 86 |
+
sample.append([r['id'],r['query'],r['image_id'],q.target,q.anchor,q.relation,int(q.plural)]+['']*5)
|
| 87 |
+
rng.shuffle(sample)
|
| 88 |
+
for who in ['A','B']:
|
| 89 |
+
with (portable/f'parser_annotator_{who}.csv').open('w',newline='') as f:
|
| 90 |
+
w=csv.writer(f);w.writerow(['id','query','image_id','proposed_target','proposed_anchor','proposed_relation','proposed_plural','representable','decomposition_correct','ambiguity','error_type','note']);w.writerows(sample)
|
| 91 |
+
(portable/'parser_sampling_key.json').write_text(json.dumps(keyrows,indent=2))
|
| 92 |
+
with gzip.open(portable/'natural_full_manifest.jsonl.gz','wt') as f:
|
| 93 |
+
for r in manifest:f.write(json.dumps(r)+'\n')
|
| 94 |
+
archive=DEST/'portable_primary_results.tar.gz'
|
| 95 |
+
with tarfile.open(archive,'w:gz',compresslevel=9) as tar:tar.add(portable,arcname='portable')
|
| 96 |
+
print(json.dumps(dict(archive=str(archive),bytes=archive.stat().st_size,sha256=hashlib.sha256(archive.read_bytes()).hexdigest())),flush=True)
|
| 97 |
+
if __name__=='__main__':main()
|
source/code/rela_engine.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Official ReLA Swin-Tiny architecture and trained checkpoint adapter."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys,json,os
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 7 |
+
class ReLA:
|
| 8 |
+
threshold=.5
|
| 9 |
+
def __init__(self,device='cuda'):
|
| 10 |
+
import torch
|
| 11 |
+
self.torch=torch;self.device=device
|
| 12 |
+
repo=ROOT/'third_party/ReLA-3ca955198da8ace68f8980b6fcbada0791cc51c2';sys.path.insert(0,str(repo))
|
| 13 |
+
if not hasattr(Image, "LINEAR"):Image.LINEAR=Image.Resampling.BILINEAR
|
| 14 |
+
from detectron2.config import get_cfg
|
| 15 |
+
from detectron2.modeling import build_model
|
| 16 |
+
from detectron2.data import transforms as T
|
| 17 |
+
from gres_model import add_maskformer2_config,add_refcoco_config
|
| 18 |
+
from transformers import BertTokenizer
|
| 19 |
+
from detectron2.projects.deeplab import add_deeplab_config
|
| 20 |
+
cfg=get_cfg();add_deeplab_config(cfg);add_maskformer2_config(cfg);add_refcoco_config(cfg)
|
| 21 |
+
cfg.merge_from_file(str(repo/'configs/referring_swin_tiny.yaml'))
|
| 22 |
+
cfg.MODEL.DEVICE=device;cfg.REFERRING.BERT_TYPE=str(ROOT/'models/bert-base-uncased')
|
| 23 |
+
self.model=build_model(cfg).eval()
|
| 24 |
+
checkpoint=torch.load(ROOT/'models/gres_swin_tiny.pth',map_location='cpu',weights_only=False)
|
| 25 |
+
state=checkpoint['model'] if 'model' in checkpoint else checkpoint
|
| 26 |
+
key='text_encoder.embeddings.position_ids'
|
| 27 |
+
if key in state:
|
| 28 |
+
assert torch.equal(state[key],self.model.text_encoder.embeddings.position_ids.cpu())
|
| 29 |
+
state.pop(key) # Identical deterministic buffer is nonpersistent in current Transformers.
|
| 30 |
+
incompat=self.model.load_state_dict(state,strict=True)
|
| 31 |
+
self.model.to(device);self.tokenizer=BertTokenizer.from_pretrained(cfg.REFERRING.BERT_TYPE,local_files_only=True)
|
| 32 |
+
self.max_tokens=cfg.REFERRING.MAX_TOKENS;self.size=cfg.INPUT.IMAGE_SIZE
|
| 33 |
+
self.resize=T.Resize((self.size,self.size))
|
| 34 |
+
print('RELA_STRICT_LOAD_OK',len(state),self.size,self.max_tokens,str(incompat),flush=True)
|
| 35 |
+
def predict(self,image,texts):
|
| 36 |
+
t=self.torch;arr=np.array(image);resized=self.resize.get_transform(arr).apply_image(arr)
|
| 37 |
+
rgb=t.as_tensor(np.ascontiguousarray(resized.transpose(2,0,1)))
|
| 38 |
+
out={};nt={};official={}
|
| 39 |
+
with t.inference_mode():
|
| 40 |
+
for start in range(0,len(texts),2):
|
| 41 |
+
batch=texts[start:start+2];inputs=[]
|
| 42 |
+
for q in batch:
|
| 43 |
+
ids=self.tokenizer.encode(text=q,add_special_tokens=True)[:self.max_tokens]
|
| 44 |
+
padding=[0]*(self.max_tokens-len(ids))
|
| 45 |
+
inputs.append(dict(image=rgb,lang_tokens=t.tensor(ids+padding).unsqueeze(0),lang_mask=t.tensor([1]*len(ids)+padding).unsqueeze(0)))
|
| 46 |
+
outputs=self.model(inputs)
|
| 47 |
+
for q,p in zip(batch,outputs):
|
| 48 |
+
official[q]=p['ref_seg'].argmax(dim=0).bool().cpu().numpy()
|
| 49 |
+
nt[q]=bool(p['nt_label'].argmax(dim=0).item())
|
| 50 |
+
# Monotone foreground/background margin for the optional
|
| 51 |
+
# shared repair interface. Native scores use exact argmax.
|
| 52 |
+
margin=(p['ref_seg'][1]-p['ref_seg'][0]+1)/2
|
| 53 |
+
out[q]=t.nn.functional.interpolate(margin[None,None],size=(image.height,image.width),mode='bilinear',align_corners=False)[0,0].float().cpu().numpy()
|
| 54 |
+
return out,dict(language_queries=len(texts),nt=nt,official_masks=official,sam_boxes=0,truncated_boxes=0)
|
| 55 |
+
|
| 56 |
+
if __name__=='__main__':
|
| 57 |
+
import torch
|
| 58 |
+
torch.set_num_threads(4)
|
| 59 |
+
engine=ReLA(device=os.getenv('R2_DEVICE','cuda'))
|
| 60 |
+
old=ROOT.parent/'refseg_scale_20260906'
|
| 61 |
+
row=next(json.loads(s) for s in (old/'data/manifest.jsonl').read_text().splitlines() if json.loads(s)['domain']=='natural' and json.loads(s)['split']=='fit')
|
| 62 |
+
image=Image.open(old/row['image_path']).convert('RGB')
|
| 63 |
+
maps,stats=engine.predict(image,[row['query']])
|
| 64 |
+
print('RELA_PILOT_OK',image.size,row['query'],{q:dict(shape=v.shape,min=float(v.min()),max=float(v.max())) for q,v in maps.items()},stats['nt'],flush=True)
|
source/code/score_human_parser_audit.py
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Score only complete independent human labels; never fill missing labels."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import argparse,csv,json,collections
|
| 4 |
+
FIELDS=['representable','decomposition_correct','ambiguity']
|
| 5 |
+
def read(p):
|
| 6 |
+
with Path(p).open(newline='') as f:rows=list(csv.DictReader(f))
|
| 7 |
+
assert len({r['id'] for r in rows})==len(rows),'duplicate ids'
|
| 8 |
+
return {r['id']:r for r in rows}
|
| 9 |
+
def main():
|
| 10 |
+
a=argparse.ArgumentParser();a.add_argument('--a',required=True);a.add_argument('--b',required=True);a.add_argument('--key',required=True);a.add_argument('--adjudicated');a.add_argument('--output',required=True);p=a.parse_args()
|
| 11 |
+
aa,bb=read(p.a),read(p.b);key={r['id']:r for r in json.loads(Path(p.key).read_text())}
|
| 12 |
+
assert aa.keys()==bb.keys()==key.keys(),'unaligned forms'
|
| 13 |
+
missing=[(i,f) for i in key for f in FIELDS if aa[i][f] not in ['0','1'] or bb[i][f] not in ['0','1']]
|
| 14 |
+
if missing:
|
| 15 |
+
report=dict(status='INCOMPLETE',items=len(key),missing_or_unresolved_fields=len(missing),reason='Human 0/1 labels required; no statistics estimated.')
|
| 16 |
+
else:
|
| 17 |
+
agreement={}
|
| 18 |
+
for field in FIELDS:
|
| 19 |
+
x=[int(aa[i][field]) for i in key];y=[int(bb[i][field]) for i in key];n=len(x);po=sum(a==b for a,b in zip(x,y))/n;px=sum(x)/n;py=sum(y)/n;pe=px*py+(1-px)*(1-py)
|
| 20 |
+
agreement[field]=dict(raw_agreement=po,kappa=(po-pe)/(1-pe) if pe<1 else None,scope='unweighted stratified audit sample')
|
| 21 |
+
disagreements=[i for i in key if any(aa[i][f]!=bb[i][f] for f in FIELDS)]
|
| 22 |
+
report=dict(status='AWAITING_ADJUDICATION',agreement=agreement,disagreement_ids=disagreements)
|
| 23 |
+
if p.adjudicated:
|
| 24 |
+
gold=read(p.adjudicated);assert gold.keys()==key.keys()
|
| 25 |
+
assert all(gold[i][f] in ['0','1'] for i in key for f in FIELDS),'unresolved adjudication'
|
| 26 |
+
counts=collections.defaultdict(float)
|
| 27 |
+
for i,k in key.items():
|
| 28 |
+
pred=bool(k['accepted']);truth=gold[i]['representable']=='1';weight=k['weight'];counts[('T' if pred==truth else 'F')+('P' if pred else 'N')]+=weight
|
| 29 |
+
tp,fp,tn,fn=[counts[k] for k in ['TP','FP','TN','FN']]
|
| 30 |
+
ratio=lambda a,b:a/b if b else None
|
| 31 |
+
report.update(status='COMPLETE',weighted_counts=dict(counts),precision=ratio(tp,tp+fp),recall=ratio(tp,tp+fn),false_acceptance_rate=ratio(fp,fp+tn),false_rejection_rate=ratio(fn,tp+fn),target='semantic representability under documented grammar',decomposition_precision_among_accepted=ratio(sum(key[i]['weight'] for i in key if key[i]['accepted'] and gold[i]['decomposition_correct']=='1'),sum(key[i]['weight'] for i in key if key[i]['accepted'])))
|
| 32 |
+
Path(p.output).write_text(json.dumps(report,indent=2));print(json.dumps(report,indent=2))
|
| 33 |
+
if __name__=='__main__':main()
|
source/code/timing_r2.py
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Paired warmed latency, same images/GPU, balanced plan order, no GT use."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import sys,json,time,os
|
| 4 |
+
import numpy as np
|
| 5 |
+
from PIL import Image
|
| 6 |
+
ROOT=Path(__file__).resolve().parents[1];from project_paths import legacy_root;OLD=legacy_root(ROOT);sys.path.insert(0,str(OLD/'code'))
|
| 7 |
+
from infer import ClipSeg,GroundedSam
|
| 8 |
+
import phase1_repair as p
|
| 9 |
+
from r2_repair import primary_plan,primary_mask,repair
|
| 10 |
+
import torch
|
| 11 |
+
torch.set_num_threads(4)
|
| 12 |
+
rows=[json.loads(s) for s in (ROOT/'data/rich_synthetic.jsonl').read_text().splitlines()]
|
| 13 |
+
chosen=[r for r in rows if r['render']=='rich' and r['mode']=='relational' and r['endpoint']==0][:12]
|
| 14 |
+
output=[]
|
| 15 |
+
for model,cls in [('clipseg',ClipSeg),('groundedsam',GroundedSam)]:
|
| 16 |
+
engine=cls()
|
| 17 |
+
image=Image.open(ROOT/chosen[0]['image_path']).convert('RGB');q=p.parse_query(chosen[0]['query']);engine.predict(image,p.query_plan(chosen[0]['query'])[1]);torch.cuda.synchronize()
|
| 18 |
+
for i,r in enumerate(chosen):
|
| 19 |
+
image=Image.open(ROOT/r['image_path']).convert('RGB');q=p.parse_query(r['query'])
|
| 20 |
+
plans={'frozen':[q.original],'sfap':primary_plan(r['query']),'cacp':p.query_plan(r['query'])[1]}
|
| 21 |
+
for rep in range(3):
|
| 22 |
+
order=['frozen','sfap','cacp'];shift=(i+rep)%3;order=order[shift:]+order[:shift]
|
| 23 |
+
for variant in order:
|
| 24 |
+
torch.cuda.synchronize();start=time.perf_counter();maps,stats=engine.predict(image,plans[variant]);torch.cuda.synchronize();forward=time.perf_counter()-start
|
| 25 |
+
maps={k:v.astype(np.float16).astype(np.float32) for k,v in maps.items()}
|
| 26 |
+
start=time.perf_counter()
|
| 27 |
+
if variant=='frozen':mask=p.native(maps[q.original],engine.threshold)
|
| 28 |
+
elif variant=='sfap':mask=primary_mask(r['query'],maps,engine.threshold)
|
| 29 |
+
else:mask=repair(r['query'],maps,engine.threshold)[0]['cacp']
|
| 30 |
+
cpu=time.perf_counter()-start
|
| 31 |
+
if variant=='cacp':assert np.array_equal(primary_mask(r['query'],maps,engine.threshold),repair(r['query'],maps,engine.threshold)[0]['safe_anchor'])
|
| 32 |
+
output.append(dict(model=model,image=r['image_path'],scene_id=r['scene_id'],repeat=rep,order=order,variant=variant,queries=len(plans[variant]),forward_seconds=forward,postprocess_seconds=cpu,total_seconds=forward+cpu))
|
| 33 |
+
print('TIMING',model,i+1,len(chosen),flush=True)
|
| 34 |
+
del engine;torch.cuda.empty_cache()
|
| 35 |
+
dest=ROOT/'results/paired_timing.json';dest.write_text(json.dumps(dict(gpu=torch.cuda.get_device_name(0),slurm_job_id=os.getenv('SLURM_JOB_ID'),records=output,warmup='One complete four-query plan per model before timing',cache='Disabled',repeats=3,selection='First twelve rich relational scene records, text/ID selection; no label or score selection'),indent=2))
|
| 36 |
+
print('PAIRED_TIMING_COMPLETE',flush=True)
|
source/code/verify_portable_results.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Rebuild primary paper metrics from shipped per-record scores, without TRUBA."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import csv,gzip,json,math,collections
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 5 |
+
def describe(rows):
|
| 6 |
+
pos=[r for r in rows if int(r['target_count'])>0];neg=[r for r in rows if int(r['target_count'])==0]
|
| 7 |
+
mean=lambda xs:sum(xs)/len(xs) if xs else None
|
| 8 |
+
return dict(n=len(rows),gIoU=mean([float(r['iou']) for r in rows]),cIoU=sum(int(r['intersection']) for r in rows)/max(1,sum(int(r['union']) for r in rows)),positive_mIoU=mean([float(r['iou']) for r in pos]),Nacc=mean([int(r['pred_nt']) for r in neg]),false_empty=mean([int(r['pred_nt']) for r in pos]),Pr50=mean([float(r['iou'])>=.5 for r in pos]))
|
| 9 |
+
def main():
|
| 10 |
+
expected=json.loads((ROOT/'results/analysis/paper_results.json').read_text());reports=[];maxerr=0.
|
| 11 |
+
for dataset in ['natural','rich']:
|
| 12 |
+
for model in ['clipseg','groundedsam','rela']:
|
| 13 |
+
p=ROOT/'results/r3/portable'/f'{dataset}_{model}_primary.csv.gz'
|
| 14 |
+
with gzip.open(p,'rt') as f:allrows=list(csv.DictReader(f))
|
| 15 |
+
for e in expected[dataset][model]['tables']:
|
| 16 |
+
if e['variant'] not in ['frozen','safe_anchor']:continue
|
| 17 |
+
variant='anchor_gate' if dataset=='rich' and e['variant']=='safe_anchor' else e['variant']
|
| 18 |
+
rows=[r for r in allrows if r['variant']==variant]
|
| 19 |
+
if dataset=='natural':rows=[r for r in rows if e['split']=='all' or r['split']==e['split']]
|
| 20 |
+
else:rows=[r for r in rows if r['corruption']==e['render'] and r['mode'] in ['attribute','relational','multi_target','empty_target']]
|
| 21 |
+
assert len(rows)==e['n'],(dataset,model,variant,len(rows),e['n'])
|
| 22 |
+
z=describe(rows)
|
| 23 |
+
if dataset=='rich':
|
| 24 |
+
pairs=collections.defaultdict(list)
|
| 25 |
+
for r in rows:pairs[r['pair_id']].append(float(r['iou']))
|
| 26 |
+
assert all(len(v)==2 for v in pairs.values())
|
| 27 |
+
z['PC50']=sum(all(x>=.5 for x in v) for v in pairs.values())/len(pairs)
|
| 28 |
+
for k,v in z.items():
|
| 29 |
+
if k in e and v is not None:
|
| 30 |
+
err=abs(v-e[k]);maxerr=max(maxerr,err);assert err<1e-10,(dataset,model,variant,k,v,e[k])
|
| 31 |
+
reports.append(dict(dataset=dataset,model=model,variant=e['variant'],split=e.get('split',e.get('render')),**z))
|
| 32 |
+
# Exact primary replay and every sensitivity mean from shipped trace records.
|
| 33 |
+
summaries=json.loads((ROOT/'results/r3/review_results.json').read_text())
|
| 34 |
+
for model in ['clipseg','groundedsam']:
|
| 35 |
+
with gzip.open(ROOT/'results/r3'/f'{model}_replay.jsonl.gz','rt') as f:rows=[json.loads(s) for s in f]
|
| 36 |
+
assert len(rows)==1557
|
| 37 |
+
for e in summaries[model]['sensitivity']:
|
| 38 |
+
d=[r['configs'][e['config']]['sfap']['iou']-r['configs'][e['config']]['frozen']['iou'] for r in rows]
|
| 39 |
+
assert abs(sum(d)/49492-e['delta'])<1e-12
|
| 40 |
+
assert sum(v< -1e-12 for v in d)==e['harmed']
|
| 41 |
+
report=dict(status='PASS',metric_rows=len(reports),max_absolute_error=maxerr,primary_tables=reports,sensitivity_settings_replayed=22)
|
| 42 |
+
out=ROOT/'results/r3/portable_verification.json';out.write_text(json.dumps(report,indent=2))
|
| 43 |
+
print(json.dumps({k:v for k,v in report.items() if k!='primary_tables'},indent=2))
|
| 44 |
+
if __name__=='__main__':main()
|
source/code/verify_rela_metrics.py
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Independent reproduction of the released ReLA evaluator equations."""
|
| 2 |
+
from pathlib import Path
|
| 3 |
+
import gzip,json,math
|
| 4 |
+
ROOT=Path(__file__).resolve().parents[1]
|
| 5 |
+
def official(rows):
|
| 6 |
+
si=su=sg=0.;n=ntn=ntok=pos=fe=pr50=0
|
| 7 |
+
for r in rows:
|
| 8 |
+
z=r['official480_scores']['frozen'];gt_nt=r['target_count']==0
|
| 9 |
+
pred_nt=bool(z.get('pred_nt',z['empty']))
|
| 10 |
+
n+=1
|
| 11 |
+
if gt_nt:
|
| 12 |
+
ntn+=1;ntok+=pred_nt;sg+=float(pred_nt)
|
| 13 |
+
if not pred_nt:su+=z['union']
|
| 14 |
+
else:
|
| 15 |
+
pos+=1;fe+=pred_nt
|
| 16 |
+
i=0 if pred_nt else z['intersection'];u=z['union']
|
| 17 |
+
si+=i;su+=u;sg+=0 if u==0 else i/u;pr50+=(0 if u==0 else i/u)>=.5
|
| 18 |
+
return dict(n=n,gIoU=sg/n,cIoU=si/su,Nacc=ntok/ntn,
|
| 19 |
+
positive_mIoU=(sg-(ntok))/pos,false_empty=fe/pos,Pr50=pr50/pos)
|
| 20 |
+
def fixtures():
|
| 21 |
+
# (gt_nt,pred_nt,I,U) includes both no-target branches and positive errors.
|
| 22 |
+
cases=[(1,1,0,0),(1,0,0,9),(0,0,5,10),(0,1,7,10),(0,0,0,0),(0,0,9,9)]
|
| 23 |
+
sg=si=su=0
|
| 24 |
+
for gt,nt,i,u in cases:
|
| 25 |
+
if gt:sg+=nt;su+=0 if nt else u
|
| 26 |
+
else:
|
| 27 |
+
i=0 if nt else i;sg+=0 if u==0 else i/u;si+=i;su+=u
|
| 28 |
+
assert math.isclose(sg/6,(1+.5+0+0+1)/6)
|
| 29 |
+
assert math.isclose(si/su,14/38)
|
| 30 |
+
return {'fixtures':6,'gIoU':sg/6,'cIoU':si/su}
|
| 31 |
+
def main():
|
| 32 |
+
p=ROOT/'results/analysis/natural_rela_evaluated.jsonl.gz'
|
| 33 |
+
with gzip.open(p,'rt') as f:rows=[json.loads(x) for x in f]
|
| 34 |
+
got=official(rows);summary=json.loads((ROOT/'results/analysis/natural_rela.json').read_text())
|
| 35 |
+
ref=next(x for x in summary['tables'] if x['split']=='all' and x['grid']=='official480_scores' and x['variant']=='frozen')
|
| 36 |
+
for k in ['gIoU','cIoU','Nacc','positive_mIoU','false_empty','Pr50']:
|
| 37 |
+
assert math.isclose(got[k],ref[k],rel_tol=0,abs_tol=1e-12),(k,got[k],ref[k])
|
| 38 |
+
out={'status':'PASS','independent_equation_replay':got,'fixture_check':fixtures(),
|
| 39 |
+
'reference':'ReLA gres_model/evaluation/refer_evaluation.py'}
|
| 40 |
+
(ROOT/'results/analysis/rela_metric_verification.json').write_text(json.dumps(out,indent=2))
|
| 41 |
+
print(json.dumps(out))
|
| 42 |
+
if __name__=='__main__':main()
|
source/figures/Fig10_harm_signatures.tex
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\node[anchor=west,font=\bfseries\small] at (0,61) {CLIPSeg};
|
| 6 |
+
\begin{axis}[journal,at={(38 mm,0mm)},anchor=south west,width=42mm,height=51mm,xmin=0,xmax=600,ymin=-.6,ymax=5.7,ytick=\empty,xlabel={Expressions},axis lines=left,xtick={0,200,400,600}]
|
| 7 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,5) {Any IoU loss};
|
| 8 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,5)(364,5)};
|
| 9 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(364,5)};
|
| 10 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:364,5) {364};
|
| 11 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,4) {Plural union};
|
| 12 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,4)(339,4)};
|
| 13 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(339,4)};
|
| 14 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:339,4) {339};
|
| 15 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,3) {Initially correct};
|
| 16 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,3)(242,3)};
|
| 17 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(242,3)};
|
| 18 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:242,3) {242};
|
| 19 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,2) {Crossed below .5};
|
| 20 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,2)(64,2)};
|
| 21 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(64,2)};
|
| 22 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:64,2) {64};
|
| 23 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,1) {Geometry sensitive};
|
| 24 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,1)(1,1)};
|
| 25 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(1,1)};
|
| 26 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:1,1) {1};
|
| 27 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,0) {Size-filter sensitive};
|
| 28 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,0)(77,0)};
|
| 29 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(77,0)};
|
| 30 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:77,0) {77};
|
| 31 |
+
\end{axis}
|
| 32 |
+
\node[anchor=west,font=\bfseries\small] at (82,61) {Grounded SAM};
|
| 33 |
+
\begin{axis}[journal,at={(120 mm,0mm)},anchor=south west,width=42mm,height=51mm,xmin=0,xmax=600,ymin=-.6,ymax=5.7,ytick=\empty,xlabel={Expressions},axis lines=left,xtick={0,200,400,600}]
|
| 34 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,5) {Any IoU loss};
|
| 35 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,5)(497,5)};
|
| 36 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(497,5)};
|
| 37 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:497,5) {497};
|
| 38 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,4) {Plural union};
|
| 39 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,4)(474,4)};
|
| 40 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(474,4)};
|
| 41 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:474,4) {474};
|
| 42 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,3) {Initially correct};
|
| 43 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,3)(392,3)};
|
| 44 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(392,3)};
|
| 45 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:392,3) {392};
|
| 46 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,2) {Crossed below .5};
|
| 47 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,2)(112,2)};
|
| 48 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(112,2)};
|
| 49 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:112,2) {112};
|
| 50 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,1) {Geometry sensitive};
|
| 51 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,1)(0,1)};
|
| 52 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(0,1)};
|
| 53 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:0,1) {0};
|
| 54 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-12,0) {Size-filter sensitive};
|
| 55 |
+
\addplot[black!60,line width=.5pt] coordinates {(0,0)(175,0)};
|
| 56 |
+
\addplot[black,only marks,mark=*,mark size=2pt] coordinates {(175,0)};
|
| 57 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:175,0) {175};
|
| 58 |
+
\end{axis}
|
| 59 |
+
\end{tikzpicture}
|
| 60 |
+
\end{document}
|
source/figures/Fig1_framework.tex
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
|
| 5 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 6 |
+
\path[use as bounding box] (0,-3) rectangle (164,57);
|
| 7 |
+
\node[anchor=west,font=\bfseries\small] at (0,54) {(a) Scope and projection};
|
| 8 |
+
\node[anchor=west,font=\bfseries\small] at (99,54) {(b) Spatial eligibility};
|
| 9 |
+
\node (q) at (4,34) {$I,q$};
|
| 10 |
+
\node[draw,rectangle,minimum width=14mm,minimum height=10mm] (f) at (28,34) {$f_{\theta}$};
|
| 11 |
+
\node (p) at (54,34) {$P_q,P_t,P_a$};
|
| 12 |
+
\node[draw,rectangle,minimum width=15mm,minimum height=10mm] (proj) at (80,34) {$\Pi_r$};
|
| 13 |
+
\draw[link] (q)--(f);
|
| 14 |
+
\draw[link] (f)--(p);
|
| 15 |
+
\draw[link] (p)--(proj);
|
| 16 |
+
\node[font=\small] at (28,43) {$\theta$ fixed};
|
| 17 |
+
\node (guard) at (28,16) {$S(q)\in\{0,1\}$};
|
| 18 |
+
\draw[link] (q.south)|-(guard.west);
|
| 19 |
+
\draw[link] (guard.north)--node[right,font=\scriptsize] {$S=1$}(f.south);
|
| 20 |
+
\draw[link,dashed] (guard.east)--(80,16)--(proj.south);
|
| 21 |
+
\node[font=\scriptsize,fill=white,inner sep=1pt] at (57,16) {fallback $M_q$};
|
| 22 |
+
\node[anchor=west,font=\scriptsize] at (0,0) {$\widehat M=\Pi_r(P_q,P_t,P_a)$ if $S(q)\land V$; otherwise $M_q$.};
|
| 23 |
+
\draw[rule] (95,3)--(95,49);
|
| 24 |
+
\draw[->,line width=.5pt] (103,8)--(162,8) node[below] {$x$};
|
| 25 |
+
\draw[->,line width=.5pt] (103,8)--(103,46) node[left] {$y$};
|
| 26 |
+
\fill[black!7] (131,9) rectangle (159,44);
|
| 27 |
+
\draw[dashed,muted] (131,8)--(131,46);
|
| 28 |
+
\node[anchor=south,font=\scriptsize] at (131,46) {$x_A+\epsilon_g$};
|
| 29 |
+
\draw[fill=black!15,line width=.6pt] (117,25) circle (3.8);
|
| 30 |
+
\node at (117,25) {$A$};
|
| 31 |
+
\draw[line width=.6pt] (111,37) ellipse (4 and 2.4);
|
| 32 |
+
\node[above] at (111,39) {$C_1$};
|
| 33 |
+
\draw[teal,fill=teal!14,line width=.8pt] (141,32) ellipse (4.5 and 3);
|
| 34 |
+
\draw[teal,fill=teal!14,line width=.8pt] (150,18) ellipse (4 and 2.8);
|
| 35 |
+
\node[above] at (141,35) {$C_2$};
|
| 36 |
+
\node[above] at (150,21) {$C_3$};
|
| 37 |
+
\draw[link] (121,25)--(136,31);
|
| 38 |
+
\node[anchor=north,font=\small] at (132,3) {$\mathcal E_{\rightarrow}=\{C_2,C_3\}$};
|
| 39 |
+
\end{tikzpicture}
|
| 40 |
+
\end{document}
|
source/figures/Fig2_rich_atlas.tex
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\path[use as bounding box] (0,-108) rectangle (164,8);
|
| 6 |
+
|
| 7 |
+
\fill[teal] (0,0) rectangle (31,-1);
|
| 8 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{7.5}{9}\selectfont,text=teal] at (15.5,-2) {ATTRIBUTE};
|
| 9 |
+
\node[anchor=north west,inner sep=0] at (0,-10) {\includegraphics[width=31mm]{assets/atlas_0_0.png}};
|
| 10 |
+
\draw[rule,line width=.3pt] (0,-10) rectangle (31,-41);
|
| 11 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (30.5,-40.5) {$|G|=3$};
|
| 12 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (0,-43) {\textbf{a}\enspace segment all orange circles};
|
| 13 |
+
\node[anchor=north west,inner sep=0] at (0,-59) {\includegraphics[width=31mm]{assets/atlas_1_0.png}};
|
| 14 |
+
\draw[rule,line width=.3pt] (0,-59) rectangle (31,-90);
|
| 15 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (30.5,-89.5) {$|G|=1$};
|
| 16 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (0,-92) {\textbf{f}\enspace segment all green ellipses};
|
| 17 |
+
\fill[violet] (33,0) rectangle (64,-1);
|
| 18 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{7.5}{9}\selectfont,text=violet] at (48.5,-2) {RELATION};
|
| 19 |
+
\node[anchor=north west,inner sep=0] at (33,-10) {\includegraphics[width=31mm]{assets/atlas_0_1.png}};
|
| 20 |
+
\draw[rule,line width=.3pt] (33,-10) rectangle (64,-41);
|
| 21 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (63.5,-40.5) {$|G|=2$};
|
| 22 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (33,-43) {\textbf{b}\enspace segment all cyan squares above the brown ring};
|
| 23 |
+
\node[anchor=north west,inner sep=0] at (33,-59) {\includegraphics[width=31mm]{assets/atlas_1_1.png}};
|
| 24 |
+
\draw[rule,line width=.3pt] (33,-59) rectangle (64,-90);
|
| 25 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (63.5,-89.5) {$|G|=2$};
|
| 26 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (33,-92) {\textbf{g}\enspace segment all olive capsules right of the yellow cross};
|
| 27 |
+
\fill[ochre] (66,0) rectangle (97,-1);
|
| 28 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{7.5}{9}\selectfont,text=ochre] at (81.5,-2) {TARGET SET};
|
| 29 |
+
\node[anchor=north west,inner sep=0] at (66,-10) {\includegraphics[width=31mm]{assets/atlas_0_2.png}};
|
| 30 |
+
\draw[rule,line width=.3pt] (66,-10) rectangle (97,-41);
|
| 31 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (96.5,-40.5) {$|G|=1$};
|
| 32 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (66,-43) {\textbf{c}\enspace segment the leftmost cyan triangle};
|
| 33 |
+
\node[anchor=north west,inner sep=0] at (66,-59) {\includegraphics[width=31mm]{assets/atlas_1_2.png}};
|
| 34 |
+
\draw[rule,line width=.3pt] (66,-59) rectangle (97,-90);
|
| 35 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (96.5,-89.5) {$|G|=3$};
|
| 36 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (66,-92) {\textbf{h}\enspace segment all cyan hearts};
|
| 37 |
+
\fill[rose] (99,0) rectangle (130,-1);
|
| 38 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{7.5}{9}\selectfont,text=rose] at (114.5,-2) {ACTION};
|
| 39 |
+
\node[anchor=north west,inner sep=0] at (99,-10) {\includegraphics[width=31mm]{assets/atlas_0_3.png}};
|
| 40 |
+
\draw[rule,line width=.3pt] (99,-10) rectangle (130,-41);
|
| 41 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (129.5,-40.5) {$|G|=0$};
|
| 42 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (99,-43) {\textbf{d}\enspace do not segment all pink stars};
|
| 43 |
+
\node[anchor=north west,inner sep=0] at (99,-59) {\includegraphics[width=31mm]{assets/atlas_1_3.png}};
|
| 44 |
+
\draw[rule,line width=.3pt] (99,-59) rectangle (130,-90);
|
| 45 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (129.5,-89.5) {$|G|=0$};
|
| 46 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (99,-92) {\textbf{i}\enspace do not segment all yellow diamonds};
|
| 47 |
+
\fill[ink] (132,0) rectangle (163,-1);
|
| 48 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{7.5}{9}\selectfont,text=ink] at (147.5,-2) {ABSENCE};
|
| 49 |
+
\node[anchor=north west,inner sep=0] at (132,-10) {\includegraphics[width=31mm]{assets/atlas_0_4.png}};
|
| 50 |
+
\draw[rule,line width=.3pt] (132,-10) rectangle (163,-41);
|
| 51 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (162.5,-40.5) {$|G|=0$};
|
| 52 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (132,-43) {\textbf{e}\enspace segment all red crosses};
|
| 53 |
+
\node[anchor=north west,inner sep=0] at (132,-59) {\includegraphics[width=31mm]{assets/atlas_1_4.png}};
|
| 54 |
+
\draw[rule,line width=.3pt] (132,-59) rectangle (163,-90);
|
| 55 |
+
\node[anchor=south east,fill=white,inner sep=.7mm,font=\rmfamily\bfseries\fontsize{7}{8}\selectfont] at (162.5,-89.5) {$|G|=0$};
|
| 56 |
+
\node[anchor=north west,text width=30mm,align=left,font=\rmfamily\fontsize{7.3}{8.8}\selectfont] at (132,-92) {\textbf{j}\enspace segment all red rings};
|
| 57 |
+
\end{tikzpicture}
|
| 58 |
+
\end{document}
|
source/figures/Fig3_paired_render.tex
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\path[use as bounding box] (-2,-13) rectangle (164,108);
|
| 6 |
+
\node[anchor=south,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont] at (24,100) {Flat surface};
|
| 7 |
+
\node[anchor=south,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont] at (75,100) {Rich surface};
|
| 8 |
+
\node[anchor=south,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont] at (126,100) {Shared target mask};
|
| 9 |
+
\node[anchor=north west,inner sep=0] at (8,98) {\includegraphics[width=31mm]{assets/paired_0_flat.png}};
|
| 10 |
+
\draw[link,draw=muted] (41,82.5)--(54,82.5);
|
| 11 |
+
\node[anchor=north west,inner sep=0] at (59,98) {\includegraphics[width=31mm]{assets/paired_0_rich.png}};
|
| 12 |
+
\draw[link,draw=muted] (92,82.5)--(105,82.5);
|
| 13 |
+
\node[anchor=north west,inner sep=0] at (110,98) {\includegraphics[width=31mm]{assets/paired_0_relational_0.png}};
|
| 14 |
+
\node[anchor=west,text width=150mm,font=\rmfamily\fontsize{7.6}{9}\selectfont] at (0,65) {\textbf{a}\enspace segment all pink stars left of the red diamond};
|
| 15 |
+
\node[anchor=north west,inner sep=0] at (8,63) {\includegraphics[width=31mm]{assets/paired_1_flat.png}};
|
| 16 |
+
\draw[link,draw=muted] (41,47.5)--(54,47.5);
|
| 17 |
+
\node[anchor=north west,inner sep=0] at (59,63) {\includegraphics[width=31mm]{assets/paired_1_rich.png}};
|
| 18 |
+
\draw[link,draw=muted] (92,47.5)--(105,47.5);
|
| 19 |
+
\node[anchor=north west,inner sep=0] at (110,63) {\includegraphics[width=31mm]{assets/paired_1_relational_0.png}};
|
| 20 |
+
\node[anchor=west,text width=150mm,font=\rmfamily\fontsize{7.6}{9}\selectfont] at (0,30) {\textbf{b}\enspace segment all olive capsules left of the yellow cross};
|
| 21 |
+
\node[anchor=north west,inner sep=0] at (8,28) {\includegraphics[width=31mm]{assets/paired_2_flat.png}};
|
| 22 |
+
\draw[link,draw=muted] (41,12.5)--(54,12.5);
|
| 23 |
+
\node[anchor=north west,inner sep=0] at (59,28) {\includegraphics[width=31mm]{assets/paired_2_rich.png}};
|
| 24 |
+
\draw[link,draw=muted] (92,12.5)--(105,12.5);
|
| 25 |
+
\node[anchor=north west,inner sep=0] at (110,28) {\includegraphics[width=31mm]{assets/paired_2_relational_0.png}};
|
| 26 |
+
\node[anchor=west,text width=150mm,font=\rmfamily\fontsize{7.6}{9}\selectfont] at (0,-5) {\textbf{c}\enspace segment all yellow diamonds left of the blue circle};
|
| 27 |
+
\end{tikzpicture}
|
| 28 |
+
\end{document}
|
source/figures/Fig4_corrected_contrasts.tex
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\path[use as bounding box] (0,-14) rectangle (163,78);
|
| 6 |
+
\node[anchor=west,font=\rmfamily\bfseries\fontsize{9}{11}\selectfont] at (0,73) {a\enspace CLIPSeg};
|
| 7 |
+
\begin{axis}[journal,at={(20 mm,0mm)},anchor=south west,width=55mm,height=57mm,xmin=-2,xmax=29,ymin=-.5,ymax=2.7,ytick=\empty,axis y line=none,axis x line=bottom,xlabel={Paired-correctness change (pp)},xmajorgrids,xtick={0,10,20}]
|
| 8 |
+
\addplot[muted,dashed] coordinates {(0,-.5)(0,2.7)};
|
| 9 |
+
\addplot[teal,line width=2.4pt,opacity=.22] coordinates {(23.197786,2)(27.500000,2)};
|
| 10 |
+
\addplot[teal,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(25.312500,2) += (2.187500,0) -= (2.114714,0)};
|
| 11 |
+
\node[anchor=south west,font=\rmfamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,2.18) {CACP $-$ frozen};
|
| 12 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont,text=teal] at (axis cs:25.312500,1.87) {+25.31};
|
| 13 |
+
\addplot[teal,line width=2.4pt,opacity=.22] coordinates {(6.312500,1)(10.562500,1)};
|
| 14 |
+
\addplot[teal,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(8.468750,1) += (2.093750,0) -= (2.156250,0)};
|
| 15 |
+
\node[anchor=south west,font=\rmfamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,1.18) {CACP $-$ global rule};
|
| 16 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont,text=teal] at (axis cs:8.468750,0.87) {+8.47};
|
| 17 |
+
\addplot[rose,line width=2.4pt,opacity=.22] coordinates {(-0.406250,0)(-0.031250,0)};
|
| 18 |
+
\addplot[rose,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(-0.187500,0) += (0.156250,0) -= (0.218750,0)};
|
| 19 |
+
\node[anchor=south west,font=\rmfamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,0.18) {CACP $-$ anchor only};
|
| 20 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont,text=rose] at (axis cs:-0.187500,-0.13) {-0.19};
|
| 21 |
+
\end{axis}
|
| 22 |
+
\node[anchor=west,font=\rmfamily\bfseries\fontsize{9}{11}\selectfont] at (83,73) {b\enspace Grounded SAM};
|
| 23 |
+
\begin{axis}[journal,at={(103 mm,0mm)},anchor=south west,width=55mm,height=57mm,xmin=-2,xmax=29,ymin=-.5,ymax=2.7,ytick=\empty,axis y line=none,axis x line=bottom,xlabel={Paired-correctness change (pp)},xmajorgrids,xtick={0,10,20}]
|
| 24 |
+
\addplot[muted,dashed] coordinates {(0,-.5)(0,2.7)};
|
| 25 |
+
\addplot[teal,line width=2.4pt,opacity=.22] coordinates {(16.583073,2)(19.958464,2)};
|
| 26 |
+
\addplot[teal,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(18.312500,2) += (1.645964,0) -= (1.729427,0)};
|
| 27 |
+
\node[anchor=south west,font=\rmfamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,2.18) {CACP $-$ frozen};
|
| 28 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont,text=teal] at (axis cs:18.312500,1.87) {+18.31};
|
| 29 |
+
\addplot[teal,line width=2.4pt,opacity=.22] coordinates {(0.854036,1)(4.208464,1)};
|
| 30 |
+
\addplot[teal,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(2.500000,1) += (1.708464,0) -= (1.645964,0)};
|
| 31 |
+
\node[anchor=south west,font=\rmfamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,1.18) {CACP $-$ global rule};
|
| 32 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont,text=teal] at (axis cs:2.500000,0.87) {+2.50};
|
| 33 |
+
\addplot[rose,line width=2.4pt,opacity=.22] coordinates {(-0.125000,0)(0.000000,0)};
|
| 34 |
+
\addplot[rose,mark=*,mark size=2pt,line width=.8pt,error bars/.cd,x dir=both,x explicit] coordinates {(-0.031250,0) += (0.031250,0) -= (0.093750,0)};
|
| 35 |
+
\node[anchor=south west,font=\rmfamily\fontsize{7.8}{9}\selectfont] at (axis cs:-1.5,0.18) {CACP $-$ anchor only};
|
| 36 |
+
\node[anchor=north,font=\rmfamily\bfseries\fontsize{8}{10}\selectfont,text=rose] at (axis cs:-0.031250,-0.13) {-0.03};
|
| 37 |
+
\end{axis}
|
| 38 |
+
\node[anchor=west,text=muted] at (0,-13) {Six contrasts; image-cluster bootstrap with Bonferroni-adjusted intervals};
|
| 39 |
+
\end{tikzpicture}
|
| 40 |
+
\end{document}
|
source/figures/Fig5_thresholds.tex
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\node[anchor=west,font=\rmfamily\bfseries\fontsize{9}{11}\selectfont] at (0,61) {CLIPSeg};
|
| 6 |
+
\begin{axis}[journal,at={(10 mm,0mm)},anchor=south west,width=64mm,height=48mm,xmin=.3,xmax=.9,ymin=0,ymax=80,xlabel={IoU threshold $\tau$},ylabel={Correct (\%)},ymajorgrids,xtick={.3,.5,.7,.9}]
|
| 7 |
+
\addplot[muted,dashed,line width=1pt] coordinates {(0.300,26.21875) (0.350,19.18750) (0.400,15.34375) (0.450,13.03125) (0.500,10.40625) (0.550,8.46875) (0.600,6.53125) (0.650,4.87500) (0.700,3.59375) (0.750,2.46875) (0.800,1.50000) (0.850,0.59375) (0.900,0.03125)};
|
| 8 |
+
\addplot[ochre,densely dotted,line width=1pt] coordinates {(0.300,43.40625) (0.350,40.06250) (0.400,36.25000) (0.450,32.46875) (0.500,27.25000) (0.550,23.37500) (0.600,19.21875) (0.650,15.15625) (0.700,11.75000) (0.750,8.59375) (0.800,5.68750) (0.850,2.71875) (0.900,0.46875)};
|
| 9 |
+
\addplot[teal,solid,line width=1pt] coordinates {(0.300,48.84375) (0.350,45.96875) (0.400,42.53125) (0.450,39.50000) (0.500,35.90625) (0.550,32.21875) (0.600,28.06250) (0.650,23.59375) (0.700,19.43750) (0.750,14.18750) (0.800,9.15625) (0.850,4.81250) (0.900,0.09375)};
|
| 10 |
+
\addplot[violet,dashdotted,line width=1pt] coordinates {(0.300,48.65625) (0.350,45.81250) (0.400,42.37500) (0.450,39.34375) (0.500,35.71875) (0.550,32.06250) (0.600,28.00000) (0.650,23.56250) (0.700,19.40625) (0.750,14.15625) (0.800,9.12500) (0.850,4.78125) (0.900,0.09375)};
|
| 11 |
+
\addplot[teal,dashed,line width=.7pt,mark=square,mark size=1.5pt,mark options={fill=white}] coordinates {(0.300,70.31250) (0.350,67.93750) (0.400,65.17188) (0.450,62.34375) (0.500,58.76562) (0.550,54.60938) (0.600,50.01562) (0.650,44.70312) (0.700,39.17188) (0.750,31.90625) (0.800,23.50000) (0.850,14.87500) (0.900,4.03125)};
|
| 12 |
+
\end{axis}
|
| 13 |
+
\node[anchor=west,font=\rmfamily\bfseries\fontsize{9}{11}\selectfont] at (82,61) {Grounded SAM};
|
| 14 |
+
\begin{axis}[journal,at={(92 mm,0mm)},anchor=south west,width=64mm,height=48mm,xmin=.3,xmax=.9,ymin=0,ymax=80,xlabel={IoU threshold $\tau$},ylabel={Correct (\%)},ymajorgrids,xtick={.3,.5,.7,.9}]
|
| 15 |
+
\addplot[muted,dashed,line width=1pt] coordinates {(0.300,7.09375) (0.350,2.31250) (0.400,0.43750) (0.450,0.06250) (0.500,0.03125) (0.550,0.00000) (0.600,0.00000) (0.650,0.00000) (0.700,0.00000) (0.750,0.00000) (0.800,0.00000) (0.850,0.00000) (0.900,0.00000)};
|
| 16 |
+
\addplot[ochre,densely dotted,line width=1pt] coordinates {(0.300,35.34375) (0.350,32.78125) (0.400,29.03125) (0.450,22.68750) (0.500,15.84375) (0.550,8.53125) (0.600,3.65625) (0.650,1.50000) (0.700,0.75000) (0.750,0.50000) (0.800,0.15625) (0.850,0.06250) (0.900,0.03125)};
|
| 17 |
+
\addplot[teal,solid,line width=1pt] coordinates {(0.300,31.15625) (0.350,28.62500) (0.400,25.93750) (0.450,22.12500) (0.500,18.37500) (0.550,13.28125) (0.600,8.68750) (0.650,5.50000) (0.700,3.53125) (0.750,2.21875) (0.800,1.00000) (0.850,0.31250) (0.900,0.28125)};
|
| 18 |
+
\addplot[violet,dashdotted,line width=1pt] coordinates {(0.300,31.12500) (0.350,28.59375) (0.400,25.90625) (0.450,22.09375) (0.500,18.34375) (0.550,13.25000) (0.600,8.65625) (0.650,5.46875) (0.700,3.53125) (0.750,2.21875) (0.800,1.00000) (0.850,0.31250) (0.900,0.28125)};
|
| 19 |
+
\addplot[teal,dashed,line width=.7pt,mark=square,mark size=1.5pt,mark options={fill=white}] coordinates {(0.300,63.28125) (0.350,59.46875) (0.400,55.00000) (0.450,48.89062) (0.500,42.89062) (0.550,35.26562) (0.600,28.01562) (0.650,22.21875) (0.700,18.95312) (0.750,16.51562) (0.800,14.32812) (0.850,13.09375) (0.900,13.01562)};
|
| 20 |
+
\end{axis}
|
| 21 |
+
\draw[black,dashed,line width=.75pt] (0,-17)--(5,-17);\node[anchor=west,font=\scriptsize] at (6,-17) {Frozen};
|
| 22 |
+
\draw[black,densely dotted,line width=.75pt] (32,-17)--(37,-17);\node[anchor=west,font=\scriptsize] at (38,-17) {Global};
|
| 23 |
+
\draw[black,solid,line width=.75pt] (64,-17)--(69,-17);\node[anchor=west,font=\scriptsize] at (70,-17) {Anchor PC};
|
| 24 |
+
\draw[black,dashdotted,line width=.75pt] (100,-17)--(105,-17);\node[anchor=west,font=\scriptsize] at (106,-17) {CACP};
|
| 25 |
+
\draw[black,dashed,line width=.75pt] (130,-17)--(135,-17);\node[anchor=west,font=\scriptsize] at (136,-17) {Anchor Pr};
|
| 26 |
+
\draw[fill=white] (132,-17.6) rectangle (133.2,-16.4);
|
| 27 |
+
\end{tikzpicture}
|
| 28 |
+
\end{document}
|
source/figures/Fig6_natural_effects.tex
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\node[anchor=west,font=\bfseries\small] at (0,50) {CLIPSeg};
|
| 6 |
+
\begin{axis}[journal,at={(10 mm,0mm)},anchor=south west,width=64mm,height=40mm,xmin=0,xmax=6,ymin=-.02,ymax=.2,xlabel={Accepted expressions (\%)},ylabel={$\Delta$gIoU (pp)},axis lines=left,xtick={0,1,2,3,4,5,6}]
|
| 7 |
+
\addplot[teal,line width=.8pt,mark=*] coordinates {(0.58999,0.006588) (0.77184,0.013447) (3.14596,0.108134) (5.67566,0.117834)};
|
| 8 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(0.589994,0.006588) += (0,0.013111) -= (0,0.013460)};
|
| 9 |
+
\node[anchor=north east,font=\scriptsize] at (axis cs:0.60999,0.002588) {R$_s$};
|
| 10 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(0.771842,0.013447) += (0,0.013946) -= (0,0.014924)};
|
| 11 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:0.79184,0.016447) {R};
|
| 12 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(3.145963,0.108134) += (0,0.033173) -= (0,0.033344)};
|
| 13 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:3.16596,0.111134) {S};
|
| 14 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(5.675665,0.117834) += (0,0.047349) -= (0,0.047607)};
|
| 15 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:5.69566,0.120834) {L};
|
| 16 |
+
\end{axis}
|
| 17 |
+
\node[anchor=west,font=\bfseries\small] at (82,50) {Grounded SAM};
|
| 18 |
+
\begin{axis}[journal,at={(92 mm,0mm)},anchor=south west,width=64mm,height=40mm,xmin=0,xmax=6,ymin=-.02,ymax=.2,xlabel={Accepted expressions (\%)},ylabel={$\Delta$gIoU (pp)},axis lines=left,xtick={0,1,2,3,4,5,6}]
|
| 19 |
+
\addplot[teal,line width=.8pt,mark=*] coordinates {(0.58999,0.013778) (0.77184,0.015319) (3.14596,0.071546) (5.67566,0.029429)};
|
| 20 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(0.589994,0.013778) += (0,0.010175) -= (0,0.008849)};
|
| 21 |
+
\node[anchor=north east,font=\scriptsize] at (axis cs:0.60999,0.009778) {R$_s$};
|
| 22 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(0.771842,0.015319) += (0,0.011307) -= (0,0.010274)};
|
| 23 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:0.79184,0.018319) {R};
|
| 24 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(3.145963,0.071546) += (0,0.036149) -= (0,0.039415)};
|
| 25 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:3.16596,0.074546) {S};
|
| 26 |
+
\addplot[teal,error bars/.cd,y dir=both,y explicit] coordinates {(5.675665,0.029429) += (0,0.045644) -= (0,0.050688)};
|
| 27 |
+
\node[anchor=south west,font=\scriptsize] at (axis cs:5.69566,0.032429) {L};
|
| 28 |
+
\end{axis}
|
| 29 |
+
\end{tikzpicture}
|
| 30 |
+
\end{document}
|
source/figures/Fig7_absence_tradeoff.tex
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\path[use as bounding box] (0,-14) rectangle (164,67);
|
| 6 |
+
\node[anchor=west,font=\rmfamily\bfseries\fontsize{9}{11}\selectfont] at (0,62) {CLIPSeg};
|
| 7 |
+
\begin{axis}[journal,at={(8 mm,0mm)},anchor=south west,width=68mm,height=49mm,xmin=0,xmax=100,ymin=0,ymax=60,xlabel={No-target accuracy (\%)},ylabel={Positive mIoU (\%)},xmajorgrids,ymajorgrids]
|
| 8 |
+
\addplot[muted,only marks,mark=*,mark size=2.6pt] coordinates {(71.1580,28.3970)} node[anchor=north east,yshift=-1mm,font=\rmfamily\fontsize{7}{8}\selectfont,text=muted] {Frozen};
|
| 9 |
+
\addplot[rose,only marks,mark=*,mark size=2.6pt] coordinates {(88.0510,22.3760)} node[anchor=south west,yshift=1mm,font=\rmfamily\fontsize{7}{8}\selectfont,text=rose] {Source};
|
| 10 |
+
\addplot[teal,only marks,mark=*,mark size=2.6pt] coordinates {(73.4490,28.4680)} node[anchor=south west,yshift=1mm,font=\rmfamily\fontsize{7}{8}\selectfont,text=teal] {5\% bound};
|
| 11 |
+
\end{axis}
|
| 12 |
+
\node[anchor=west,font=\rmfamily\bfseries\fontsize{9}{11}\selectfont] at (82,62) {Grounded SAM};
|
| 13 |
+
\begin{axis}[journal,at={(90 mm,0mm)},anchor=south west,width=68mm,height=49mm,xmin=0,xmax=100,ymin=0,ymax=60,xlabel={No-target accuracy (\%)},ylabel={Positive mIoU (\%)},xmajorgrids,ymajorgrids]
|
| 14 |
+
\addplot[muted,only marks,mark=*,mark size=2.6pt] coordinates {(15.3330,53.3080)} node[anchor=north east,yshift=-1mm,font=\rmfamily\fontsize{7}{8}\selectfont,text=muted] {Frozen};
|
| 15 |
+
\addplot[rose,only marks,mark=*,mark size=2.6pt] coordinates {(29.7020,45.1320)} node[anchor=south west,yshift=1mm,font=\rmfamily\fontsize{7}{8}\selectfont,text=rose] {Source};
|
| 16 |
+
\addplot[teal,only marks,mark=*,mark size=2.6pt] coordinates {(16.2150,53.3420)} node[anchor=south west,yshift=1mm,font=\rmfamily\fontsize{7}{8}\selectfont,text=teal] {5\% bound};
|
| 17 |
+
\end{axis}
|
| 18 |
+
\node[anchor=west,text=muted,font=\rmfamily\fontsize{7.3}{9}\selectfont] at (0,-12) {Moving right can erase positive masks: source calibration raises N-acc but sharply lowers positive mIoU.};
|
| 19 |
+
\end{tikzpicture}
|
| 20 |
+
\end{document}
|
source/figures/Fig8_rich_performance.tex
ADDED
|
@@ -0,0 +1,28 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\node[anchor=west,font=\bfseries\small] at (0,44) {Flat};
|
| 6 |
+
\begin{axis}[journal,at={(10 mm,0mm)},anchor=south west,width=65mm,height=32mm,xmin=0,xmax=21,ymin=-.5,ymax=1.6,ytick=\empty,xlabel={PC$_{.5}$ (\%)},axis lines=left,xtick={0,5,10,15,20}]
|
| 7 |
+
\addplot[black!55,line width=.6pt] coordinates {(0.0833,0)(8.0000,0)};
|
| 8 |
+
\addplot[black,only marks,mark=o,mark size=2.3pt] coordinates {(0.0833,0)};
|
| 9 |
+
\addplot[black,only marks,mark=*,mark size=2.3pt] coordinates {(8.0000,0)};
|
| 10 |
+
\node[anchor=south east,font=\scriptsize] at (axis cs:20.8,0.12) {Grounded SAM};
|
| 11 |
+
\addplot[black!55,line width=.6pt] coordinates {(4.5208,1)(17.4792,1)};
|
| 12 |
+
\addplot[black,only marks,mark=o,mark size=2.3pt] coordinates {(4.5208,1)};
|
| 13 |
+
\addplot[black,only marks,mark=*,mark size=2.3pt] coordinates {(17.4792,1)};
|
| 14 |
+
\node[anchor=south east,font=\scriptsize] at (axis cs:20.8,1.12) {CLIPSeg};
|
| 15 |
+
\end{axis}
|
| 16 |
+
\node[anchor=west,font=\bfseries\small] at (82,44) {Rich};
|
| 17 |
+
\begin{axis}[journal,at={(92 mm,0mm)},anchor=south west,width=65mm,height=32mm,xmin=0,xmax=21,ymin=-.5,ymax=1.6,ytick=\empty,xlabel={PC$_{.5}$ (\%)},axis lines=left,xtick={0,5,10,15,20}]
|
| 18 |
+
\addplot[black!55,line width=.6pt] coordinates {(0.5000,0)(17.3333,0)};
|
| 19 |
+
\addplot[black,only marks,mark=o,mark size=2.3pt] coordinates {(0.5000,0)};
|
| 20 |
+
\addplot[black,only marks,mark=*,mark size=2.3pt] coordinates {(17.3333,0)};
|
| 21 |
+
\node[anchor=south east,font=\scriptsize] at (axis cs:20.8,0.12) {Grounded SAM};
|
| 22 |
+
\addplot[black!55,line width=.6pt] coordinates {(3.2708,1)(9.0000,1)};
|
| 23 |
+
\addplot[black,only marks,mark=o,mark size=2.3pt] coordinates {(3.2708,1)};
|
| 24 |
+
\addplot[black,only marks,mark=*,mark size=2.3pt] coordinates {(9.0000,1)};
|
| 25 |
+
\node[anchor=south east,font=\scriptsize] at (axis cs:20.8,1.12) {CLIPSeg};
|
| 26 |
+
\end{axis}
|
| 27 |
+
\end{tikzpicture}
|
| 28 |
+
\end{document}
|
source/figures/Fig9_threshold_robustness.tex
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
\documentclass[tikz,border=1.5pt]{standalone}
|
| 2 |
+
\input{style}
|
| 3 |
+
\begin{document}
|
| 4 |
+
\begin{tikzpicture}[x=1mm,y=1mm]
|
| 5 |
+
\node[anchor=west,font=\bfseries\small] at (0,76) {CLIPSeg};
|
| 6 |
+
\begin{axis}[journal,at={(26 mm,0mm)},anchor=south west,width=50mm,height=65mm,xmin=0,xmax=.18,ymin=-.7,ymax=10.7,ytick=\empty,xlabel={$\Delta$gIoU (pp)},axis lines=left,xtick={0,.05,.1,.15}]
|
| 7 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,10) {Primary};
|
| 8 |
+
\addplot[black,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.108134,10) += (0.033173,0) -= (0.033344,0)};
|
| 9 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,9) {$\delta_a=.02$};
|
| 10 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.110654,9) += (0.034363,0) -= (0.033817,0)};
|
| 11 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,8) {$\delta_a=.10$};
|
| 12 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.107714,8) += (0.033203,0) -= (0.033546,0)};
|
| 13 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,7) {$\delta_t=.02$};
|
| 14 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.108965,7) += (0.033125,0) -= (0.033342,0)};
|
| 15 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,6) {$\delta_t=.10$};
|
| 16 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.105164,6) += (0.033294,0) -= (0.032671,0)};
|
| 17 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,5) {$\epsilon_g=.01$};
|
| 18 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.108607,5) += (0.033268,0) -= (0.033608,0)};
|
| 19 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,4) {$\epsilon_g=.05$};
|
| 20 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.108899,4) += (0.033126,0) -= (0.033323,0)};
|
| 21 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,3) {$a_{\min}\times.5$};
|
| 22 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.107847,3) += (0.032703,0) -= (0.033137,0)};
|
| 23 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,2) {$a_{\min}\times2$};
|
| 24 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.111440,2) += (0.032679,0) -= (0.032702,0)};
|
| 25 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,1) {$t_0-.05$};
|
| 26 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.106074,1) += (0.031520,0) -= (0.031451,0)};
|
| 27 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,0) {$t_0+.05$};
|
| 28 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.105752,0) += (0.032759,0) -= (0.033400,0)};
|
| 29 |
+
\end{axis}
|
| 30 |
+
\node[anchor=west,font=\bfseries\small] at (82,76) {Grounded SAM};
|
| 31 |
+
\begin{axis}[journal,at={(108 mm,0mm)},anchor=south west,width=50mm,height=65mm,xmin=0,xmax=.18,ymin=-.7,ymax=10.7,ytick=\empty,xlabel={$\Delta$gIoU (pp)},axis lines=left,xtick={0,.05,.1,.15}]
|
| 32 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,10) {Primary};
|
| 33 |
+
\addplot[black,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.071546,10) += (0.036149,0) -= (0.039415,0)};
|
| 34 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,9) {$\delta_a=.02$};
|
| 35 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.069326,9) += (0.036746,0) -= (0.039467,0)};
|
| 36 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,8) {$\delta_a=.10$};
|
| 37 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.070596,8) += (0.036522,0) -= (0.038942,0)};
|
| 38 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,7) {$\delta_t=.02$};
|
| 39 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.069838,7) += (0.036347,0) -= (0.038941,0)};
|
| 40 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,6) {$\delta_t=.10$};
|
| 41 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.073230,6) += (0.036431,0) -= (0.038994,0)};
|
| 42 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,5) {$\epsilon_g=.01$};
|
| 43 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.073022,5) += (0.037390,0) -= (0.039008,0)};
|
| 44 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,4) {$\epsilon_g=.05$};
|
| 45 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.070984,4) += (0.036045,0) -= (0.039434,0)};
|
| 46 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,3) {$a_{\min}\times.5$};
|
| 47 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.068147,3) += (0.036245,0) -= (0.038972,0)};
|
| 48 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,2) {$a_{\min}\times2$};
|
| 49 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.076628,2) += (0.036978,0) -= (0.038982,0)};
|
| 50 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,1) {$t_0-.05$};
|
| 51 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.071546,1) += (0.036149,0) -= (0.039415,0)};
|
| 52 |
+
\node[anchor=east,font=\scriptsize] at (axis cs:-.005,0) {$t_0+.05$};
|
| 53 |
+
\addplot[teal,mark=*,mark size=1.5pt,error bars/.cd,x dir=both,x explicit] coordinates {(0.102102,0) += (0.041258,0) -= (0.038146,0)};
|
| 54 |
+
\end{axis}
|
| 55 |
+
\end{tikzpicture}
|
| 56 |
+
\end{document}
|
source/figures/atlas_manifest.json
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"panel": "a",
|
| 4 |
+
"scene_id": "r11_0000",
|
| 5 |
+
"family": "attribute",
|
| 6 |
+
"query": "segment all orange circles",
|
| 7 |
+
"target_count": 3,
|
| 8 |
+
"raster": "data/rich/r11_0000/rich.png"
|
| 9 |
+
},
|
| 10 |
+
{
|
| 11 |
+
"panel": "f",
|
| 12 |
+
"scene_id": "r11_0005",
|
| 13 |
+
"family": "attribute",
|
| 14 |
+
"query": "segment all green ellipses",
|
| 15 |
+
"target_count": 1,
|
| 16 |
+
"raster": "data/rich/r11_0005/rich.png"
|
| 17 |
+
},
|
| 18 |
+
{
|
| 19 |
+
"panel": "b",
|
| 20 |
+
"scene_id": "r11_0001",
|
| 21 |
+
"family": "relational",
|
| 22 |
+
"query": "segment all cyan squares above the brown ring",
|
| 23 |
+
"target_count": 2,
|
| 24 |
+
"raster": "data/rich/r11_0001/rich.png"
|
| 25 |
+
},
|
| 26 |
+
{
|
| 27 |
+
"panel": "g",
|
| 28 |
+
"scene_id": "r11_0006",
|
| 29 |
+
"family": "relational",
|
| 30 |
+
"query": "segment all olive capsules right of the yellow cross",
|
| 31 |
+
"target_count": 2,
|
| 32 |
+
"raster": "data/rich/r11_0006/rich.png"
|
| 33 |
+
},
|
| 34 |
+
{
|
| 35 |
+
"panel": "c",
|
| 36 |
+
"scene_id": "r11_0002",
|
| 37 |
+
"family": "multi_target",
|
| 38 |
+
"query": "segment the leftmost cyan triangle",
|
| 39 |
+
"target_count": 1,
|
| 40 |
+
"raster": "data/rich/r11_0002/rich.png"
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"panel": "h",
|
| 44 |
+
"scene_id": "r11_0007",
|
| 45 |
+
"family": "multi_target",
|
| 46 |
+
"query": "segment all cyan hearts",
|
| 47 |
+
"target_count": 3,
|
| 48 |
+
"raster": "data/rich/r11_0007/rich.png"
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"panel": "d",
|
| 52 |
+
"scene_id": "r11_0003",
|
| 53 |
+
"family": "negative_action",
|
| 54 |
+
"query": "do not segment all pink stars",
|
| 55 |
+
"target_count": 0,
|
| 56 |
+
"raster": "data/rich/r11_0003/rich.png"
|
| 57 |
+
},
|
| 58 |
+
{
|
| 59 |
+
"panel": "i",
|
| 60 |
+
"scene_id": "r11_0008",
|
| 61 |
+
"family": "negative_action",
|
| 62 |
+
"query": "do not segment all yellow diamonds",
|
| 63 |
+
"target_count": 0,
|
| 64 |
+
"raster": "data/rich/r11_0008/rich.png"
|
| 65 |
+
},
|
| 66 |
+
{
|
| 67 |
+
"panel": "e",
|
| 68 |
+
"scene_id": "r11_0004",
|
| 69 |
+
"family": "empty_target",
|
| 70 |
+
"query": "segment all red crosses",
|
| 71 |
+
"target_count": 0,
|
| 72 |
+
"raster": "data/rich/r11_0004/rich.png"
|
| 73 |
+
},
|
| 74 |
+
{
|
| 75 |
+
"panel": "j",
|
| 76 |
+
"scene_id": "r11_0009",
|
| 77 |
+
"family": "empty_target",
|
| 78 |
+
"query": "segment all red rings",
|
| 79 |
+
"target_count": 0,
|
| 80 |
+
"raster": "data/rich/r11_0009/rich.png"
|
| 81 |
+
}
|
| 82 |
+
]
|