Spaces:
Running on Zero
Running on Zero
Grounded version
Browse files- .gitignore +8 -0
- CITATION.cff +15 -0
- README.md +114 -1
- app.py +174 -55
- cli.py +124 -0
- inversion/__init__.py +12 -0
- inversion/backends.py +110 -0
- inversion/compiler.py +283 -0
- inversion/dino.py +70 -0
- inversion/engine.py +248 -0
- inversion/proxy.py +61 -0
- inversion/schema.py +216 -0
- inversion/vlm.py +254 -0
- requirements.txt +10 -0
- tests/test_engine.py +256 -0
.gitignore
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
__pycache__/
|
| 2 |
+
*.pyc
|
| 3 |
+
.pytest_cache/
|
| 4 |
+
runs/
|
| 5 |
+
renders/
|
| 6 |
+
medoids/
|
| 7 |
+
medoids.json
|
| 8 |
+
tests/sample
|
CITATION.cff
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
cff-version: 1.2.0
|
| 2 |
+
message: "If you use this software, please cite it as below."
|
| 3 |
+
authors:
|
| 4 |
+
- family-names: Larrain Varas
|
| 5 |
+
given-names: Gaspar Dario
|
| 6 |
+
title: "Grounded Prompt-to-Image VLM Space"
|
| 7 |
+
abstract: "The software implements a 4-layer process (VLM, DSG, Flux, VQA) to transform an image into a grounded prompt"
|
| 8 |
+
version: 2.0.1
|
| 9 |
+
date-released: 2026-11-17
|
| 10 |
+
identifiers:
|
| 11 |
+
- description: The following is the Hugging Face space associated with this software
|
| 12 |
+
type: url
|
| 13 |
+
value: "https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer"
|
| 14 |
+
license: Apache-2.0
|
| 15 |
+
repository-code: "https://github.com/glarrainv/Prompt-Reverse-Engineer"
|
README.md
CHANGED
|
@@ -6,8 +6,121 @@ colorTo: blue
|
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
| 8 |
python_version: "3.12.12"
|
|
|
|
| 9 |
app_file: app.py
|
| 10 |
-
pinned:
|
|
|
|
|
|
|
| 11 |
models:
|
| 12 |
- Qwen/Qwen3-VL-8B-Instruct
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 6 |
sdk: gradio
|
| 7 |
sdk_version: 6.31.0
|
| 8 |
python_version: "3.12.12"
|
| 9 |
+
suggested_hardware: zero-a10g
|
| 10 |
app_file: app.py
|
| 11 |
+
pinned: true
|
| 12 |
+
short_description: Image to prompt reverse enginner, turn any image back.
|
| 13 |
+
license: apache-2.0
|
| 14 |
models:
|
| 15 |
- Qwen/Qwen3-VL-8B-Instruct
|
| 16 |
+
- black-forest-labs/FLUX.1-schnell
|
| 17 |
+
- facebook/dinov2-base
|
| 18 |
+
library_name: transformers
|
| 19 |
+
tags:
|
| 20 |
+
- image-to-prompt
|
| 21 |
+
- computer vision
|
| 22 |
+
- captioning
|
| 23 |
+
- qwen
|
| 24 |
---
|
| 25 |
+
|
| 26 |
+
# Prompt Reverse Engineer: closed-loop DSG + VQA inversion
|
| 27 |
+
|
| 28 |
+
The original pipeline was one step: an image went into Qwen3-VL-8B, which returned unconstrained prose. This version wraps that same VLM in a self-correcting loop with four modules:
|
| 29 |
+
|
| 30 |
+
```
|
| 31 |
+
OG image S_k
|
| 32 |
+
│
|
| 33 |
+
▼ Module 1 Constrained DSG extractor (Qwen3-VL + Pydantic schema, 3×3 grid, medium/palette)
|
| 34 |
+
│ └─ grounding: every predicate is checked on S_k itself; facts the scorer rejects
|
| 35 |
+
│ on the original are pruned as hallucinations (they could never be satisfied),
|
| 36 |
+
│ including medium/optics facets, which are removed from the prompt as well;
|
| 37 |
+
│ a rejected grid cell is re-localized by scoring all 9 cells on S_k
|
| 38 |
+
▼ Module 2 Predicate compiler + canonical linearizer
|
| 39 |
+
│ G_k → dependency-ordered yes/no predicates Q_DSG (global → entity → attribute
|
| 40 |
+
│ → position → relation) and a deterministic canonical prompt P_k^(0)
|
| 41 |
+
▼ Module 3 Proxy T2I renderer (FLUX.1-schnell, 4 steps, seed = 42 + t)
|
| 42 |
+
▼ Module 4 Dual verifier
|
| 43 |
+
│ 4A VQAScore: P(yes | proxy, 'Does this image show "{q}"? …') per predicate,
|
| 44 |
+
│ DSG rule: children of an absent parent entity score 0
|
| 45 |
+
│ 4B DINOv2 patch-aligned cosine between S_k and the proxy (layout)
|
| 46 |
+
│
|
| 47 |
+
├─ S_VQA ≥ 0.90 AND S_DINO ≥ 0.80 → lock P_k*
|
| 48 |
+
├─ t = max_iters → return best prompt by 0.7·S_VQA + 0.3·S_DINO
|
| 49 |
+
└─ otherwise: targeted diff rewrite → only spans tied to failed predicates are edited
|
| 50 |
+
(the VLM sees original + proxy; edits must quote the prompt verbatim and are applied
|
| 51 |
+
deterministically; unmatched edits are skipped and recorded, never guessed; edits that
|
| 52 |
+
would inject an era/style buzzword absent from the grounded prompt, e.g. "vintage",
|
| 53 |
+
"cinematic", "1970s", "Bauhaus", are skipped as unverified)
|
| 54 |
+
```
|
| 55 |
+
|
| 56 |
+
## Code map
|
| 57 |
+
|
| 58 |
+
| Path | Role |
|
| 59 |
+
| --- | --- |
|
| 60 |
+
| `inversion/schema.py` | Module 1 schema (`DSGSceneSchema`, `SpatialNode`, `Relation`) and the `RewritePatch` diff schema |
|
| 61 |
+
| `inversion/compiler.py` | Module 2: `compile_predicates`, `apply_dependencies`, `prune_hallucinations`, `linearize`, `apply_patch` |
|
| 62 |
+
| `inversion/vlm.py` | `LocalQwenVLM` (one set of weights for extraction, VQAScore, and rewriting) and `OpenAICompatVLM` (API) |
|
| 63 |
+
| `inversion/proxy.py` | Module 3: `FluxSchnellRenderer` (diffusers) and `FalRenderer` (fal.ai) |
|
| 64 |
+
| `inversion/dino.py` | Module 4B: `DinoEmbedder` (DINOv2-B default), `dino_similarity`, `medoid_index` |
|
| 65 |
+
| `inversion/engine.py` | The state machine: `iter_inversion` (streams stages), `invert_image_to_verified_prompt`, `save_run` |
|
| 66 |
+
| `inversion/backends.py` | Builds all components from environment variables |
|
| 67 |
+
| `app.py` | Gradio Space UI. Each model call gets its own `@spaces.GPU` allocation |
|
| 68 |
+
| `cli.py` | Batch `invert` over a stimulus folder, and DINO `medoid` selection over seed renders |
|
| 69 |
+
| `tests/` | Model-free tests of the schema, compiler, dependency rule, grounding, diff, and loop |
|
| 70 |
+
|
| 71 |
+
## Setup
|
| 72 |
+
|
| 73 |
+
**Prerequisites (both pathways).** `black-forest-labs/FLUX.1-schnell` is gated on Hugging Face. Accept its license with your account, then create a read token (`HF_TOKEN`). On the Space, add `HF_TOKEN` as a secret, or the Space will fail at startup. The default DINOv2 backbone is ungated; a gated `facebook/dinov3-*` checkpoint can be used through `DINO_MODEL_ID` once access is granted.
|
| 74 |
+
|
| 75 |
+
### Pathway B: local GPU, HPC, or the HF Space (default, no API cost)
|
| 76 |
+
|
| 77 |
+
```bash
|
| 78 |
+
conda create -n dsg_vqa_inv python=3.12 -y && conda activate dsg_vqa_inv
|
| 79 |
+
pip install -r requirements.txt
|
| 80 |
+
export HF_TOKEN=hf_...
|
| 81 |
+
python app.py # UI
|
| 82 |
+
python cli.py invert --input stimuli/ --out runs/ # batch: runs/<stem>/report.json, best_prompt.txt, proxies
|
| 83 |
+
```
|
| 84 |
+
|
| 85 |
+
Loading Qwen3-VL-8B, FLUX.1-schnell, and DINOv2-B together needs about 52 GB. On a 24 GB card, set `PROXY_CPU_OFFLOAD=1`, or set `PROXY_BACKEND=fal` to move proxy rendering to the API.
|
| 86 |
+
|
| 87 |
+
### Pathway A: no local GPU (API)
|
| 88 |
+
|
| 89 |
+
```bash
|
| 90 |
+
export VLM_BACKEND=api VLM_API_KEY=sk-or-... # OpenRouter, qwen/qwen3-vl-32b-instruct by default
|
| 91 |
+
export SCORER_BACKEND=api OPENAI_API_KEY=sk-... # VQAScore via gpt-4o logprobs
|
| 92 |
+
export PROXY_BACKEND=fal FAL_KEY=... # fal-ai/flux/schnell
|
| 93 |
+
export DINO_MODEL_ID=facebook/dinov2-small DINO_DEVICE=cpu
|
| 94 |
+
python cli.py invert --input stimuli/ --out runs/
|
| 95 |
+
```
|
| 96 |
+
|
| 97 |
+
The API scorer reads P("Yes") from the top-20 logprobs of a one-token answer, so `SCORER_API_MODEL` must be a model that returns logprobs for image inputs (gpt-4o does). Many OpenRouter providers do not, which is why the scorer is configured separately from the VLM.
|
| 98 |
+
|
| 99 |
+
| Variable | Default |
|
| 100 |
+
| --- | --- |
|
| 101 |
+
| `VLM_BACKEND` | `local` (`api`) |
|
| 102 |
+
| `VLM_MODEL_ID` | `Qwen/Qwen3-VL-8B-Instruct` (e.g. `Qwen/Qwen3-VL-32B-Instruct`) |
|
| 103 |
+
| `VLM_API_MODEL` / `VLM_API_BASE_URL` / `VLM_API_KEY` | `qwen/qwen3-vl-32b-instruct` / OpenRouter / — |
|
| 104 |
+
| `SCORER_BACKEND` | same as VLM; reuses the VLM's weights when both are local |
|
| 105 |
+
| `SCORER_API_MODEL` / `SCORER_API_BASE_URL` / `SCORER_API_KEY` | `gpt-4o` / OpenAI / `OPENAI_API_KEY` |
|
| 106 |
+
| `PROXY_BACKEND` | `flux` (`fal`) |
|
| 107 |
+
| `PROXY_MODEL_ID`, `PROXY_CPU_OFFLOAD`, `FAL_ENDPOINT` | `black-forest-labs/FLUX.1-schnell`, `0`, `fal-ai/flux/schnell` |
|
| 108 |
+
| `DINO_MODEL_ID`, `DINO_DEVICE` | `facebook/dinov2-base` (Pivot 1 backbone), auto |
|
| 109 |
+
| `VQA_MODE` | `normalized` (`yes` = original VQAScore, P("Yes") only) |
|
| 110 |
+
|
| 111 |
+
## Stimulus-bank workflow
|
| 112 |
+
|
| 113 |
+
1. **Positive control.** Run `python cli.py invert --input 000DAH.png --out runs/` and inspect `runs/000DAH/report.json`. Check whether the camera, the "PALACE" marquee position, and the subject's orientation survived grounding as predicates, and whether S_VQA ≥ 0.90.
|
| 114 |
+
2. **Lock P\*_1…P\*_9.** Run `python cli.py invert --input stimuli/ --out runs/`. `runs/summary.csv` lists each image's stop reason, best scores, and best prompt.
|
| 115 |
+
3. **Render target conditions** in the target models, outside this repo. Save them as `renders/<condition>/<seed>.png`, then pick one medoid per condition: `python cli.py medoid --input renders/ --out medoids.json --copy-to medoids/`.
|
| 116 |
+
|
| 117 |
+
## Notes and limitations
|
| 118 |
+
|
| 119 |
+
- **VQAScore normalization.** The original VQAScore is P("Yes") over the full vocabulary. Qwen3-VL answers mostly with lowercase "yes". In testing, a fact it affirmed with probability 0.99 scored P("Yes") = 0.009, and batched and single runs disagreed by up to 0.05. By default the scorer therefore uses P(yes-variants) / (P(yes-variants) + P(no-variants)). `VQA_MODE=yes` restores the original definition, but its thresholds are then not comparable.
|
| 120 |
+
|
| 121 |
+
- **Structured output.** The API backend requests `json_schema` output. The local backend puts the schema in the prompt and validates with Pydantic, with up to two repair retries. It does not use token-level constrained decoding.
|
| 122 |
+
- **Self-verification bias.** With the local backend, one model extracts the predicates and also scores them. Grounding removes facts the model rejects on the original, but shared blind spots stay. For an independent check, use a different scorer (`SCORER_BACKEND=api`, or a larger `VLM_MODEL_ID` for scoring).
|
| 123 |
+
- **DINO gate.** S_DINO compares patch (i, j) of the original with patch (i, j) of the proxy at 448×448. It responds to layout and to left/right flips. Treat the 0.80 default as a strong target, not a calibrated threshold, and calibrate it on your own stimuli. The 0.80 value is not transferable between backbones (DINOv2 vs DINOv3), and it is an addition to the plan's stop rule (S_VQA ≥ 0.90 only); set `--dino-gate 0` to apply the plan's rule exactly.
|
| 124 |
+
- **Prompt length.** The canonical prompt can exceed the 77-token CLIP limit. FLUX reads up to 512 T5 tokens, so the proxy still sees the full prompt.
|
| 125 |
+
|
| 126 |
+
Author: Larrain, G
|
app.py
CHANGED
|
@@ -1,70 +1,150 @@
|
|
| 1 |
-
import
|
|
|
|
|
|
|
| 2 |
import gradio as gr
|
| 3 |
-
import
|
| 4 |
-
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
|
|
|
| 8 |
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
processor = AutoProcessor.from_pretrained(MODEL_ID)
|
| 12 |
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
| 18 |
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
)
|
| 46 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 47 |
|
| 48 |
|
| 49 |
with gr.Blocks(title="Prompt Reverse Engineer") as demo:
|
| 50 |
gr.Markdown("# Prompt Reverse Engineer")
|
| 51 |
-
gr.Markdown("## Image
|
| 52 |
-
gr.Markdown(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 53 |
|
| 54 |
with gr.Row():
|
| 55 |
-
with gr.Column():
|
| 56 |
-
image = gr.Image(type="pil", label="
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 68 |
@misc{qwen3technicalreport,
|
| 69 |
title={Qwen3 Technical Report},
|
| 70 |
author={Qwen Team},
|
|
@@ -95,9 +175,48 @@ with gr.Blocks(title="Prompt Reverse Engineer") as demo:
|
|
| 95 |
journal={arXiv preprint arXiv:2308.12966},
|
| 96 |
year={2023}
|
| 97 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
""")
|
| 99 |
|
| 100 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
if __name__ == "__main__":
|
| 103 |
demo.launch()
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
import tempfile
|
| 3 |
+
|
| 4 |
import gradio as gr
|
| 5 |
+
import spaces
|
|
|
|
| 6 |
|
| 7 |
+
from inversion import EngineConfig, iter_inversion
|
| 8 |
+
from inversion.backends import BackendSettings, load_components
|
| 9 |
+
from inversion.engine import Backends
|
| 10 |
|
| 11 |
+
SETTINGS = BackendSettings()
|
| 12 |
+
C = load_components(SETTINGS)
|
|
|
|
| 13 |
|
| 14 |
|
| 15 |
+
# Each model call gets its own (short) ZeroGPU allocation instead of one long one
|
| 16 |
+
# for the whole loop. Outside Spaces/ZeroGPU, @spaces.GPU is a no-op.
|
| 17 |
+
@spaces.GPU(duration=180)
|
| 18 |
+
def gpu_extract(image):
|
| 19 |
+
return C.vlm.extract_dsg(image)
|
| 20 |
|
| 21 |
+
|
| 22 |
+
@spaces.GPU(duration=90)
|
| 23 |
+
def gpu_vqa(image, statements, template):
|
| 24 |
+
return C.scorer.vqa_scores(image, statements, template)
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
@spaces.GPU(duration=120)
|
| 28 |
+
def gpu_rewrite(og, proxy, prompt, failed):
|
| 29 |
+
return C.vlm.rewrite(og, proxy, prompt, failed)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
@spaces.GPU(duration=60)
|
| 33 |
+
def gpu_render(prompt, seed, width, height):
|
| 34 |
+
return C.renderer(prompt, seed, width, height)
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@spaces.GPU(duration=30)
|
| 38 |
+
def gpu_embed(image):
|
| 39 |
+
return C.dino.embed(image)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
BACKENDS = Backends(extract_dsg=gpu_extract, vqa_scores=gpu_vqa, rewrite=gpu_rewrite,
|
| 43 |
+
render=gpu_render, embed=gpu_embed)
|
| 44 |
+
|
| 45 |
+
ITER_HEADERS = ["t", "seed", "S_VQA", "S_DINO (patch)", "DINO (CLS)", "joint", "failed", "edits applied"]
|
| 46 |
+
PRED_HEADERS = ["kind", "statement", "P(yes)", "effective", "status"]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _iteration_rows(run):
|
| 50 |
+
rows = []
|
| 51 |
+
for it in run.iterations:
|
| 52 |
+
applied = "" if it.patch is None else f"{len(it.patch.applied)} (+{len(it.patch.added)} added)"
|
| 53 |
+
if it.rewrite_error:
|
| 54 |
+
applied = "rewrite error"
|
| 55 |
+
rows.append([it.t, it.seed, round(it.mean_vqa, 3), round(it.dino_patch, 3), round(it.dino_cls, 3),
|
| 56 |
+
round(it.joint, 3), len(it.failed), applied])
|
| 57 |
+
return rows
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _predicate_rows(run, fail_threshold):
|
| 61 |
+
best = run.best
|
| 62 |
+
if best is None:
|
| 63 |
+
return [[p.kind, p.statement, None, None, "pending"] for p in run.predicates]
|
| 64 |
+
rows = []
|
| 65 |
+
for sp in best.scored:
|
| 66 |
+
status = ("blocked: " + ", ".join(sp.blocked_by)) if sp.blocked_by else (
|
| 67 |
+
"pass" if sp.effective >= fail_threshold else "FAIL")
|
| 68 |
+
rows.append([sp.predicate.kind, sp.predicate.statement, round(sp.raw, 3), round(sp.effective, 3), status])
|
| 69 |
+
return rows
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _outputs(run, fail_threshold, report_path=None):
|
| 73 |
+
gallery = [(it.proxy_image, f"t={it.t} · VQA {it.mean_vqa:.2f} · DINO {it.dino_patch:.2f}"
|
| 74 |
+
+ (" · best" if it is run.best else "")) for it in run.iterations]
|
| 75 |
+
dropped = [[sp.predicate.kind, sp.predicate.statement, round(sp.raw, 3)] for sp in run.dropped]
|
| 76 |
+
dropped += [["position → re-localized", f"{m['entity']}: {m['from']} → {m['to']}", m["p_yes"]]
|
| 77 |
+
for m in run.relocalized]
|
| 78 |
+
return (
|
| 79 |
+
f"**Status:** {run.status}",
|
| 80 |
+
run.best_prompt,
|
| 81 |
+
gallery,
|
| 82 |
+
_iteration_rows(run),
|
| 83 |
+
_predicate_rows(run, fail_threshold),
|
| 84 |
+
run.graph.model_dump() if run.graph else None,
|
| 85 |
+
dropped,
|
| 86 |
+
report_path,
|
| 87 |
)
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def invert(image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground):
|
| 91 |
+
if image is None:
|
| 92 |
+
raise gr.Error("Upload an image.")
|
| 93 |
+
cfg = EngineConfig(max_iters=int(max_iters), vqa_gate=vqa_gate, dino_gate=dino_gate,
|
| 94 |
+
fail_threshold=fail_threshold, w_vqa=w_vqa, w_dino=round(1 - w_vqa, 4),
|
| 95 |
+
base_seed=int(base_seed), ground=bool(ground))
|
| 96 |
+
run = None
|
| 97 |
+
for run in iter_inversion(image, BACKENDS, cfg):
|
| 98 |
+
yield _outputs(run, fail_threshold)
|
| 99 |
+
assert run is not None
|
| 100 |
+
with tempfile.NamedTemporaryFile("w", suffix=".json", prefix="inversion_report_", delete=False,
|
| 101 |
+
encoding="utf-8") as f:
|
| 102 |
+
json.dump(run.to_dict(), f, indent=2)
|
| 103 |
+
yield _outputs(run, fail_threshold, f.name)
|
| 104 |
|
| 105 |
|
| 106 |
with gr.Blocks(title="Prompt Reverse Engineer") as demo:
|
| 107 |
gr.Markdown("# Prompt Reverse Engineer")
|
| 108 |
+
gr.Markdown("## Image → Verified Prompt")
|
| 109 |
+
gr.Markdown(
|
| 110 |
+
"Closed-loop inversion: **(1)** a constrained Davidsonian scene graph is extracted on a 3×3 grid, "
|
| 111 |
+
"**(2)** compiled into dependency-ordered yes/no predicates and a canonical prompt, "
|
| 112 |
+
"**(3)** rendered by a fast proxy text-to-image model, and **(4)** verified with VQAScore + DINOv2 patch "
|
| 113 |
+
"similarity. Only failed predicates are rewritten, until S_VQA and S_DINO clear their gates."
|
| 114 |
+
)
|
| 115 |
|
| 116 |
with gr.Row():
|
| 117 |
+
with gr.Column(scale=1):
|
| 118 |
+
image = gr.Image(type="pil", label="Original image")
|
| 119 |
+
max_iters = gr.Slider(1, 8, value=5, step=1, label="Max iterations (t)")
|
| 120 |
+
vqa_gate = gr.Slider(0.5, 1.0, value=0.90, step=0.01, label="S_VQA gate")
|
| 121 |
+
dino_gate = gr.Slider(0.3, 1.0, value=0.80, step=0.01, label="S_DINO gate (patch cosine)")
|
| 122 |
+
with gr.Accordion("Advanced", open=False):
|
| 123 |
+
fail_threshold = gr.Slider(0.3, 0.95, value=0.75, step=0.01,
|
| 124 |
+
label="Predicate failure threshold (sent to rewriter)")
|
| 125 |
+
w_vqa = gr.Slider(0.0, 1.0, value=0.7, step=0.05, label="Joint-score weight on S_VQA (rest on DINO)")
|
| 126 |
+
base_seed = gr.Number(value=42, precision=0, label="Base proxy seed (seed = base + t)")
|
| 127 |
+
ground = gr.Checkbox(value=True, label="Ground predicates on the original (prune hallucinations)")
|
| 128 |
+
run_button = gr.Button("Invert", variant="primary")
|
| 129 |
+
|
| 130 |
+
with gr.Column(scale=2):
|
| 131 |
+
status = gr.Markdown("**Status:** idle")
|
| 132 |
+
best_prompt = gr.Textbox(label="Verified prompt P*", lines=10, interactive=False, buttons=["copy"])
|
| 133 |
+
gallery = gr.Gallery(label="Proxy renders Î(t)", columns=3, height="auto")
|
| 134 |
+
iterations = gr.Dataframe(headers=ITER_HEADERS, label="Iterations", interactive=False)
|
| 135 |
+
|
| 136 |
+
with gr.Accordion("Predicates (best iteration)", open=False):
|
| 137 |
+
predicates = gr.Dataframe(headers=PRED_HEADERS, interactive=False, wrap=True)
|
| 138 |
+
with gr.Accordion("Scene graph G (after grounding)", open=False):
|
| 139 |
+
graph_json = gr.JSON()
|
| 140 |
+
with gr.Accordion("Grounding: predicates pruned as hallucinations", open=False):
|
| 141 |
+
dropped = gr.Dataframe(headers=["kind", "statement", "P(yes) on original"], interactive=False, wrap=True)
|
| 142 |
+
report = gr.File(label="Run report (JSON)")
|
| 143 |
+
|
| 144 |
+
gr.Markdown("Author: Larrain, G")
|
| 145 |
+
|
| 146 |
+
with gr.Accordion("References", open=False):
|
| 147 |
+
gr.Markdown("""
|
| 148 |
@misc{qwen3technicalreport,
|
| 149 |
title={Qwen3 Technical Report},
|
| 150 |
author={Qwen Team},
|
|
|
|
| 175 |
journal={arXiv preprint arXiv:2308.12966},
|
| 176 |
year={2023}
|
| 177 |
}
|
| 178 |
+
|
| 179 |
+
@inproceedings{cho2024dsg,
|
| 180 |
+
title={Davidsonian Scene Graph: Improving Reliability in Fine-grained Evaluation for Text-to-Image Generation},
|
| 181 |
+
author={Cho, Jaemin and Hu, Yushi and Garg, Roopal and Anderson, Peter and Krishna, Ranjay and Baldridge, Jason and Bansal, Mohit and Pont-Tuset, Jordi and Wang, Su},
|
| 182 |
+
booktitle={International Conference on Learning Representations (ICLR)},
|
| 183 |
+
year={2024}
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
@inproceedings{lin2024vqascore,
|
| 187 |
+
title={Evaluating Text-to-Visual Generation with Image-to-Text Generation},
|
| 188 |
+
author={Lin, Zhiqiu and Pathak, Deepak and Li, Baiqi and Li, Jiayao and Xia, Xide and Neubig, Graham and Zhang, Pengchuan and Ramanan, Deva},
|
| 189 |
+
booktitle={European Conference on Computer Vision (ECCV)},
|
| 190 |
+
year={2024}
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
@article{oquab2024dinov2,
|
| 194 |
+
title={DINOv2: Learning Robust Visual Features without Supervision},
|
| 195 |
+
author={Oquab, Maxime and Darcet, Timoth{\\'e}e and Moutakanni, Th{\\'e}o and others},
|
| 196 |
+
journal={Transactions on Machine Learning Research (TMLR)},
|
| 197 |
+
year={2024}
|
| 198 |
+
}
|
| 199 |
+
|
| 200 |
+
@article{simeoni2025dinov3,
|
| 201 |
+
title={DINOv3},
|
| 202 |
+
author={Sim{\\'e}oni, Oriane and others},
|
| 203 |
+
journal={arXiv preprint arXiv:2508.10104},
|
| 204 |
+
year={2025}
|
| 205 |
+
}
|
| 206 |
+
|
| 207 |
+
@misc{flux2024,
|
| 208 |
+
title={FLUX},
|
| 209 |
+
author={{Black Forest Labs}},
|
| 210 |
+
year={2024},
|
| 211 |
+
howpublished={https://github.com/black-forest-labs/flux}
|
| 212 |
+
}
|
| 213 |
""")
|
| 214 |
|
| 215 |
+
run_button.click(
|
| 216 |
+
invert,
|
| 217 |
+
[image, max_iters, vqa_gate, dino_gate, fail_threshold, w_vqa, base_seed, ground],
|
| 218 |
+
[status, best_prompt, gallery, iterations, predicates, graph_json, dropped, report],
|
| 219 |
+
)
|
| 220 |
|
| 221 |
if __name__ == "__main__":
|
| 222 |
demo.launch()
|
cli.py
ADDED
|
@@ -0,0 +1,124 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Batch tooling for the stimulus bank.
|
| 2 |
+
|
| 3 |
+
python cli.py invert --input stimuli/ --out runs/ # lock P*_k for every S_k
|
| 4 |
+
python cli.py medoid --input renders/ --out medoids.json # DINO medoid of the seeds per condition
|
| 5 |
+
|
| 6 |
+
Model backends are configured with the environment variables documented in
|
| 7 |
+
inversion/backends.py (local Qwen3-VL + FLUX by default; API pathway available).
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import argparse
|
| 13 |
+
import csv
|
| 14 |
+
import json
|
| 15 |
+
import shutil
|
| 16 |
+
import sys
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
|
| 19 |
+
from PIL import Image
|
| 20 |
+
|
| 21 |
+
IMAGE_EXTS = {".png", ".jpg", ".jpeg", ".webp", ".bmp", ".tif", ".tiff"}
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _images(path: Path) -> list[Path]:
|
| 25 |
+
if path.is_file():
|
| 26 |
+
return [path]
|
| 27 |
+
return sorted(p for p in path.iterdir() if p.suffix.lower() in IMAGE_EXTS)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def cmd_invert(args: argparse.Namespace) -> int:
|
| 31 |
+
from inversion import EngineConfig, iter_inversion, save_run
|
| 32 |
+
from inversion.backends import load_components
|
| 33 |
+
|
| 34 |
+
images = _images(Path(args.input))
|
| 35 |
+
if not images:
|
| 36 |
+
print(f"no images found in {args.input}", file=sys.stderr)
|
| 37 |
+
return 1
|
| 38 |
+
cfg = EngineConfig(max_iters=args.max_iters, vqa_gate=args.vqa_gate, dino_gate=args.dino_gate,
|
| 39 |
+
fail_threshold=args.fail_threshold, w_vqa=args.w_vqa, w_dino=round(1 - args.w_vqa, 4),
|
| 40 |
+
base_seed=args.seed, ground=not args.no_ground)
|
| 41 |
+
backends = load_components().backends()
|
| 42 |
+
out_root = Path(args.out)
|
| 43 |
+
summary = []
|
| 44 |
+
for path in images:
|
| 45 |
+
og = Image.open(path).convert("RGB")
|
| 46 |
+
print(f"\n=== {path.name}")
|
| 47 |
+
run = None
|
| 48 |
+
for run in iter_inversion(og, backends, cfg):
|
| 49 |
+
print(f" {run.status}", flush=True)
|
| 50 |
+
save_run(run, out_root / path.stem, og)
|
| 51 |
+
best = run.best
|
| 52 |
+
summary.append({"image": path.name, "stop_reason": run.stop_reason, "best_t": best.t,
|
| 53 |
+
"S_VQA": round(best.mean_vqa, 4), "S_DINO_patch": round(best.dino_patch, 4),
|
| 54 |
+
"joint": round(best.joint, 4), "n_predicates": len(run.predicates),
|
| 55 |
+
"n_grounding_dropped": len(run.dropped), "best_prompt": run.best_prompt})
|
| 56 |
+
with open(out_root / "summary.csv", "w", newline="", encoding="utf-8") as f:
|
| 57 |
+
writer = csv.DictWriter(f, fieldnames=list(summary[0]))
|
| 58 |
+
writer.writeheader()
|
| 59 |
+
writer.writerows(summary)
|
| 60 |
+
print(f"\nwrote {out_root / 'summary.csv'}")
|
| 61 |
+
return 0
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def cmd_medoid(args: argparse.Namespace) -> int:
|
| 65 |
+
import os
|
| 66 |
+
|
| 67 |
+
from inversion.dino import DEFAULT_DINO_MODEL, DinoEmbedder, medoid_index
|
| 68 |
+
|
| 69 |
+
root = Path(args.input)
|
| 70 |
+
# Each subdirectory with images is one condition (e.g. renders/S1_nano_banana/seed*.png);
|
| 71 |
+
# a flat directory of images is treated as a single condition.
|
| 72 |
+
conditions = {d.name: _images(d) for d in sorted(root.iterdir()) if d.is_dir() and _images(d)}
|
| 73 |
+
if not conditions and _images(root):
|
| 74 |
+
conditions = {root.name: _images(root)}
|
| 75 |
+
if not conditions:
|
| 76 |
+
print(f"no images found under {root}", file=sys.stderr)
|
| 77 |
+
return 1
|
| 78 |
+
|
| 79 |
+
dino = DinoEmbedder(os.getenv("DINO_MODEL_ID") or DEFAULT_DINO_MODEL)
|
| 80 |
+
result = {}
|
| 81 |
+
for name, paths in conditions.items():
|
| 82 |
+
embs = [dino.embed(Image.open(p)) for p in paths]
|
| 83 |
+
idx, mean_sims = medoid_index(embs, key=args.key)
|
| 84 |
+
result[name] = {"medoid": str(paths[idx]),
|
| 85 |
+
"mean_similarity": {str(p): round(s, 4) for p, s in zip(paths, mean_sims)}}
|
| 86 |
+
print(f"{name}: medoid = {paths[idx].name} (mean {args.key} cosine {mean_sims[idx]:.3f})")
|
| 87 |
+
if args.copy_to:
|
| 88 |
+
dest = Path(args.copy_to)
|
| 89 |
+
dest.mkdir(parents=True, exist_ok=True)
|
| 90 |
+
shutil.copy2(paths[idx], dest / f"{name}{paths[idx].suffix}")
|
| 91 |
+
Path(args.out).write_text(json.dumps(result, indent=2), encoding="utf-8")
|
| 92 |
+
print(f"wrote {args.out}")
|
| 93 |
+
return 0
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
def main(argv: list[str] | None = None) -> int:
|
| 97 |
+
parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
|
| 98 |
+
sub = parser.add_subparsers(dest="cmd", required=True)
|
| 99 |
+
|
| 100 |
+
inv = sub.add_parser("invert", help="run the closed-loop inversion on an image or a folder of images")
|
| 101 |
+
inv.add_argument("--input", required=True)
|
| 102 |
+
inv.add_argument("--out", default="runs")
|
| 103 |
+
inv.add_argument("--max-iters", type=int, default=5)
|
| 104 |
+
inv.add_argument("--vqa-gate", type=float, default=0.90)
|
| 105 |
+
inv.add_argument("--dino-gate", type=float, default=0.80)
|
| 106 |
+
inv.add_argument("--fail-threshold", type=float, default=0.75)
|
| 107 |
+
inv.add_argument("--w-vqa", type=float, default=0.7)
|
| 108 |
+
inv.add_argument("--seed", type=int, default=42)
|
| 109 |
+
inv.add_argument("--no-ground", action="store_true", help="skip pruning predicates false on the original")
|
| 110 |
+
inv.set_defaults(func=cmd_invert)
|
| 111 |
+
|
| 112 |
+
med = sub.add_parser("medoid", help="select the DINO medoid render per condition folder")
|
| 113 |
+
med.add_argument("--input", required=True)
|
| 114 |
+
med.add_argument("--out", default="medoids.json")
|
| 115 |
+
med.add_argument("--key", choices=["patch", "cls"], default="patch")
|
| 116 |
+
med.add_argument("--copy-to", help="optional folder to copy each condition's medoid into")
|
| 117 |
+
med.set_defaults(func=cmd_medoid)
|
| 118 |
+
|
| 119 |
+
args = parser.parse_args(argv)
|
| 120 |
+
return args.func(args)
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
if __name__ == "__main__":
|
| 124 |
+
sys.exit(main())
|
inversion/__init__.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Closed-loop DSG + VQA image-to-prompt inversion engine."""
|
| 2 |
+
|
| 3 |
+
from .compiler import apply_dependencies, apply_patch, compile_predicates, linearize, prune_hallucinations
|
| 4 |
+
from .engine import (Backends, EngineConfig, InversionRun, invert_image_to_verified_prompt, iter_inversion,
|
| 5 |
+
save_run)
|
| 6 |
+
from .schema import DSGSceneSchema, RewritePatch, SpatialNode
|
| 7 |
+
|
| 8 |
+
__all__ = [
|
| 9 |
+
"Backends", "DSGSceneSchema", "EngineConfig", "InversionRun", "RewritePatch", "SpatialNode",
|
| 10 |
+
"apply_dependencies", "apply_patch", "compile_predicates", "invert_image_to_verified_prompt",
|
| 11 |
+
"iter_inversion", "linearize", "prune_hallucinations", "save_run",
|
| 12 |
+
]
|
inversion/backends.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Build model components from environment variables (one place for all deployment knobs).
|
| 2 |
+
|
| 3 |
+
Pathway B (local / HPC / HF Space GPU) is the default:
|
| 4 |
+
VLM_BACKEND=local, PROXY_BACKEND=flux -> Qwen3-VL-8B + FLUX.1-schnell + DINOv2-B, all local.
|
| 5 |
+
Pathway A (no local GPU):
|
| 6 |
+
VLM_BACKEND=api VLM_API_KEY=... (OpenRouter by default, Qwen3-VL-32B-Instruct)
|
| 7 |
+
SCORER_BACKEND=api OPENAI_API_KEY=... (gpt-4o logprobs for VQAScore)
|
| 8 |
+
PROXY_BACKEND=fal FAL_KEY=...
|
| 9 |
+
DINO_MODEL_ID=facebook/dinov2-small (small, CPU-friendly)
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
from __future__ import annotations
|
| 13 |
+
|
| 14 |
+
import os
|
| 15 |
+
from dataclasses import dataclass, field
|
| 16 |
+
from typing import TYPE_CHECKING, Callable
|
| 17 |
+
|
| 18 |
+
from PIL import Image
|
| 19 |
+
|
| 20 |
+
from .dino import DEFAULT_DINO_MODEL
|
| 21 |
+
from .engine import Backends
|
| 22 |
+
|
| 23 |
+
if TYPE_CHECKING:
|
| 24 |
+
from .dino import DinoEmbedder
|
| 25 |
+
from .vlm import VLMBase
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _env(name: str, default: str | None = None) -> str | None:
|
| 29 |
+
value = os.getenv(name)
|
| 30 |
+
return value if value not in (None, "") else default
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@dataclass
|
| 34 |
+
class BackendSettings:
|
| 35 |
+
vlm_backend: str = field(default_factory=lambda: _env("VLM_BACKEND", "local"))
|
| 36 |
+
vlm_model_id: str = field(default_factory=lambda: _env("VLM_MODEL_ID", "Qwen/Qwen3-VL-8B-Instruct"))
|
| 37 |
+
vlm_api_model: str = field(default_factory=lambda: _env("VLM_API_MODEL", "qwen/qwen3-vl-32b-instruct"))
|
| 38 |
+
vlm_api_base_url: str | None = field(
|
| 39 |
+
default_factory=lambda: _env("VLM_API_BASE_URL", "https://openrouter.ai/api/v1"))
|
| 40 |
+
vlm_api_key: str | None = field(default_factory=lambda: _env("VLM_API_KEY"))
|
| 41 |
+
|
| 42 |
+
# Defaults to sharing the VLM's weights when local (Module 1/4A/rewriter on one model).
|
| 43 |
+
scorer_backend: str | None = field(default_factory=lambda: _env("SCORER_BACKEND"))
|
| 44 |
+
scorer_api_model: str = field(default_factory=lambda: _env("SCORER_API_MODEL", "gpt-4o"))
|
| 45 |
+
scorer_api_base_url: str | None = field(default_factory=lambda: _env("SCORER_API_BASE_URL"))
|
| 46 |
+
scorer_api_key: str | None = field(
|
| 47 |
+
default_factory=lambda: _env("SCORER_API_KEY", _env("OPENAI_API_KEY")))
|
| 48 |
+
|
| 49 |
+
proxy_backend: str = field(default_factory=lambda: _env("PROXY_BACKEND", "flux"))
|
| 50 |
+
proxy_model_id: str = field(default_factory=lambda: _env("PROXY_MODEL_ID", "black-forest-labs/FLUX.1-schnell"))
|
| 51 |
+
proxy_cpu_offload: bool = field(default_factory=lambda: _env("PROXY_CPU_OFFLOAD", "0") == "1")
|
| 52 |
+
fal_endpoint: str = field(default_factory=lambda: _env("FAL_ENDPOINT", "fal-ai/flux/schnell"))
|
| 53 |
+
|
| 54 |
+
vqa_mode: str = field(default_factory=lambda: _env("VQA_MODE", "normalized"))
|
| 55 |
+
|
| 56 |
+
dino_model_id: str = field(
|
| 57 |
+
default_factory=lambda: _env("DINO_MODEL_ID", DEFAULT_DINO_MODEL))
|
| 58 |
+
dino_device: str | None = field(default_factory=lambda: _env("DINO_DEVICE"))
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass
|
| 62 |
+
class Components:
|
| 63 |
+
vlm: VLMBase
|
| 64 |
+
scorer: VLMBase
|
| 65 |
+
renderer: Callable[[str, int, int, int], Image.Image]
|
| 66 |
+
dino: DinoEmbedder
|
| 67 |
+
|
| 68 |
+
def backends(self) -> Backends:
|
| 69 |
+
return Backends(
|
| 70 |
+
extract_dsg=self.vlm.extract_dsg,
|
| 71 |
+
vqa_scores=self.scorer.vqa_scores,
|
| 72 |
+
rewrite=self.vlm.rewrite,
|
| 73 |
+
render=self.renderer,
|
| 74 |
+
embed=self.dino.embed,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def load_components(settings: BackendSettings | None = None) -> Components:
|
| 79 |
+
s = settings or BackendSettings()
|
| 80 |
+
from .dino import DinoEmbedder
|
| 81 |
+
from .vlm import LocalQwenVLM, OpenAICompatVLM
|
| 82 |
+
|
| 83 |
+
if s.vlm_backend == "local":
|
| 84 |
+
vlm = LocalQwenVLM(s.vlm_model_id, vqa_mode=s.vqa_mode)
|
| 85 |
+
elif s.vlm_backend == "api":
|
| 86 |
+
vlm = OpenAICompatVLM(s.vlm_api_model, base_url=s.vlm_api_base_url, api_key=s.vlm_api_key,
|
| 87 |
+
vqa_mode=s.vqa_mode)
|
| 88 |
+
else:
|
| 89 |
+
raise ValueError(f"VLM_BACKEND must be 'local' or 'api', got {s.vlm_backend!r}")
|
| 90 |
+
|
| 91 |
+
scorer_backend = s.scorer_backend or ("local" if s.vlm_backend == "local" else "api")
|
| 92 |
+
if scorer_backend == "local":
|
| 93 |
+
scorer = vlm if isinstance(vlm, LocalQwenVLM) else LocalQwenVLM(s.vlm_model_id, vqa_mode=s.vqa_mode)
|
| 94 |
+
elif scorer_backend == "api":
|
| 95 |
+
scorer = OpenAICompatVLM(s.scorer_api_model, base_url=s.scorer_api_base_url, api_key=s.scorer_api_key,
|
| 96 |
+
vqa_mode=s.vqa_mode)
|
| 97 |
+
else:
|
| 98 |
+
raise ValueError(f"SCORER_BACKEND must be 'local' or 'api', got {scorer_backend!r}")
|
| 99 |
+
|
| 100 |
+
if s.proxy_backend == "flux":
|
| 101 |
+
from .proxy import FluxSchnellRenderer
|
| 102 |
+
renderer = FluxSchnellRenderer(s.proxy_model_id, cpu_offload=s.proxy_cpu_offload)
|
| 103 |
+
elif s.proxy_backend == "fal":
|
| 104 |
+
from .proxy import FalRenderer
|
| 105 |
+
renderer = FalRenderer(s.fal_endpoint)
|
| 106 |
+
else:
|
| 107 |
+
raise ValueError(f"PROXY_BACKEND must be 'flux' or 'fal', got {s.proxy_backend!r}")
|
| 108 |
+
|
| 109 |
+
dino = DinoEmbedder(s.dino_model_id, device=s.dino_device)
|
| 110 |
+
return Components(vlm=vlm, scorer=scorer, renderer=renderer, dino=dino)
|
inversion/compiler.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module 2: dependency predicate compiler, canonical linearizer, and diff applier.
|
| 2 |
+
|
| 3 |
+
Predicates follow the Davidsonian Scene Graph (DSG) dependency rule: an
|
| 4 |
+
attribute, position, or relation question is only credited when every parent
|
| 5 |
+
entity it depends on is itself judged present. Children of a failed parent
|
| 6 |
+
are "blocked" and score 0, so a relation is never rewarded when its objects
|
| 7 |
+
are missing.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import copy
|
| 13 |
+
import re
|
| 14 |
+
from dataclasses import asdict, dataclass, field
|
| 15 |
+
|
| 16 |
+
from .schema import GRID_ORDER, GRID_PHRASE, DSGSceneSchema, RewritePatch
|
| 17 |
+
|
| 18 |
+
KIND_ORDER = ("global", "entity", "attribute", "position", "relation")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
@dataclass
|
| 22 |
+
class Predicate:
|
| 23 |
+
id: str
|
| 24 |
+
kind: str # one of KIND_ORDER
|
| 25 |
+
statement: str # noun phrase / clause inserted into the VQA question template
|
| 26 |
+
parents: list[str] = field(default_factory=list)
|
| 27 |
+
# Where in the graph this fact came from, used to prune hallucinations.
|
| 28 |
+
ref: dict = field(default_factory=dict)
|
| 29 |
+
|
| 30 |
+
def to_dict(self) -> dict:
|
| 31 |
+
return asdict(self)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@dataclass
|
| 35 |
+
class ScoredPredicate:
|
| 36 |
+
predicate: Predicate
|
| 37 |
+
raw: float # P("Yes") from the scorer
|
| 38 |
+
effective: float # raw, or 0.0 when a parent failed
|
| 39 |
+
blocked_by: list[str] = field(default_factory=list)
|
| 40 |
+
|
| 41 |
+
def passed(self, threshold: float) -> bool:
|
| 42 |
+
return self.effective >= threshold
|
| 43 |
+
|
| 44 |
+
def to_dict(self) -> dict:
|
| 45 |
+
return {
|
| 46 |
+
"id": self.predicate.id,
|
| 47 |
+
"kind": self.predicate.kind,
|
| 48 |
+
"statement": self.predicate.statement,
|
| 49 |
+
"parents": self.predicate.parents,
|
| 50 |
+
"p_yes": round(self.raw, 4),
|
| 51 |
+
"effective": round(self.effective, 4),
|
| 52 |
+
"blocked_by": self.blocked_by,
|
| 53 |
+
}
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
# --------------------------------------------------------------------------- text helpers
|
| 57 |
+
|
| 58 |
+
_ARTICLE = re.compile(r"^(a|an|one|some)\s+", re.IGNORECASE)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def definite(np: str) -> str:
|
| 62 |
+
"""'a red circle' -> 'the red circle' (leaves already-definite phrases alone)."""
|
| 63 |
+
text = np.strip()
|
| 64 |
+
if re.match(r"^the\s", text, re.IGNORECASE):
|
| 65 |
+
return text
|
| 66 |
+
if _ARTICLE.match(text):
|
| 67 |
+
return _ARTICLE.sub("the ", text, count=1)
|
| 68 |
+
return f"the {text}"
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def _sentence(text: str) -> str:
|
| 72 |
+
text = " ".join(text.split()).strip()
|
| 73 |
+
if not text:
|
| 74 |
+
return ""
|
| 75 |
+
text = text[0].upper() + text[1:]
|
| 76 |
+
return text if text[-1] in ".!?" else text + "."
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _join_list(items: list[str]) -> str:
|
| 80 |
+
if len(items) <= 1:
|
| 81 |
+
return "".join(items)
|
| 82 |
+
if len(items) == 2:
|
| 83 |
+
return f"{items[0]} and {items[1]}"
|
| 84 |
+
return ", ".join(items[:-1]) + f", and {items[-1]}"
|
| 85 |
+
|
| 86 |
+
|
| 87 |
+
# --------------------------------------------------------------------------- compiler
|
| 88 |
+
|
| 89 |
+
def position_statement(entity: str, grid_cell: str) -> str:
|
| 90 |
+
return f"{entity} located in the {GRID_PHRASE[grid_cell]} region of the image"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
def _key(text: str) -> str:
|
| 94 |
+
return re.sub(r"[^a-z0-9]+", "_", text.lower()).strip("_")[:48]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def compile_predicates(graph: DSGSceneSchema) -> list[Predicate]:
|
| 98 |
+
"""Compile the scene graph into dependency-ordered binary VQA predicates.
|
| 99 |
+
|
| 100 |
+
Ids are keyed on content (not list position) so they stay stable when the
|
| 101 |
+
graph is pruned or recompiled.
|
| 102 |
+
"""
|
| 103 |
+
preds: list[Predicate] = []
|
| 104 |
+
|
| 105 |
+
for facet in graph.medium_and_optics:
|
| 106 |
+
preds.append(Predicate(f"medium:{_key(facet)}", "global", facet, ref={"field": "medium"}))
|
| 107 |
+
if graph.background:
|
| 108 |
+
preds.append(Predicate("background", "global", graph.background, ref={"field": "background"}))
|
| 109 |
+
for color in graph.color_palette:
|
| 110 |
+
preds.append(Predicate(f"palette:{_key(color)}", "global", f"the color {color}",
|
| 111 |
+
ref={"field": "palette", "value": color}))
|
| 112 |
+
for check in graph.extra_checks:
|
| 113 |
+
preds.append(Predicate(f"check:{_key(check)}", "global", check,
|
| 114 |
+
ref={"field": "extra_checks", "value": check}))
|
| 115 |
+
|
| 116 |
+
entity_id = {n.id: f"entity:{n.id}" for n in graph.nodes}
|
| 117 |
+
for n in graph.nodes:
|
| 118 |
+
preds.append(Predicate(entity_id[n.id], "entity", n.entity, ref={"node": n.id}))
|
| 119 |
+
for n in graph.nodes:
|
| 120 |
+
for attr in n.attributes:
|
| 121 |
+
preds.append(Predicate(f"attr:{n.id}:{_key(attr)}", "attribute", f"{n.entity} that is {attr}",
|
| 122 |
+
parents=[entity_id[n.id]], ref={"node": n.id, "attribute": attr}))
|
| 123 |
+
for n in graph.nodes:
|
| 124 |
+
preds.append(Predicate(f"pos:{n.id}", "position", position_statement(n.entity, n.grid_cell),
|
| 125 |
+
parents=[entity_id[n.id]], ref={"node": n.id, "grid_cell": n.grid_cell}))
|
| 126 |
+
for n in graph.nodes:
|
| 127 |
+
for rel in n.relations:
|
| 128 |
+
target = graph.node(rel.target_id)
|
| 129 |
+
preds.append(Predicate(
|
| 130 |
+
f"rel:{n.id}:{_key(rel.predicate)}:{target.id}", "relation",
|
| 131 |
+
f"{n.entity} that {rel.predicate} {definite(target.entity)}",
|
| 132 |
+
parents=[entity_id[n.id], entity_id[target.id]],
|
| 133 |
+
ref={"node": n.id, "relation": rel.model_dump()},
|
| 134 |
+
))
|
| 135 |
+
unique: dict[str, Predicate] = {}
|
| 136 |
+
for p in preds:
|
| 137 |
+
unique.setdefault(p.id, p)
|
| 138 |
+
return list(unique.values())
|
| 139 |
+
|
| 140 |
+
|
| 141 |
+
def apply_dependencies(predicates: list[Predicate], raw_scores: list[float],
|
| 142 |
+
parent_gate: float) -> list[ScoredPredicate]:
|
| 143 |
+
"""DSG rule: a child's score is zeroed when any parent scores below `parent_gate`."""
|
| 144 |
+
raw = {p.id: s for p, s in zip(predicates, raw_scores)}
|
| 145 |
+
out = []
|
| 146 |
+
for p, s in zip(predicates, raw_scores):
|
| 147 |
+
blocked = [par for par in p.parents if raw.get(par, 0.0) < parent_gate]
|
| 148 |
+
out.append(ScoredPredicate(p, float(s), 0.0 if blocked else float(s), blocked))
|
| 149 |
+
return out
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def prune_hallucinations(graph: DSGSceneSchema, scored: list[ScoredPredicate],
|
| 153 |
+
threshold: float) -> tuple[DSGSceneSchema, list[Predicate], list[ScoredPredicate]]:
|
| 154 |
+
"""Ground the graph against the OG image itself.
|
| 155 |
+
|
| 156 |
+
Facts the scorer rejects *on the original image* can never be satisfied by a
|
| 157 |
+
proxy render, so they are removed before the loop starts. Returns the pruned
|
| 158 |
+
graph, the surviving predicates, and the dropped (scored) predicates.
|
| 159 |
+
"""
|
| 160 |
+
g = copy.deepcopy(graph)
|
| 161 |
+
dropped = [sp for sp in scored if sp.effective < threshold]
|
| 162 |
+
dropped_ids = {sp.predicate.id for sp in dropped}
|
| 163 |
+
|
| 164 |
+
dead_nodes = {sp.predicate.ref["node"] for sp in dropped if sp.predicate.kind == "entity"}
|
| 165 |
+
if len(dead_nodes) == len(g.nodes): # never prune the graph to nothing
|
| 166 |
+
dead_nodes = set()
|
| 167 |
+
dropped = [sp for sp in dropped if sp.predicate.kind != "entity"]
|
| 168 |
+
dropped_ids = {sp.predicate.id for sp in dropped}
|
| 169 |
+
|
| 170 |
+
bad_attrs = {(sp.predicate.ref["node"], sp.predicate.ref["attribute"])
|
| 171 |
+
for sp in dropped if sp.predicate.kind == "attribute"}
|
| 172 |
+
bad_rels = {(sp.predicate.ref["node"], sp.predicate.ref["relation"]["predicate"],
|
| 173 |
+
sp.predicate.ref["relation"]["target_id"])
|
| 174 |
+
for sp in dropped if sp.predicate.kind == "relation"}
|
| 175 |
+
bad_colors = {sp.predicate.ref["value"] for sp in dropped if sp.predicate.ref.get("field") == "palette"}
|
| 176 |
+
bad_checks = {sp.predicate.ref["value"] for sp in dropped if sp.predicate.ref.get("field") == "extra_checks"}
|
| 177 |
+
bad_medium = {sp.predicate.statement for sp in dropped if sp.predicate.ref.get("field") == "medium"}
|
| 178 |
+
|
| 179 |
+
g.nodes = [n for n in g.nodes if n.id not in dead_nodes]
|
| 180 |
+
for n in g.nodes:
|
| 181 |
+
n.attributes = [a for a in n.attributes if (n.id, a) not in bad_attrs]
|
| 182 |
+
n.relations = [r for r in n.relations
|
| 183 |
+
if r.target_id not in dead_nodes and (n.id, r.predicate, r.target_id) not in bad_rels]
|
| 184 |
+
g.color_palette = [c for c in g.color_palette if c not in bad_colors]
|
| 185 |
+
g.extra_checks = [c for c in g.extra_checks if c not in bad_checks]
|
| 186 |
+
# Medium/optics facets rejected on the original are unverified style claims (e.g. an
|
| 187 |
+
# injected "shallow depth of field with soft bokeh"), so they leave the prompt too.
|
| 188 |
+
g.medium_and_optics = [m for m in g.medium_and_optics if m not in bad_medium]
|
| 189 |
+
# Background and grid position stay in the prompt (they are still the best available
|
| 190 |
+
# description; positions are re-localized by the engine); only their predicates are dropped.
|
| 191 |
+
|
| 192 |
+
surviving = [p for p in compile_predicates(g) if p.id not in dropped_ids]
|
| 193 |
+
return g, surviving, dropped
|
| 194 |
+
|
| 195 |
+
|
| 196 |
+
# --------------------------------------------------------------------------- linearizer
|
| 197 |
+
|
| 198 |
+
def linearize(graph: DSGSceneSchema) -> str:
|
| 199 |
+
"""Deterministically serialize the graph into the canonical prompt P_k^(0)."""
|
| 200 |
+
parts = [_sentence(", ".join(graph.medium_and_optics))]
|
| 201 |
+
if graph.background:
|
| 202 |
+
parts.append(_sentence(f"Background: {graph.background}"))
|
| 203 |
+
if graph.color_palette:
|
| 204 |
+
parts.append(_sentence(f"Color palette limited to {_join_list(graph.color_palette)}"))
|
| 205 |
+
|
| 206 |
+
by_id = {n.id: n for n in graph.nodes}
|
| 207 |
+
for cell in GRID_ORDER:
|
| 208 |
+
for n in (n for n in graph.nodes if n.grid_cell == cell):
|
| 209 |
+
desc = n.entity
|
| 210 |
+
if n.attributes:
|
| 211 |
+
desc += f" ({'; '.join(n.attributes)})"
|
| 212 |
+
text = f"In the {GRID_PHRASE[cell]} of the frame, {desc}"
|
| 213 |
+
rels = [f"{r.predicate} {definite(by_id[r.target_id].entity)}" for r in n.relations]
|
| 214 |
+
if rels:
|
| 215 |
+
text += f"; it {_join_list(rels)}"
|
| 216 |
+
parts.append(_sentence(text))
|
| 217 |
+
for check in graph.extra_checks:
|
| 218 |
+
parts.append(_sentence(f"The image shows {check}"))
|
| 219 |
+
return " ".join(p for p in parts if p)
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
# --------------------------------------------------------------------------- targeted diff
|
| 223 |
+
|
| 224 |
+
@dataclass
|
| 225 |
+
class PatchResult:
|
| 226 |
+
prompt: str
|
| 227 |
+
applied: list[dict]
|
| 228 |
+
skipped: list[dict]
|
| 229 |
+
added: list[str]
|
| 230 |
+
|
| 231 |
+
|
| 232 |
+
# Era / art-historical / aesthetic-hype vocabulary. Rewrites are not re-verified on the original,
|
| 233 |
+
# so a term from this list may only enter the prompt if the (grounded) prompt already contains it.
|
| 234 |
+
_BUZZWORDS = re.compile(
|
| 235 |
+
r"(?<![\w'])(?:"
|
| 236 |
+
r"(?:1[0-9]|20)\d0s|'\d0s|\d{1,2}(?:st|nd|rd|th)[- ]century|mid[- ]century|"
|
| 237 |
+
r"vintage|retro|old[- ]fashioned|antique|nostalgic|victorian|edwardian|"
|
| 238 |
+
r"cinematic|film still|masterpiece|award[- ]winning|trending|artstation|hyper[- ]?realistic|photorealistic|"
|
| 239 |
+
r"8k|4k|ultra[- ]detailed|epic|in the style of|style of|"
|
| 240 |
+
r"art deco|art nouveau|bauhaus|de stijl|dada(?:ism|ist)?|pop art|op art|renaissance|baroque|rococo|"
|
| 241 |
+
r"(?:cub|surreal|expression|impression|constructiv|supremat|futur|modern|minimal|fauv|orph|vortic)"
|
| 242 |
+
r"(?:ism|ist|istic)"
|
| 243 |
+
r")(?!\w)",
|
| 244 |
+
re.IGNORECASE,
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def buzzwords(text: str) -> set[str]:
|
| 249 |
+
"""Lower-cased era/style buzzwords found in `text`."""
|
| 250 |
+
return {m.group(0).lower() for m in _BUZZWORDS.finditer(text)}
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
def apply_patch(prompt: str, patch: RewritePatch) -> PatchResult:
|
| 254 |
+
"""Apply a targeted diff; spans not found verbatim are skipped, never guessed.
|
| 255 |
+
|
| 256 |
+
Edits and additions that would introduce an era/style buzzword absent from the
|
| 257 |
+
current prompt are skipped (unverified on the original image).
|
| 258 |
+
"""
|
| 259 |
+
new, applied, skipped = prompt, [], []
|
| 260 |
+
for edit in patch.edits:
|
| 261 |
+
orig, rev = edit.original.strip(), edit.revised.strip()
|
| 262 |
+
injected = buzzwords(rev) - buzzwords(new)
|
| 263 |
+
if not orig or orig == rev:
|
| 264 |
+
skipped.append({**edit.model_dump(), "reason": "empty or unchanged"})
|
| 265 |
+
elif injected:
|
| 266 |
+
skipped.append({**edit.model_dump(), "reason": f"unverified style/era terms: {sorted(injected)}"})
|
| 267 |
+
elif orig in new:
|
| 268 |
+
new = new.replace(orig, rev, 1)
|
| 269 |
+
applied.append(edit.model_dump())
|
| 270 |
+
else:
|
| 271 |
+
skipped.append({**edit.model_dump(), "reason": "original span not found verbatim"})
|
| 272 |
+
added = []
|
| 273 |
+
for sentence in (_sentence(a) for a in patch.additions):
|
| 274 |
+
if not sentence or sentence in new:
|
| 275 |
+
continue
|
| 276 |
+
injected = buzzwords(sentence) - buzzwords(new)
|
| 277 |
+
if injected:
|
| 278 |
+
skipped.append({"addition": sentence, "reason": f"unverified style/era terms: {sorted(injected)}"})
|
| 279 |
+
else:
|
| 280 |
+
added.append(sentence)
|
| 281 |
+
if added:
|
| 282 |
+
new = new.rstrip() + " " + " ".join(added)
|
| 283 |
+
return PatchResult(new, applied, skipped, added)
|
inversion/dino.py
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module 4B: DINO spatial-layout verifier and embedding medoid selection.
|
| 2 |
+
|
| 3 |
+
The default backbone is DINOv2 ViT-B/14 (ungated), as specified in the research plan (Pivot 1).
|
| 4 |
+
Any DINOv2/DINOv3 checkpoint works via DINO_MODEL_ID; patch tokens are always the last N
|
| 5 |
+
tokens, after CLS and any register tokens.
|
| 6 |
+
|
| 7 |
+
Both images are resized to the same square resolution so patch (i, j) of the
|
| 8 |
+
OG image is compared against patch (i, j) of the proxy. The mean per-patch
|
| 9 |
+
cosine is therefore sensitive to *where* things are (layout, left/right,
|
| 10 |
+
figure-ground), unlike a pooled CLS cosine, which is also reported.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from __future__ import annotations
|
| 14 |
+
|
| 15 |
+
from dataclasses import dataclass
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from PIL import Image
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
DEFAULT_DINO_MODEL = "facebook/dinov2-base"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@dataclass
|
| 26 |
+
class DinoEmbedding:
|
| 27 |
+
cls: torch.Tensor # [D], CPU float32
|
| 28 |
+
patches: torch.Tensor # [N, D], CPU float32, row-major patch grid
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DinoEmbedder:
|
| 32 |
+
def __init__(self, model_id: str = DEFAULT_DINO_MODEL, device: str | None = None,
|
| 33 |
+
resolution: int = 448):
|
| 34 |
+
from transformers import AutoImageProcessor, AutoModel
|
| 35 |
+
|
| 36 |
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 37 |
+
self.model = AutoModel.from_pretrained(model_id).to(self.device).eval()
|
| 38 |
+
proc = AutoImageProcessor.from_pretrained(model_id)
|
| 39 |
+
self.mean = torch.tensor(getattr(proc, "image_mean", None) or [0.485, 0.456, 0.406]).view(3, 1, 1)
|
| 40 |
+
self.std = torch.tensor(getattr(proc, "image_std", None) or [0.229, 0.224, 0.225]).view(3, 1, 1)
|
| 41 |
+
self.patch = int(getattr(self.model.config, "patch_size", 16))
|
| 42 |
+
self.resolution = resolution - resolution % self.patch
|
| 43 |
+
self.n_patches = (self.resolution // self.patch) ** 2
|
| 44 |
+
|
| 45 |
+
@torch.inference_mode()
|
| 46 |
+
def embed(self, image: Image.Image) -> DinoEmbedding:
|
| 47 |
+
img = image.convert("RGB").resize((self.resolution, self.resolution), Image.Resampling.BICUBIC)
|
| 48 |
+
x = torch.from_numpy(np.asarray(img, dtype=np.float32) / 255.0).permute(2, 0, 1)
|
| 49 |
+
x = ((x - self.mean) / self.std).unsqueeze(0).to(self.device, next(self.model.parameters()).dtype)
|
| 50 |
+
hidden = self.model(pixel_values=x).last_hidden_state[0].float().cpu()
|
| 51 |
+
# Layout: [CLS, register tokens..., patch tokens]; patch tokens are always the last N.
|
| 52 |
+
return DinoEmbedding(cls=hidden[0], patches=hidden[-self.n_patches:])
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def dino_similarity(a: DinoEmbedding, b: DinoEmbedding) -> dict[str, float]:
|
| 56 |
+
patch = torch.nn.functional.cosine_similarity(a.patches, b.patches, dim=-1).mean().item()
|
| 57 |
+
cls = torch.nn.functional.cosine_similarity(a.cls, b.cls, dim=-1).item()
|
| 58 |
+
return {"patch": patch, "cls": cls}
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def medoid_index(embeddings: list[DinoEmbedding], key: str = "patch") -> tuple[int, list[float]]:
|
| 62 |
+
"""Index of the embedding with the highest mean similarity to all others."""
|
| 63 |
+
n = len(embeddings)
|
| 64 |
+
if n == 1:
|
| 65 |
+
return 0, [1.0]
|
| 66 |
+
means = []
|
| 67 |
+
for i in range(n):
|
| 68 |
+
sims = [dino_similarity(embeddings[i], embeddings[j])[key] for j in range(n) if j != i]
|
| 69 |
+
means.append(sum(sims) / len(sims))
|
| 70 |
+
return int(np.argmax(means)), means
|
inversion/engine.py
ADDED
|
@@ -0,0 +1,248 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Closed-loop inversion engine: extract -> ground -> linearize -> (render -> verify -> diff-rewrite)*.
|
| 2 |
+
|
| 3 |
+
The engine is a generator that yields the same `InversionRun` after every stage,
|
| 4 |
+
so UIs can stream progress. Model work goes through the `Backends` callables,
|
| 5 |
+
which lets the Space wrap each one in its own ZeroGPU allocation and lets tests
|
| 6 |
+
substitute stubs.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import json
|
| 12 |
+
from dataclasses import asdict, dataclass, field
|
| 13 |
+
from pathlib import Path
|
| 14 |
+
from typing import Callable, Iterator
|
| 15 |
+
|
| 16 |
+
from PIL import Image
|
| 17 |
+
|
| 18 |
+
from .compiler import (PatchResult, Predicate, ScoredPredicate, apply_dependencies, apply_patch,
|
| 19 |
+
compile_predicates, linearize, position_statement, prune_hallucinations)
|
| 20 |
+
from .dino import DinoEmbedding, dino_similarity
|
| 21 |
+
from .proxy import proxy_size
|
| 22 |
+
from .schema import GRID_ORDER, DSGSceneSchema, RewritePatch
|
| 23 |
+
from .vlm import VQA_TEMPLATE
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
@dataclass
|
| 27 |
+
class EngineConfig:
|
| 28 |
+
max_iters: int = 5
|
| 29 |
+
vqa_gate: float = 0.90 # stop when mean effective VQAScore >= this ...
|
| 30 |
+
dino_gate: float = 0.80 # ... AND DINO patch cosine >= this
|
| 31 |
+
fail_threshold: float = 0.75 # predicates below this are sent to the rewriter
|
| 32 |
+
parent_gate: float = 0.5 # DSG: children of a parent below this are blocked (scored 0)
|
| 33 |
+
ground: bool = True # verify extracted predicates on the OG image and prune hallucinations
|
| 34 |
+
grounding_threshold: float = 0.5
|
| 35 |
+
w_vqa: float = 0.7
|
| 36 |
+
w_dino: float = 0.3
|
| 37 |
+
base_seed: int = 42 # proxy seed at iteration t is base_seed + t
|
| 38 |
+
proxy_long_side: int = 1024
|
| 39 |
+
question_template: str = VQA_TEMPLATE
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass
|
| 43 |
+
class Backends:
|
| 44 |
+
extract_dsg: Callable[[Image.Image], DSGSceneSchema]
|
| 45 |
+
vqa_scores: Callable[[Image.Image, list[str], str], list[float]]
|
| 46 |
+
rewrite: Callable[[Image.Image, Image.Image, str, list[str]], RewritePatch]
|
| 47 |
+
render: Callable[[str, int, int, int], Image.Image]
|
| 48 |
+
embed: Callable[[Image.Image], DinoEmbedding]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@dataclass
|
| 52 |
+
class IterationRecord:
|
| 53 |
+
t: int
|
| 54 |
+
seed: int
|
| 55 |
+
prompt: str
|
| 56 |
+
proxy_image: Image.Image
|
| 57 |
+
scored: list[ScoredPredicate]
|
| 58 |
+
mean_vqa: float
|
| 59 |
+
dino_patch: float
|
| 60 |
+
dino_cls: float
|
| 61 |
+
joint: float
|
| 62 |
+
failed: list[ScoredPredicate]
|
| 63 |
+
rewrite_notes: list[str] = field(default_factory=list)
|
| 64 |
+
patch: PatchResult | None = None
|
| 65 |
+
rewrite_error: str | None = None
|
| 66 |
+
|
| 67 |
+
def to_dict(self) -> dict:
|
| 68 |
+
return {
|
| 69 |
+
"t": self.t, "seed": self.seed, "prompt": self.prompt,
|
| 70 |
+
"S_VQA": round(self.mean_vqa, 4), "S_DINO_patch": round(self.dino_patch, 4),
|
| 71 |
+
"S_DINO_cls": round(self.dino_cls, 4), "joint": round(self.joint, 4),
|
| 72 |
+
"failed": [sp.predicate.id for sp in self.failed],
|
| 73 |
+
"rewrite_notes": self.rewrite_notes,
|
| 74 |
+
"patch": asdict(self.patch) if self.patch else None,
|
| 75 |
+
"rewrite_error": self.rewrite_error,
|
| 76 |
+
"predicates": [sp.to_dict() for sp in self.scored],
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass
|
| 81 |
+
class InversionRun:
|
| 82 |
+
config: EngineConfig
|
| 83 |
+
status: str = ""
|
| 84 |
+
raw_graph: DSGSceneSchema | None = None
|
| 85 |
+
graph: DSGSceneSchema | None = None
|
| 86 |
+
predicates: list[Predicate] = field(default_factory=list)
|
| 87 |
+
grounding: list[ScoredPredicate] = field(default_factory=list)
|
| 88 |
+
dropped: list[ScoredPredicate] = field(default_factory=list)
|
| 89 |
+
relocalized: list[dict] = field(default_factory=list)
|
| 90 |
+
canonical_prompt: str = ""
|
| 91 |
+
proxy_wh: tuple[int, int] | None = None
|
| 92 |
+
iterations: list[IterationRecord] = field(default_factory=list)
|
| 93 |
+
best_index: int | None = None
|
| 94 |
+
stop_reason: str | None = None
|
| 95 |
+
|
| 96 |
+
@property
|
| 97 |
+
def best(self) -> IterationRecord | None:
|
| 98 |
+
return None if self.best_index is None else self.iterations[self.best_index]
|
| 99 |
+
|
| 100 |
+
@property
|
| 101 |
+
def best_prompt(self) -> str:
|
| 102 |
+
return self.best.prompt if self.best else self.canonical_prompt
|
| 103 |
+
|
| 104 |
+
def to_dict(self) -> dict:
|
| 105 |
+
best = self.best
|
| 106 |
+
return {
|
| 107 |
+
"config": asdict(self.config),
|
| 108 |
+
"stop_reason": self.stop_reason,
|
| 109 |
+
"best_prompt": self.best_prompt,
|
| 110 |
+
"best_iteration": best.t if best else None,
|
| 111 |
+
"best_scores": ({"S_VQA": round(best.mean_vqa, 4), "S_DINO_patch": round(best.dino_patch, 4),
|
| 112 |
+
"joint": round(best.joint, 4)} if best else None),
|
| 113 |
+
"canonical_prompt": self.canonical_prompt,
|
| 114 |
+
"proxy_size": self.proxy_wh,
|
| 115 |
+
"raw_graph": self.raw_graph.model_dump() if self.raw_graph else None,
|
| 116 |
+
"graph": self.graph.model_dump() if self.graph else None,
|
| 117 |
+
"predicates": [p.to_dict() for p in self.predicates],
|
| 118 |
+
"grounding_dropped": [sp.to_dict() for sp in self.dropped],
|
| 119 |
+
"grounding_relocalized": self.relocalized,
|
| 120 |
+
"iterations": [it.to_dict() for it in self.iterations],
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def _relocalize(run: InversionRun, og: Image.Image, backends: Backends, cfg: EngineConfig) -> None:
|
| 125 |
+
"""A rejected grid cell would leave a wrong position in the prompt, so instead of only
|
| 126 |
+
dropping it, ask the scorer about all 9 cells and move the node to the best-supported one."""
|
| 127 |
+
alive = {n.id for n in run.graph.nodes}
|
| 128 |
+
pending = [sp for sp in run.dropped if sp.predicate.kind == "position" and sp.predicate.ref["node"] in alive]
|
| 129 |
+
nodes = [run.graph.node(sp.predicate.ref["node"]) for sp in pending]
|
| 130 |
+
statements = [position_statement(n.entity, cell) for n in nodes for cell in GRID_ORDER]
|
| 131 |
+
scores = backends.vqa_scores(og, statements, cfg.question_template)
|
| 132 |
+
k = len(GRID_ORDER)
|
| 133 |
+
for i, (sp, node) in enumerate(zip(pending, nodes)):
|
| 134 |
+
cell_scores = scores[i * k:(i + 1) * k]
|
| 135 |
+
best = max(range(k), key=cell_scores.__getitem__)
|
| 136 |
+
if cell_scores[best] >= cfg.grounding_threshold and GRID_ORDER[best] != node.grid_cell:
|
| 137 |
+
run.relocalized.append({"node": node.id, "entity": node.entity, "from": node.grid_cell,
|
| 138 |
+
"to": GRID_ORDER[best], "p_yes": round(cell_scores[best], 4)})
|
| 139 |
+
node.grid_cell = GRID_ORDER[best]
|
| 140 |
+
run.dropped.remove(sp)
|
| 141 |
+
if run.relocalized:
|
| 142 |
+
dropped_ids = {sp.predicate.id for sp in run.dropped}
|
| 143 |
+
run.predicates = [p for p in compile_predicates(run.graph) if p.id not in dropped_ids]
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def iter_inversion(og_image: Image.Image, backends: Backends,
|
| 147 |
+
config: EngineConfig | None = None) -> Iterator[InversionRun]:
|
| 148 |
+
cfg = config or EngineConfig()
|
| 149 |
+
if cfg.max_iters < 1:
|
| 150 |
+
raise ValueError("max_iters must be >= 1")
|
| 151 |
+
og = og_image.convert("RGB")
|
| 152 |
+
run = InversionRun(config=cfg)
|
| 153 |
+
|
| 154 |
+
# ---- Module 1: constrained DSG extraction
|
| 155 |
+
run.status = "Module 1 · extracting constrained scene graph"
|
| 156 |
+
yield run
|
| 157 |
+
run.raw_graph = backends.extract_dsg(og)
|
| 158 |
+
predicates = compile_predicates(run.raw_graph)
|
| 159 |
+
|
| 160 |
+
# ---- Anti-hallucination grounding: facts false on the OG itself are unfixable
|
| 161 |
+
if cfg.ground:
|
| 162 |
+
run.status = f"Module 2 · grounding {len(predicates)} predicates on the original image"
|
| 163 |
+
yield run
|
| 164 |
+
og_scores = backends.vqa_scores(og, [p.statement for p in predicates], cfg.question_template)
|
| 165 |
+
run.grounding = apply_dependencies(predicates, og_scores, cfg.parent_gate)
|
| 166 |
+
run.graph, run.predicates, run.dropped = prune_hallucinations(
|
| 167 |
+
run.raw_graph, run.grounding, cfg.grounding_threshold)
|
| 168 |
+
if any(sp.predicate.kind == "position" for sp in run.dropped):
|
| 169 |
+
run.status = "Module 2 · re-localizing entities whose grid cell was rejected on the original"
|
| 170 |
+
yield run
|
| 171 |
+
_relocalize(run, og, backends, cfg)
|
| 172 |
+
else:
|
| 173 |
+
run.graph, run.predicates = run.raw_graph, predicates
|
| 174 |
+
|
| 175 |
+
# ---- Module 2: canonical linearization
|
| 176 |
+
prompt = run.canonical_prompt = linearize(run.graph)
|
| 177 |
+
statements = [p.statement for p in run.predicates]
|
| 178 |
+
og_emb = backends.embed(og)
|
| 179 |
+
run.proxy_wh = width, height = proxy_size(og.size, cfg.proxy_long_side)
|
| 180 |
+
|
| 181 |
+
for t in range(cfg.max_iters):
|
| 182 |
+
seed = cfg.base_seed + t
|
| 183 |
+
# ---- Module 3: proxy render
|
| 184 |
+
run.status = f"t={t + 1}/{cfg.max_iters} · Module 3 · rendering proxy (seed {seed})"
|
| 185 |
+
yield run
|
| 186 |
+
proxy = backends.render(prompt, seed, width, height)
|
| 187 |
+
|
| 188 |
+
# ---- Module 4: dual verification
|
| 189 |
+
run.status = f"t={t + 1}/{cfg.max_iters} · Module 4 · scoring {len(statements)} predicates + DINO layout"
|
| 190 |
+
yield run
|
| 191 |
+
raw = backends.vqa_scores(proxy, statements, cfg.question_template)
|
| 192 |
+
scored = apply_dependencies(run.predicates, raw, cfg.parent_gate)
|
| 193 |
+
mean_vqa = sum(sp.effective for sp in scored) / max(1, len(scored))
|
| 194 |
+
sim = dino_similarity(og_emb, backends.embed(proxy))
|
| 195 |
+
joint = cfg.w_vqa * mean_vqa + cfg.w_dino * sim["patch"]
|
| 196 |
+
# Root-cause failures only: blocked children are fixed by fixing their parent.
|
| 197 |
+
failed = [sp for sp in scored if sp.raw < cfg.fail_threshold and not sp.blocked_by]
|
| 198 |
+
|
| 199 |
+
rec = IterationRecord(t + 1, seed, prompt, proxy, scored, mean_vqa, sim["patch"], sim["cls"], joint, failed)
|
| 200 |
+
run.iterations.append(rec)
|
| 201 |
+
if run.best is None or joint > run.best.joint:
|
| 202 |
+
run.best_index = len(run.iterations) - 1
|
| 203 |
+
|
| 204 |
+
if mean_vqa >= cfg.vqa_gate and sim["patch"] >= cfg.dino_gate:
|
| 205 |
+
run.stop_reason = "converged"
|
| 206 |
+
break
|
| 207 |
+
if t == cfg.max_iters - 1:
|
| 208 |
+
run.stop_reason = "max_iters"
|
| 209 |
+
break
|
| 210 |
+
|
| 211 |
+
# ---- Targeted diff rewrite (only failed predicates)
|
| 212 |
+
notes = [sp.predicate.statement for sp in failed]
|
| 213 |
+
if sim["patch"] < cfg.dino_gate:
|
| 214 |
+
notes.append(f"the overall layout: every shape occupies the same position, size, and proportion of the "
|
| 215 |
+
f"frame as in the original (layout similarity {sim['patch']:.2f} < {cfg.dino_gate:.2f})")
|
| 216 |
+
rec.rewrite_notes = notes
|
| 217 |
+
run.status = f"t={t + 1}/{cfg.max_iters} · targeted rewrite of {len(failed)} failed predicate(s)"
|
| 218 |
+
yield run
|
| 219 |
+
try:
|
| 220 |
+
rec.patch = apply_patch(prompt, backends.rewrite(og, proxy, prompt, notes))
|
| 221 |
+
prompt = rec.patch.prompt
|
| 222 |
+
except Exception as err: # keep the loop alive; next iteration re-renders with a new seed
|
| 223 |
+
rec.rewrite_error = f"{type(err).__name__}: {err}"
|
| 224 |
+
|
| 225 |
+
best = run.best
|
| 226 |
+
run.status = (f"Done · {run.stop_reason} · best t={best.t}: S_VQA={best.mean_vqa:.3f}, "
|
| 227 |
+
f"S_DINO={best.dino_patch:.3f}, joint={best.joint:.3f}")
|
| 228 |
+
yield run
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def invert_image_to_verified_prompt(og_image: Image.Image, backends: Backends,
|
| 232 |
+
config: EngineConfig | None = None) -> InversionRun:
|
| 233 |
+
run = None
|
| 234 |
+
for run in iter_inversion(og_image, backends, config):
|
| 235 |
+
pass
|
| 236 |
+
return run
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def save_run(run: InversionRun, out_dir: str | Path, og_image: Image.Image | None = None) -> Path:
|
| 240 |
+
out = Path(out_dir)
|
| 241 |
+
out.mkdir(parents=True, exist_ok=True)
|
| 242 |
+
(out / "report.json").write_text(json.dumps(run.to_dict(), indent=2), encoding="utf-8")
|
| 243 |
+
(out / "best_prompt.txt").write_text(run.best_prompt + "\n", encoding="utf-8")
|
| 244 |
+
if og_image is not None:
|
| 245 |
+
og_image.convert("RGB").save(out / "original.png")
|
| 246 |
+
for it in run.iterations:
|
| 247 |
+
it.proxy_image.save(out / f"proxy_t{it.t}_seed{it.seed}.png")
|
| 248 |
+
return out
|
inversion/proxy.py
ADDED
|
@@ -0,0 +1,61 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module 3: fast proxy text-to-image renderer (the internal forward model)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import io
|
| 6 |
+
import urllib.request
|
| 7 |
+
|
| 8 |
+
from PIL import Image
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def proxy_size(og_size: tuple[int, int], long_side: int = 1024, multiple: int = 16) -> tuple[int, int]:
|
| 12 |
+
"""Match the OG aspect ratio at ~`long_side`, snapped to the model's latent multiple."""
|
| 13 |
+
w, h = og_size
|
| 14 |
+
scale = long_side / max(w, h)
|
| 15 |
+
|
| 16 |
+
def snap(x: float) -> int:
|
| 17 |
+
return max(multiple, int(round(x * scale / multiple)) * multiple)
|
| 18 |
+
|
| 19 |
+
return snap(w), snap(h)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FluxSchnellRenderer:
|
| 23 |
+
"""black-forest-labs/FLUX.1-schnell via diffusers (4-step distilled, guidance-free)."""
|
| 24 |
+
|
| 25 |
+
def __init__(self, model_id: str = "black-forest-labs/FLUX.1-schnell", device: str | None = None,
|
| 26 |
+
cpu_offload: bool = False, steps: int = 4, max_sequence_length: int = 512):
|
| 27 |
+
import torch
|
| 28 |
+
from diffusers import FluxPipeline
|
| 29 |
+
|
| 30 |
+
self.torch = torch
|
| 31 |
+
self.pipe = FluxPipeline.from_pretrained(model_id, torch_dtype=torch.bfloat16)
|
| 32 |
+
if cpu_offload:
|
| 33 |
+
self.pipe.enable_model_cpu_offload()
|
| 34 |
+
else:
|
| 35 |
+
self.pipe.to(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
| 36 |
+
self.steps, self.max_sequence_length = steps, max_sequence_length
|
| 37 |
+
|
| 38 |
+
def __call__(self, prompt: str, seed: int, width: int, height: int) -> Image.Image:
|
| 39 |
+
generator = self.torch.Generator(device="cpu").manual_seed(int(seed))
|
| 40 |
+
return self.pipe(
|
| 41 |
+
prompt, width=width, height=height, num_inference_steps=self.steps, guidance_scale=0.0,
|
| 42 |
+
max_sequence_length=self.max_sequence_length, generator=generator,
|
| 43 |
+
).images[0]
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class FalRenderer:
|
| 47 |
+
"""fal-ai/flux/schnell over the fal.ai API (reads FAL_KEY from the environment)."""
|
| 48 |
+
|
| 49 |
+
def __init__(self, endpoint: str = "fal-ai/flux/schnell", steps: int = 4):
|
| 50 |
+
import fal_client
|
| 51 |
+
|
| 52 |
+
self.fal, self.endpoint, self.steps = fal_client, endpoint, steps
|
| 53 |
+
|
| 54 |
+
def __call__(self, prompt: str, seed: int, width: int, height: int) -> Image.Image:
|
| 55 |
+
result = self.fal.subscribe(self.endpoint, arguments={
|
| 56 |
+
"prompt": prompt, "seed": int(seed), "num_inference_steps": self.steps,
|
| 57 |
+
"image_size": {"width": width, "height": height}, "num_images": 1,
|
| 58 |
+
})
|
| 59 |
+
url = result["images"][0]["url"]
|
| 60 |
+
with urllib.request.urlopen(url, timeout=60) as resp:
|
| 61 |
+
return Image.open(io.BytesIO(resp.read())).convert("RGB")
|
inversion/schema.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Module 1 schema: typed Davidsonian-style scene graph extracted from the OG image.
|
| 2 |
+
|
| 3 |
+
The VLM must emit JSON that validates against `DSGSceneSchema`. Validators are
|
| 4 |
+
lenient on surface form (grid-cell spelling, list lengths) but strict on
|
| 5 |
+
structure, so the downstream compiler always receives a well-formed graph.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
from typing import Literal
|
| 12 |
+
|
| 13 |
+
from pydantic import BaseModel, Field, field_validator, model_validator
|
| 14 |
+
|
| 15 |
+
GridCell = Literal[
|
| 16 |
+
"Top-Left", "Top-Center", "Top-Right",
|
| 17 |
+
"Mid-Left", "Center", "Mid-Right",
|
| 18 |
+
"Bot-Left", "Bot-Center", "Bot-Right",
|
| 19 |
+
]
|
| 20 |
+
GRID_ORDER: tuple[str, ...] = GridCell.__args__ # reading order: left-to-right, top-to-bottom
|
| 21 |
+
|
| 22 |
+
GRID_PHRASE = {
|
| 23 |
+
"Top-Left": "top-left", "Top-Center": "top-center", "Top-Right": "top-right",
|
| 24 |
+
"Mid-Left": "middle-left", "Center": "center", "Mid-Right": "middle-right",
|
| 25 |
+
"Bot-Left": "bottom-left", "Bot-Center": "bottom-center", "Bot-Right": "bottom-right",
|
| 26 |
+
}
|
| 27 |
+
|
| 28 |
+
MAX_NODES = 12
|
| 29 |
+
MAX_ATTRIBUTES = 4
|
| 30 |
+
MAX_RELATIONS = 3
|
| 31 |
+
MAX_PALETTE = 8
|
| 32 |
+
MAX_EXTRA_CHECKS = 6
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def normalize_grid_cell(value: str) -> str:
|
| 36 |
+
"""Map spellings like 'top left', 'middle-right', 'bottom center' onto GridCell."""
|
| 37 |
+
s = re.sub(r"[\s_]+", "-", str(value).strip().lower())
|
| 38 |
+
s = s.replace("middle", "mid").replace("bottom", "bot").replace("centre", "center")
|
| 39 |
+
if s in {"center", "mid-center", "center-center", "mid-mid", "mid"}:
|
| 40 |
+
return "Center"
|
| 41 |
+
for cell in GRID_ORDER:
|
| 42 |
+
if s == cell.lower():
|
| 43 |
+
return cell
|
| 44 |
+
raise ValueError(f"unknown grid cell {value!r}; use one of {', '.join(GRID_ORDER)}")
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def _slug(value: str) -> str:
|
| 48 |
+
return re.sub(r"[^a-z0-9]+", "_", value.lower()).strip("_") or "node"
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
_KEY_PREFIX = re.compile(r"^[A-Za-z][A-Za-z /_-]{1,24}:\s+") # 'color: dark red' -> 'dark red'
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def _clean_list(items: list[str], limit: int, strip_keys: bool = False) -> list[str]:
|
| 55 |
+
if isinstance(items, str):
|
| 56 |
+
items = [items]
|
| 57 |
+
seen, out = set(), []
|
| 58 |
+
for item in items:
|
| 59 |
+
text = " ".join(str(item).split()).strip(" .;,")
|
| 60 |
+
if strip_keys:
|
| 61 |
+
text = _KEY_PREFIX.sub("", text)
|
| 62 |
+
if text and text.lower() not in seen:
|
| 63 |
+
seen.add(text.lower())
|
| 64 |
+
out.append(text)
|
| 65 |
+
return out[:limit]
|
| 66 |
+
|
| 67 |
+
|
| 68 |
+
class Relation(BaseModel):
|
| 69 |
+
predicate: str = Field(
|
| 70 |
+
description="Spatial or physical relation phrased so '<subject> <predicate> <target>' reads as a sentence, "
|
| 71 |
+
"e.g. 'is left of', 'overlaps', 'is above', 'is partially behind', 'touches'."
|
| 72 |
+
)
|
| 73 |
+
target_id: str = Field(description="`id` of another node in this graph.")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class SpatialNode(BaseModel):
|
| 77 |
+
id: str = Field(description="Unique snake_case identifier, e.g. 'red_circle'.")
|
| 78 |
+
grid_cell: GridCell = Field(
|
| 79 |
+
description="Cell of the 3x3 grid holding the node's visual center. One of: " + ", ".join(GRID_ORDER)
|
| 80 |
+
)
|
| 81 |
+
entity: str = Field(
|
| 82 |
+
description="Objective visual form/object as an indefinite noun phrase (e.g. 'a large circle', "
|
| 83 |
+
"'a sign reading \"PALACE\"'), without unverified era or style buzzwords."
|
| 84 |
+
)
|
| 85 |
+
attributes: list[str] = Field(
|
| 86 |
+
default_factory=list,
|
| 87 |
+
description=f"Up to {MAX_ATTRIBUTES} exact visual properties as bare phrases (e.g. 'crimson red', "
|
| 88 |
+
"'sharp edges', 'rotated 45 degrees', 'about one third of the frame width'), never 'key: value'. "
|
| 89 |
+
"Do not repeat what the entity noun already says.",
|
| 90 |
+
)
|
| 91 |
+
relations: list[Relation] = Field(
|
| 92 |
+
default_factory=list,
|
| 93 |
+
description=f"Up to {MAX_RELATIONS} spatial/physical relations to other nodes.",
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
@field_validator("grid_cell", mode="before")
|
| 97 |
+
@classmethod
|
| 98 |
+
def _grid(cls, v):
|
| 99 |
+
return normalize_grid_cell(v)
|
| 100 |
+
|
| 101 |
+
@field_validator("id", mode="before")
|
| 102 |
+
@classmethod
|
| 103 |
+
def _id(cls, v):
|
| 104 |
+
return _slug(str(v))
|
| 105 |
+
|
| 106 |
+
@field_validator("entity", mode="before")
|
| 107 |
+
@classmethod
|
| 108 |
+
def _entity(cls, v):
|
| 109 |
+
text = " ".join(str(v).split()).strip(" .")
|
| 110 |
+
if not text:
|
| 111 |
+
raise ValueError("entity must be non-empty")
|
| 112 |
+
return text
|
| 113 |
+
|
| 114 |
+
@field_validator("attributes", mode="before")
|
| 115 |
+
@classmethod
|
| 116 |
+
def _attrs(cls, v):
|
| 117 |
+
return _clean_list(v or [], MAX_ATTRIBUTES, strip_keys=True)
|
| 118 |
+
|
| 119 |
+
@field_validator("relations", mode="after")
|
| 120 |
+
@classmethod
|
| 121 |
+
def _rels(cls, v):
|
| 122 |
+
return v[:MAX_RELATIONS]
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
MAX_MEDIUM_FACETS = 4
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
class DSGSceneSchema(BaseModel):
|
| 129 |
+
medium_and_optics: list[str] = Field(
|
| 130 |
+
description=f"1-{MAX_MEDIUM_FACETS} short, separately verifiable facets of the physical medium, surface "
|
| 131 |
+
"and optics, e.g. ['flat gouache on matte paper', 'zero drop shadows', 'deep depth of field']. "
|
| 132 |
+
"Observable facts only; no guesses about how the image was made."
|
| 133 |
+
)
|
| 134 |
+
background: str = Field(description="The background/ground as a noun phrase, e.g. 'a plain off-white background'.")
|
| 135 |
+
color_palette: list[str] = Field(description=f"3-{MAX_PALETTE} dominant colors as precise color names.")
|
| 136 |
+
nodes: list[SpatialNode] = Field(
|
| 137 |
+
description=f"1-{MAX_NODES} distinct visible entities, each anchored to one 3x3 grid cell."
|
| 138 |
+
)
|
| 139 |
+
extra_checks: list[str] = Field(
|
| 140 |
+
default_factory=list,
|
| 141 |
+
description=f"0-{MAX_EXTRA_CHECKS} additional atomic, binary-verifiable visual facts not captured by nodes "
|
| 142 |
+
"(e.g. counts: 'exactly three circles'; visible text). Noun-phrase or short-clause form.",
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
@field_validator("medium_and_optics", mode="before")
|
| 146 |
+
@classmethod
|
| 147 |
+
def _medium(cls, v):
|
| 148 |
+
# A plain string is split on semicolons only: commas often join adjectives ("a flat, matte image").
|
| 149 |
+
if isinstance(v, str):
|
| 150 |
+
v = v.split(";")
|
| 151 |
+
out = _clean_list(v or [], MAX_MEDIUM_FACETS)
|
| 152 |
+
if not out:
|
| 153 |
+
raise ValueError("medium_and_optics must contain at least one facet")
|
| 154 |
+
return out
|
| 155 |
+
|
| 156 |
+
@field_validator("background", mode="before")
|
| 157 |
+
@classmethod
|
| 158 |
+
def _text(cls, v):
|
| 159 |
+
return " ".join(str(v).split()).strip(" .")
|
| 160 |
+
|
| 161 |
+
@field_validator("color_palette", mode="before")
|
| 162 |
+
@classmethod
|
| 163 |
+
def _palette(cls, v):
|
| 164 |
+
return _clean_list(v or [], MAX_PALETTE)
|
| 165 |
+
|
| 166 |
+
@field_validator("extra_checks", mode="before")
|
| 167 |
+
@classmethod
|
| 168 |
+
def _extra(cls, v):
|
| 169 |
+
return _clean_list(v or [], MAX_EXTRA_CHECKS)
|
| 170 |
+
|
| 171 |
+
@model_validator(mode="after")
|
| 172 |
+
def _graph_integrity(self):
|
| 173 |
+
if not self.nodes:
|
| 174 |
+
raise ValueError("nodes must contain at least one entity")
|
| 175 |
+
self.nodes = self.nodes[:MAX_NODES]
|
| 176 |
+
# Make ids unique, then drop relations whose target is missing or self-referential.
|
| 177 |
+
seen: dict[str, int] = {}
|
| 178 |
+
for node in self.nodes:
|
| 179 |
+
base = node.id
|
| 180 |
+
if base in seen:
|
| 181 |
+
seen[base] += 1
|
| 182 |
+
node.id = f"{base}_{seen[base]}"
|
| 183 |
+
else:
|
| 184 |
+
seen[base] = 1
|
| 185 |
+
ids = {n.id for n in self.nodes}
|
| 186 |
+
for node in self.nodes:
|
| 187 |
+
node.relations = [r for r in node.relations if r.target_id in ids and r.target_id != node.id]
|
| 188 |
+
return self
|
| 189 |
+
|
| 190 |
+
def node(self, node_id: str) -> SpatialNode:
|
| 191 |
+
return next(n for n in self.nodes if n.id == node_id)
|
| 192 |
+
|
| 193 |
+
|
| 194 |
+
class TextEdit(BaseModel):
|
| 195 |
+
original: str = Field(description="An exact, verbatim substring of the current prompt to replace.")
|
| 196 |
+
revised: str = Field(description="Replacement text for that span.")
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
class RewritePatch(BaseModel):
|
| 200 |
+
"""Targeted diff: only spans tied to failed predicates are touched."""
|
| 201 |
+
|
| 202 |
+
edits: list[TextEdit] = Field(default_factory=list, description="At most 6 span replacements.")
|
| 203 |
+
additions: list[str] = Field(
|
| 204 |
+
default_factory=list,
|
| 205 |
+
description="At most 3 short new sentences for failed facts that no existing span covers.",
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
@field_validator("edits", mode="after")
|
| 209 |
+
@classmethod
|
| 210 |
+
def _cap_edits(cls, v):
|
| 211 |
+
return v[:6]
|
| 212 |
+
|
| 213 |
+
@field_validator("additions", mode="before")
|
| 214 |
+
@classmethod
|
| 215 |
+
def _cap_additions(cls, v):
|
| 216 |
+
return _clean_list(v or [], 3)
|
inversion/vlm.py
ADDED
|
@@ -0,0 +1,254 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""VLM backends: Module 1 (DSG extraction), Module 4A (VQAScore), and the targeted rewriter.
|
| 2 |
+
|
| 3 |
+
`LocalQwenVLM` keeps a single set of Qwen3-VL weights in memory and serves all
|
| 4 |
+
three roles. `OpenAICompatVLM` targets any OpenAI-compatible endpoint
|
| 5 |
+
(OpenAI, OpenRouter, Together, Fireworks) for the no-local-GPU pathway.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import base64
|
| 11 |
+
import io
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
import re
|
| 15 |
+
from concurrent.futures import ThreadPoolExecutor
|
| 16 |
+
from typing import TypeVar
|
| 17 |
+
|
| 18 |
+
from PIL import Image
|
| 19 |
+
from pydantic import BaseModel, ValidationError
|
| 20 |
+
|
| 21 |
+
from .schema import GRID_ORDER, DSGSceneSchema, RewritePatch
|
| 22 |
+
|
| 23 |
+
T = TypeVar("T", bound=BaseModel)
|
| 24 |
+
|
| 25 |
+
VQA_TEMPLATE = 'Does this image show "{}"? Please answer yes or no.'
|
| 26 |
+
|
| 27 |
+
# VQAScore modes:
|
| 28 |
+
# "normalized" (default): P(yes-variants) / (P(yes-variants) + P(no-variants)). Qwen3-VL puts most of
|
| 29 |
+
# its mass on lowercase "yes", so the exact-"Yes" probability badly under-reads true facts
|
| 30 |
+
# (e.g. 0.009 for a fact answered "yes" with p=0.99) and is unstable across batching.
|
| 31 |
+
# "yes": the original VQAScore definition, P("Yes") over the full vocabulary.
|
| 32 |
+
VQA_MODES = ("normalized", "yes")
|
| 33 |
+
_YES, _NO = ("Yes", "yes", "YES"), ("No", "no", "NO")
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def _combine(p_yes: float, p_no: float, p_exact_yes: float, mode: str) -> float:
|
| 37 |
+
if mode == "yes":
|
| 38 |
+
return p_exact_yes
|
| 39 |
+
return p_yes / (p_yes + p_no) if (p_yes + p_no) > 0 else 0.0
|
| 40 |
+
|
| 41 |
+
EXTRACTION_INSTRUCTION = f"""You are building a verifiable scene graph of this image so that a text-to-image model can reproduce it exactly without seeing it.
|
| 42 |
+
|
| 43 |
+
Procedure:
|
| 44 |
+
1. Partition the image into a 3x3 grid: {", ".join(GRID_ORDER)}.
|
| 45 |
+
2. List every distinct visible entity (shapes, objects, figures, marks, visible text) as a node anchored to the grid cell that contains its visual center.
|
| 46 |
+
3. For each node give up to 4 exact visual attributes (precise color name, geometry, size relative to the frame, orientation/facing direction, edge sharpness, texture) and up to 3 spatial or physical relations to other nodes, referenced by node id.
|
| 47 |
+
4. Describe the medium, surface, and optics as observable facts; describe the background; list the dominant color palette.
|
| 48 |
+
5. Optionally add a few extra atomic checks (counts, visible text) not already covered by nodes.
|
| 49 |
+
|
| 50 |
+
Rules:
|
| 51 |
+
- Describe only what is visible. No artist names, art movements, eras, or style buzzwords unless they are written in the image. No interpretation of meaning.
|
| 52 |
+
- Every attribute and relation must be independently verifiable by looking at the image.
|
| 53 |
+
- Entities are indefinite noun phrases ("a large circle"). Visible text is quoted verbatim inside an entity (a sign reading "PALACE").
|
| 54 |
+
- Attributes are bare phrases ("crimson red", "rotated 45 degrees"), never "key: value", and never restate the entity noun.
|
| 55 |
+
- A node's grid cell is where its center falls when the width and the height are each split into thirds.
|
| 56 |
+
- Left/right always mean the viewer's left/right."""
|
| 57 |
+
|
| 58 |
+
REWRITE_INSTRUCTION = """Image 1 is the ORIGINAL target image. Image 2 is a PROXY rendered by a text-to-image model from the prompt below.
|
| 59 |
+
|
| 60 |
+
PROMPT:
|
| 61 |
+
<<<
|
| 62 |
+
{prompt}
|
| 63 |
+
>>>
|
| 64 |
+
|
| 65 |
+
These visual facts are TRUE in the original image but FAILED verification in the proxy:
|
| 66 |
+
{failed}
|
| 67 |
+
|
| 68 |
+
Produce a minimal targeted diff to the prompt so that a text-to-image model will render the failed facts correctly.
|
| 69 |
+
Rules:
|
| 70 |
+
- Only touch text related to the failed facts; leave everything else exactly as it is.
|
| 71 |
+
- Each edit's "original" must be a short span (one clause or sentence) copied verbatim, character for character, from the prompt; "revised" replaces it. Make failed facts more explicit, concrete, and prominent (exact color names, position in the frame, size, count, orientation).
|
| 72 |
+
- Use "additions" (at most 3 short sentences) only for failed facts that no existing span covers.
|
| 73 |
+
- Describe only what is visible in image 1. No artist names, art movements, eras, or style buzzwords."""
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
def fit(image: Image.Image, max_side: int) -> Image.Image:
|
| 77 |
+
"""Downscale (never upscale) so the longest side is at most `max_side`."""
|
| 78 |
+
image = image.convert("RGB")
|
| 79 |
+
w, h = image.size
|
| 80 |
+
scale = max_side / max(w, h)
|
| 81 |
+
if scale >= 1:
|
| 82 |
+
return image
|
| 83 |
+
return image.resize((max(1, round(w * scale)), max(1, round(h * scale))), Image.Resampling.LANCZOS)
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
def extract_json(raw: str) -> str:
|
| 87 |
+
text = re.sub(r"<think>.*?</think>", "", raw, flags=re.DOTALL)
|
| 88 |
+
text = re.sub(r"^```(?:json)?\s*|\s*```$", "", text.strip())
|
| 89 |
+
start, end = text.find("{"), text.rfind("}")
|
| 90 |
+
if start == -1 or end <= start:
|
| 91 |
+
raise ValueError("no JSON object found in model output")
|
| 92 |
+
return text[start:end + 1]
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class VLMBase:
|
| 96 |
+
"""Shared structured-output logic; subclasses implement `chat` and `vqa_scores`."""
|
| 97 |
+
|
| 98 |
+
extract_tokens = 3072
|
| 99 |
+
rewrite_tokens = 1024
|
| 100 |
+
|
| 101 |
+
def chat(self, images: list[Image.Image], text: str, max_new_tokens: int = 512,
|
| 102 |
+
json_schema: dict | None = None) -> str:
|
| 103 |
+
raise NotImplementedError
|
| 104 |
+
|
| 105 |
+
def vqa_scores(self, image: Image.Image, statements: list[str], template: str = VQA_TEMPLATE) -> list[float]:
|
| 106 |
+
raise NotImplementedError
|
| 107 |
+
|
| 108 |
+
def structured(self, images: list[Image.Image], instruction: str, schema_cls: type[T],
|
| 109 |
+
max_new_tokens: int, retries: int = 2) -> T:
|
| 110 |
+
"""Schema-constrained generation: schema in prompt (+ API json_schema), Pydantic
|
| 111 |
+
validation, and repair retries that feed the validation error back to the model."""
|
| 112 |
+
schema = schema_cls.model_json_schema()
|
| 113 |
+
base = (f"{instruction}\n\nReturn ONLY one JSON object that validates against this JSON Schema "
|
| 114 |
+
f"(no markdown, no commentary):\n{json.dumps(schema)}")
|
| 115 |
+
prompt, last_err = base, None
|
| 116 |
+
for _ in range(retries + 1):
|
| 117 |
+
raw = self.chat(images, prompt, max_new_tokens=max_new_tokens, json_schema=schema)
|
| 118 |
+
try:
|
| 119 |
+
return schema_cls.model_validate_json(extract_json(raw))
|
| 120 |
+
except (ValidationError, ValueError) as err:
|
| 121 |
+
last_err = err
|
| 122 |
+
prompt = (f"{base}\n\nYour previous answer was invalid:\n{str(err)[:1500]}\n\n"
|
| 123 |
+
f"Previous answer (truncated):\n{raw[:3000]}\n\nReturn the corrected JSON object only.")
|
| 124 |
+
raise RuntimeError(f"{schema_cls.__name__} extraction failed after {retries + 1} attempts: {last_err}")
|
| 125 |
+
|
| 126 |
+
def extract_dsg(self, image: Image.Image) -> DSGSceneSchema:
|
| 127 |
+
return self.structured([image], EXTRACTION_INSTRUCTION, DSGSceneSchema, self.extract_tokens)
|
| 128 |
+
|
| 129 |
+
def rewrite(self, og_image: Image.Image, proxy_image: Image.Image, prompt: str,
|
| 130 |
+
failed: list[str]) -> RewritePatch:
|
| 131 |
+
bullet = "\n".join(f"- {f}" for f in failed)
|
| 132 |
+
return self.structured([og_image, proxy_image], REWRITE_INSTRUCTION.format(prompt=prompt, failed=bullet),
|
| 133 |
+
RewritePatch, self.rewrite_tokens)
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
class LocalQwenVLM(VLMBase):
|
| 137 |
+
def __init__(self, model_id: str = "Qwen/Qwen3-VL-8B-Instruct", device: str | None = None,
|
| 138 |
+
max_side: int = 1024, vqa_max_side: int = 768, vqa_batch_size: int = 8,
|
| 139 |
+
vqa_mode: str = "normalized"):
|
| 140 |
+
import torch
|
| 141 |
+
from transformers import AutoProcessor, Qwen3VLForConditionalGeneration
|
| 142 |
+
|
| 143 |
+
if vqa_mode not in VQA_MODES:
|
| 144 |
+
raise ValueError(f"vqa_mode must be one of {VQA_MODES}")
|
| 145 |
+
self.torch = torch
|
| 146 |
+
self.device = device or ("cuda" if torch.cuda.is_available() else "cpu")
|
| 147 |
+
self.model = Qwen3VLForConditionalGeneration.from_pretrained(model_id, dtype="auto").to(self.device).eval()
|
| 148 |
+
self.processor = AutoProcessor.from_pretrained(model_id)
|
| 149 |
+
self.processor.tokenizer.padding_side = "left" # last position = next-token logits in a batch
|
| 150 |
+
self.max_side, self.vqa_max_side, self.vqa_batch_size = max_side, vqa_max_side, vqa_batch_size
|
| 151 |
+
self.vqa_mode = vqa_mode
|
| 152 |
+
tok = self.processor.tokenizer
|
| 153 |
+
self.yes_id = tok.convert_tokens_to_ids("Yes")
|
| 154 |
+
self.yes_ids, self.no_ids = self._single_token_ids(tok, _YES), self._single_token_ids(tok, _NO)
|
| 155 |
+
|
| 156 |
+
@staticmethod
|
| 157 |
+
def _single_token_ids(tok, words) -> list[int]:
|
| 158 |
+
ids = set()
|
| 159 |
+
for w in words:
|
| 160 |
+
for variant in (w, " " + w):
|
| 161 |
+
enc = tok.encode(variant, add_special_tokens=False)
|
| 162 |
+
if len(enc) == 1:
|
| 163 |
+
ids.add(enc[0])
|
| 164 |
+
return sorted(ids)
|
| 165 |
+
|
| 166 |
+
def chat(self, images, text, max_new_tokens=512, json_schema=None):
|
| 167 |
+
content = [{"type": "image", "image": fit(img, self.max_side)} for img in images]
|
| 168 |
+
content.append({"type": "text", "text": text})
|
| 169 |
+
inputs = self.processor.apply_chat_template(
|
| 170 |
+
[{"role": "user", "content": content}], tokenize=True, add_generation_prompt=True,
|
| 171 |
+
return_dict=True, return_tensors="pt",
|
| 172 |
+
).to(self.model.device)
|
| 173 |
+
with self.torch.inference_mode():
|
| 174 |
+
out = self.model.generate(**inputs, max_new_tokens=int(max_new_tokens), do_sample=False)
|
| 175 |
+
trimmed = out[:, inputs["input_ids"].shape[1]:]
|
| 176 |
+
return self.processor.batch_decode(trimmed, skip_special_tokens=True)[0]
|
| 177 |
+
|
| 178 |
+
def vqa_scores(self, image, statements, template=VQA_TEMPLATE):
|
| 179 |
+
"""VQAScore from the next-token distribution (see VQA_MODES)."""
|
| 180 |
+
img = fit(image, self.vqa_max_side)
|
| 181 |
+
scores: list[float] = []
|
| 182 |
+
for i in range(0, len(statements), self.vqa_batch_size):
|
| 183 |
+
batch = statements[i:i + self.vqa_batch_size]
|
| 184 |
+
texts = [
|
| 185 |
+
self.processor.apply_chat_template(
|
| 186 |
+
[{"role": "user", "content": [{"type": "image"},
|
| 187 |
+
{"type": "text", "text": template.replace("{}", s)}]}],
|
| 188 |
+
tokenize=False, add_generation_prompt=True,
|
| 189 |
+
)
|
| 190 |
+
for s in batch
|
| 191 |
+
]
|
| 192 |
+
inputs = self.processor(text=texts, images=[img] * len(batch), padding=True,
|
| 193 |
+
return_tensors="pt").to(self.model.device)
|
| 194 |
+
with self.torch.inference_mode():
|
| 195 |
+
logits = self.model(**inputs).logits[:, -1, :].float()
|
| 196 |
+
probs = self.torch.softmax(logits, dim=-1)
|
| 197 |
+
p_yes = probs[:, self.yes_ids].sum(-1).tolist()
|
| 198 |
+
p_no = probs[:, self.no_ids].sum(-1).tolist()
|
| 199 |
+
p_exact = probs[:, self.yes_id].tolist()
|
| 200 |
+
scores.extend(_combine(y, n, e, self.vqa_mode) for y, n, e in zip(p_yes, p_no, p_exact))
|
| 201 |
+
return scores
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
class OpenAICompatVLM(VLMBase):
|
| 205 |
+
def __init__(self, model: str, base_url: str | None = None, api_key: str | None = None,
|
| 206 |
+
max_side: int = 1024, workers: int = 8, vqa_mode: str = "normalized"):
|
| 207 |
+
from openai import OpenAI
|
| 208 |
+
|
| 209 |
+
if vqa_mode not in VQA_MODES:
|
| 210 |
+
raise ValueError(f"vqa_mode must be one of {VQA_MODES}")
|
| 211 |
+
self.client = OpenAI(base_url=base_url, api_key=api_key)
|
| 212 |
+
self.model, self.max_side, self.workers, self.vqa_mode = model, max_side, workers, vqa_mode
|
| 213 |
+
|
| 214 |
+
def _image_part(self, image: Image.Image) -> dict:
|
| 215 |
+
buf = io.BytesIO()
|
| 216 |
+
fit(image, self.max_side).save(buf, format="PNG")
|
| 217 |
+
url = "data:image/png;base64," + base64.b64encode(buf.getvalue()).decode()
|
| 218 |
+
return {"type": "image_url", "image_url": {"url": url}}
|
| 219 |
+
|
| 220 |
+
def _create(self, content: list[dict], **kwargs):
|
| 221 |
+
return self.client.chat.completions.create(
|
| 222 |
+
model=self.model, messages=[{"role": "user", "content": content}], temperature=0, **kwargs)
|
| 223 |
+
|
| 224 |
+
def chat(self, images, text, max_new_tokens=512, json_schema=None):
|
| 225 |
+
import openai
|
| 226 |
+
|
| 227 |
+
content = [self._image_part(img) for img in images] + [{"type": "text", "text": text}]
|
| 228 |
+
kwargs = {"max_tokens": int(max_new_tokens)}
|
| 229 |
+
if json_schema is not None:
|
| 230 |
+
fmt = {"type": "json_schema", "json_schema": {"name": "output", "schema": json_schema}}
|
| 231 |
+
try:
|
| 232 |
+
return self._create(content, response_format=fmt, **kwargs).choices[0].message.content or ""
|
| 233 |
+
except openai.BadRequestError:
|
| 234 |
+
pass # provider does not support json_schema; fall back to prompt + validation
|
| 235 |
+
return self._create(content, **kwargs).choices[0].message.content or ""
|
| 236 |
+
|
| 237 |
+
def vqa_scores(self, image, statements, template=VQA_TEMPLATE):
|
| 238 |
+
part = self._image_part(image)
|
| 239 |
+
|
| 240 |
+
def score(statement: str) -> float:
|
| 241 |
+
resp = self._create([part, {"type": "text", "text": template.replace("{}", statement)}],
|
| 242 |
+
max_tokens=1, logprobs=True, top_logprobs=20)
|
| 243 |
+
lp = resp.choices[0].logprobs
|
| 244 |
+
if lp is None or not lp.content:
|
| 245 |
+
raise RuntimeError(f"{self.model} returned no logprobs; VQAScore needs a logprob-capable scorer "
|
| 246 |
+
"(e.g. gpt-4o) or the local backend.")
|
| 247 |
+
top = lp.content[0].top_logprobs
|
| 248 |
+
p_yes = sum(math.exp(t.logprob) for t in top if t.token.strip() in _YES)
|
| 249 |
+
p_no = sum(math.exp(t.logprob) for t in top if t.token.strip() in _NO)
|
| 250 |
+
p_exact = sum(math.exp(t.logprob) for t in top if t.token.strip() == "Yes")
|
| 251 |
+
return _combine(p_yes, p_no, p_exact, self.vqa_mode)
|
| 252 |
+
|
| 253 |
+
with ThreadPoolExecutor(self.workers) as pool:
|
| 254 |
+
return list(pool.map(score, statements))
|
requirements.txt
CHANGED
|
@@ -2,3 +2,13 @@ spaces
|
|
| 2 |
torch==2.13.0
|
| 3 |
torchvision==0.28.0
|
| 4 |
transformers==5.22.1
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 2 |
torch==2.13.0
|
| 3 |
torchvision==0.28.0
|
| 4 |
transformers==5.22.1
|
| 5 |
+
diffusers
|
| 6 |
+
accelerate
|
| 7 |
+
sentencepiece
|
| 8 |
+
protobuf
|
| 9 |
+
pydantic>=2.6
|
| 10 |
+
numpy
|
| 11 |
+
pillow
|
| 12 |
+
# Optional API pathway (VLM_BACKEND=api / SCORER_BACKEND=api / PROXY_BACKEND=fal)
|
| 13 |
+
openai
|
| 14 |
+
fal-client
|
tests/test_engine.py
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Model-free tests: schema validation, DSG compilation/dependencies, grounding, diff patches, and the loop."""
|
| 2 |
+
|
| 3 |
+
import json
|
| 4 |
+
|
| 5 |
+
import pytest
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
|
| 9 |
+
from inversion import (Backends, DSGSceneSchema, EngineConfig, RewritePatch, apply_dependencies, apply_patch,
|
| 10 |
+
compile_predicates, invert_image_to_verified_prompt, linearize, prune_hallucinations)
|
| 11 |
+
from inversion.dino import DinoEmbedding, medoid_index
|
| 12 |
+
from inversion.proxy import proxy_size
|
| 13 |
+
from inversion.vlm import extract_json
|
| 14 |
+
|
| 15 |
+
GRAPH = {
|
| 16 |
+
"medium_and_optics": "flat gouache on matte paper; zero drop shadows; deep depth of field",
|
| 17 |
+
"background": "a plain off-white background",
|
| 18 |
+
"color_palette": ["cobalt blue", "crimson red", "Cobalt Blue", "ochre yellow"],
|
| 19 |
+
"nodes": [
|
| 20 |
+
{"id": "Red Circle", "grid_cell": "middle left", "entity": "a large circle",
|
| 21 |
+
"attributes": ["color: crimson red", "sharp edges"],
|
| 22 |
+
"relations": [{"predicate": "is left of", "target_id": "blue_square"},
|
| 23 |
+
{"predicate": "touches", "target_id": "ghost"}]},
|
| 24 |
+
{"id": "blue_square", "grid_cell": "Mid-Right", "entity": "a small square",
|
| 25 |
+
"attributes": ["cobalt blue", "rotated 45 degrees"], "relations": []},
|
| 26 |
+
{"id": "sign", "grid_cell": "top center", "entity": 'a sign reading "PALACE"', "attributes": []},
|
| 27 |
+
],
|
| 28 |
+
"extra_checks": ["exactly one circle"],
|
| 29 |
+
}
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def graph() -> DSGSceneSchema:
|
| 33 |
+
return DSGSceneSchema.model_validate(GRAPH)
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def test_schema_normalizes_and_cleans():
|
| 37 |
+
g = graph()
|
| 38 |
+
assert [n.id for n in g.nodes] == ["red_circle", "blue_square", "sign"]
|
| 39 |
+
assert [n.grid_cell for n in g.nodes] == ["Mid-Left", "Mid-Right", "Top-Center"]
|
| 40 |
+
assert g.color_palette == ["cobalt blue", "crimson red", "ochre yellow"] # case-insensitive dedupe
|
| 41 |
+
assert g.nodes[0].attributes == ["crimson red", "sharp edges"] # 'key: value' prefix stripped
|
| 42 |
+
assert g.medium_and_optics == ["flat gouache on matte paper", "zero drop shadows", "deep depth of field"]
|
| 43 |
+
commas = DSGSceneSchema.model_validate({**GRAPH, "medium_and_optics": "a flat, matte image"})
|
| 44 |
+
assert commas.medium_and_optics == ["a flat, matte image"] # commas never split a facet
|
| 45 |
+
# Dangling relation target is dropped.
|
| 46 |
+
assert [r.target_id for r in g.nodes[0].relations] == ["blue_square"]
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def test_schema_rejects_bad_grid_and_empty_nodes():
|
| 50 |
+
with pytest.raises(Exception):
|
| 51 |
+
DSGSceneSchema.model_validate({**GRAPH, "nodes": [{**GRAPH["nodes"][0], "grid_cell": "upstairs"}]})
|
| 52 |
+
with pytest.raises(Exception):
|
| 53 |
+
DSGSceneSchema.model_validate({**GRAPH, "nodes": []})
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def test_compile_is_dependency_ordered():
|
| 57 |
+
preds = compile_predicates(graph())
|
| 58 |
+
kinds = [p.kind for p in preds]
|
| 59 |
+
order = ["global", "entity", "attribute", "position", "relation"]
|
| 60 |
+
assert kinds == sorted(kinds, key=order.index)
|
| 61 |
+
rel = next(p for p in preds if p.kind == "relation")
|
| 62 |
+
assert rel.parents == ["entity:red_circle", "entity:blue_square"]
|
| 63 |
+
assert rel.statement == "a large circle that is left of the small square"
|
| 64 |
+
assert len({p.id for p in preds}) == len(preds)
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def test_dependencies_block_children_of_absent_parent():
|
| 68 |
+
preds = compile_predicates(graph())
|
| 69 |
+
raw = [0.1 if p.id == "entity:blue_square" else 0.95 for p in preds]
|
| 70 |
+
scored = {sp.predicate.id: sp for sp in apply_dependencies(preds, raw, parent_gate=0.5)}
|
| 71 |
+
assert scored["rel:red_circle:is_left_of:blue_square"].effective == 0.0
|
| 72 |
+
assert scored["rel:red_circle:is_left_of:blue_square"].blocked_by == ["entity:blue_square"]
|
| 73 |
+
assert scored["pos:blue_square"].effective == 0.0
|
| 74 |
+
assert scored["pos:red_circle"].effective == 0.95
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
def test_grounding_prunes_hallucinated_content_with_stable_ids():
|
| 78 |
+
g = graph()
|
| 79 |
+
preds = compile_predicates(g)
|
| 80 |
+
bad = {"attr:red_circle:crimson_red", "palette:ochre_yellow", "entity:sign", "medium:deep_depth_of_field"}
|
| 81 |
+
raw = [0.1 if p.id in bad else 0.9 for p in preds]
|
| 82 |
+
pruned, surviving, dropped = prune_hallucinations(g, apply_dependencies(preds, raw, 0.5), 0.5)
|
| 83 |
+
ids = {p.id for p in surviving}
|
| 84 |
+
assert "attr:red_circle:sharp_edges" in ids # sibling of the dropped attribute survives
|
| 85 |
+
assert not ids & bad
|
| 86 |
+
assert "pos:sign" not in ids # child of dropped entity
|
| 87 |
+
assert [n.id for n in pruned.nodes] == ["red_circle", "blue_square"]
|
| 88 |
+
assert pruned.nodes[0].attributes == ["sharp edges"]
|
| 89 |
+
assert pruned.color_palette == ["cobalt blue", "crimson red"]
|
| 90 |
+
assert pruned.medium_and_optics == ["flat gouache on matte paper", "zero drop shadows"] # unverified facet leaves
|
| 91 |
+
assert {sp.predicate.id for sp in dropped} >= bad
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def test_grounding_never_empties_graph():
|
| 95 |
+
g = graph()
|
| 96 |
+
preds = compile_predicates(g)
|
| 97 |
+
pruned, surviving, _ = prune_hallucinations(g, apply_dependencies(preds, [0.0] * len(preds), 0.5), 0.5)
|
| 98 |
+
assert len(pruned.nodes) == 3
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def test_linearize_is_deterministic_and_grid_ordered():
|
| 102 |
+
text = linearize(graph())
|
| 103 |
+
assert text == linearize(graph())
|
| 104 |
+
assert text.startswith("Flat gouache on matte paper")
|
| 105 |
+
assert text.index("top-center") < text.index("middle-left") < text.index("middle-right")
|
| 106 |
+
assert "it is left of the small square" in text
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def test_apply_patch_only_touches_verbatim_spans():
|
| 110 |
+
prompt = "A red circle on the left. A blue square on the right."
|
| 111 |
+
patch = RewritePatch(edits=[{"original": "A red circle", "revised": "A large crimson-red circle"},
|
| 112 |
+
{"original": "nonexistent span", "revised": "x"}],
|
| 113 |
+
additions=["A sign reading PALACE sits top center"])
|
| 114 |
+
res = apply_patch(prompt, patch)
|
| 115 |
+
assert res.prompt == ("A large crimson-red circle on the left. A blue square on the right. "
|
| 116 |
+
"A sign reading PALACE sits top center.")
|
| 117 |
+
assert len(res.applied) == 1 and len(res.skipped) == 1
|
| 118 |
+
|
| 119 |
+
|
| 120 |
+
def test_grounding_removes_rejected_medium_facet_from_prompt():
|
| 121 |
+
# Pivot 1: an unverified optics claim (the Figure 1 "soft bokeh" failure) must not reach the T2I prompt.
|
| 122 |
+
g = DSGSceneSchema.model_validate({**GRAPH, "medium_and_optics": "flat gouache; shallow depth of field with soft bokeh"})
|
| 123 |
+
preds = compile_predicates(g)
|
| 124 |
+
raw = [0.1 if "bokeh" in p.statement else 0.9 for p in preds]
|
| 125 |
+
pruned, _, _ = prune_hallucinations(g, apply_dependencies(preds, raw, 0.5), 0.5)
|
| 126 |
+
assert pruned.medium_and_optics == ["flat gouache"]
|
| 127 |
+
assert "bokeh" not in linearize(pruned)
|
| 128 |
+
|
| 129 |
+
|
| 130 |
+
@pytest.mark.parametrize("text, expected", [
|
| 131 |
+
("a vintage orange bus", {"vintage"}),
|
| 132 |
+
("1970s cinematic film look", {"1970s", "cinematic"}),
|
| 133 |
+
("the '70s, in the style of Bauhaus", {"'70s", "in the style of", "bauhaus"}),
|
| 134 |
+
("a Cubist, Surrealist and minimalist composition", {"cubist", "surrealist", "minimalist"}),
|
| 135 |
+
("a red circle rotated 45 degrees, sharp edges, deep depth of field", set()),
|
| 136 |
+
("modernity and cubes", set()),
|
| 137 |
+
])
|
| 138 |
+
def test_buzzword_lint(text, expected):
|
| 139 |
+
from inversion.compiler import buzzwords
|
| 140 |
+
assert buzzwords(text) == expected
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def test_apply_patch_rejects_injected_buzzwords():
|
| 144 |
+
prompt = "Flat gouache on paper. A red circle on the left. A sign reading \"RETRO\" at the top."
|
| 145 |
+
patch = RewritePatch(edits=[{"original": "A red circle", "revised": "A vintage red circle"},
|
| 146 |
+
{"original": "on the left", "revised": "on the far left, retro"}],
|
| 147 |
+
additions=["Cinematic lighting", "A small blue square at the bottom right"])
|
| 148 |
+
res = apply_patch(prompt, patch)
|
| 149 |
+
assert "vintage" not in res.prompt and "Cinematic" not in res.prompt
|
| 150 |
+
assert "on the far left, retro" in res.prompt # 'retro' already present (visible text), so allowed
|
| 151 |
+
assert res.added == ["A small blue square at the bottom right."]
|
| 152 |
+
assert sum("unverified" in s["reason"] for s in res.skipped) == 2
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
def test_extract_json_handles_fences_and_think():
|
| 156 |
+
raw = "<think>hmm</think>```json\n{\"a\": {\"b\": 1}}\n```"
|
| 157 |
+
assert json.loads(extract_json(raw)) == {"a": {"b": 1}}
|
| 158 |
+
|
| 159 |
+
|
| 160 |
+
def test_proxy_size_keeps_aspect_and_multiple_of_16():
|
| 161 |
+
w, h = proxy_size((3000, 2000))
|
| 162 |
+
assert (w, h) == (1024, 688) and w % 16 == 0 and h % 16 == 0
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def test_medoid():
|
| 166 |
+
def emb(v):
|
| 167 |
+
return DinoEmbedding(cls=torch.tensor(v, dtype=torch.float32), patches=torch.tensor([v], dtype=torch.float32))
|
| 168 |
+
idx, _ = medoid_index([emb([1, 0]), emb([1, 0.1]), emb([1, 0.2])])
|
| 169 |
+
assert idx == 1
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
# ---------------------------------------------------------------- full loop with stub backends
|
| 173 |
+
|
| 174 |
+
class StubWorld:
|
| 175 |
+
"""Proxy 'renders' encode the prompt; the scorer says yes iff the statement's key phrase is in it."""
|
| 176 |
+
|
| 177 |
+
def __init__(self, fix_on_rewrite=True):
|
| 178 |
+
self.fix_on_rewrite = fix_on_rewrite
|
| 179 |
+
self.rendered: dict[int, str] = {}
|
| 180 |
+
self.rewrites = 0
|
| 181 |
+
self.og = Image.new("RGB", (640, 480), "white")
|
| 182 |
+
|
| 183 |
+
def extract(self, image):
|
| 184 |
+
return graph()
|
| 185 |
+
|
| 186 |
+
def vqa(self, image, statements, template):
|
| 187 |
+
assert "{}" in template
|
| 188 |
+
if id(image) not in self.rendered: # OG grounding: all true except the hallucinated palette color
|
| 189 |
+
return [0.1 if "ochre" in s else 0.95 for s in statements]
|
| 190 |
+
prompt = self.rendered[id(image)]
|
| 191 |
+
# 18 predicates: one failure at 0.0 pulls the mean to ~0.87 (< 0.90 gate).
|
| 192 |
+
return [0.92 if ("rotated" not in s or "rotated 45 degrees, clearly" in prompt) else 0.0 for s in statements]
|
| 193 |
+
|
| 194 |
+
def rewrite(self, og, proxy, prompt, failed):
|
| 195 |
+
self.rewrites += 1
|
| 196 |
+
assert any("rotated 45 degrees" in f for f in failed)
|
| 197 |
+
if not self.fix_on_rewrite:
|
| 198 |
+
return RewritePatch(edits=[{"original": "not in prompt", "revised": "x"}])
|
| 199 |
+
return RewritePatch(edits=[{"original": "rotated 45 degrees", "revised": "rotated 45 degrees, clearly"}])
|
| 200 |
+
|
| 201 |
+
def render(self, prompt, seed, w, h):
|
| 202 |
+
img = Image.new("RGB", (w, h), "white")
|
| 203 |
+
self.rendered[id(img)] = prompt
|
| 204 |
+
return img
|
| 205 |
+
|
| 206 |
+
def embed(self, image):
|
| 207 |
+
return DinoEmbedding(cls=torch.ones(4), patches=torch.ones(9, 4))
|
| 208 |
+
|
| 209 |
+
def backends(self):
|
| 210 |
+
return Backends(self.extract, self.vqa, self.rewrite, self.render, self.embed)
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def test_loop_converges_after_targeted_rewrite():
|
| 214 |
+
world = StubWorld()
|
| 215 |
+
run = invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=5))
|
| 216 |
+
assert run.stop_reason == "converged"
|
| 217 |
+
assert len(run.iterations) == 2 and world.rewrites == 1
|
| 218 |
+
assert "ochre" not in run.canonical_prompt # pruned during grounding
|
| 219 |
+
assert run.best.t == 2 and "clearly" in run.best_prompt
|
| 220 |
+
assert run.best.mean_vqa >= 0.9 and run.best.dino_patch == pytest.approx(1.0)
|
| 221 |
+
json.dumps(run.to_dict()) # report is serializable
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
@pytest.mark.parametrize("sign_really_at, expect_move", [("bottom-center", True), (None, False)])
|
| 225 |
+
def test_grounding_relocalizes_rejected_grid_cell(sign_really_at, expect_move):
|
| 226 |
+
world = StubWorld()
|
| 227 |
+
base_vqa = world.vqa
|
| 228 |
+
|
| 229 |
+
def vqa(image, statements, template):
|
| 230 |
+
scores = base_vqa(image, statements, template)
|
| 231 |
+
if id(image) in world.rendered:
|
| 232 |
+
return scores
|
| 233 |
+
# On the original, the sign is NOT top-center (the extractor's claim) but at `sign_really_at`.
|
| 234 |
+
return [(0.95 if sign_really_at and sign_really_at in s else 0.05)
|
| 235 |
+
if ("PALACE" in s and "located in" in s) else sc for s, sc in zip(statements, scores)]
|
| 236 |
+
|
| 237 |
+
world.vqa = vqa
|
| 238 |
+
run = invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=1))
|
| 239 |
+
if expect_move:
|
| 240 |
+
assert run.relocalized == [{"node": "sign", "entity": 'a sign reading "PALACE"', "from": "Top-Center",
|
| 241 |
+
"to": "Bot-Center", "p_yes": 0.95}]
|
| 242 |
+
assert 'In the bottom-center of the frame, a sign reading "PALACE"' in run.canonical_prompt
|
| 243 |
+
assert "pos:sign" in {p.id for p in run.predicates}
|
| 244 |
+
assert "bottom-center" in next(p for p in run.predicates if p.id == "pos:sign").statement
|
| 245 |
+
else:
|
| 246 |
+
assert run.relocalized == []
|
| 247 |
+
assert "pos:sign" in {sp.predicate.id for sp in run.dropped}
|
| 248 |
+
assert "pos:sign" not in {p.id for p in run.predicates}
|
| 249 |
+
|
| 250 |
+
|
| 251 |
+
def test_loop_hits_max_iters_and_keeps_best():
|
| 252 |
+
world = StubWorld(fix_on_rewrite=False)
|
| 253 |
+
run = invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=3))
|
| 254 |
+
assert run.stop_reason == "max_iters"
|
| 255 |
+
assert len(run.iterations) == 3 and world.rewrites == 2 # no rewrite after the final render
|
| 256 |
+
assert run.iterations[0].patch.skipped and run.best_prompt == run.canonical_prompt
|