Spaces:
Running on Zero
Running on Zero
GPU Changes. FLux update
Browse files- README.md +92 -51
- app.py +18 -84
- app/theme.css +74 -0
- inversion/backends.py +51 -4
- inversion/engine.py +4 -1
- inversion/proxy.py +51 -10
- requirements.txt +1 -1
- tests/test_engine.py +39 -0
README.md
CHANGED
|
@@ -12,8 +12,9 @@ license: apache-2.0
|
|
| 12 |
suggested_hardware: zero-a10g
|
| 13 |
models:
|
| 14 |
- Qwen/Qwen3-VL-8B-Instruct
|
|
|
|
| 15 |
- black-forest-labs/FLUX.1-schnell
|
| 16 |
-
- facebook/
|
| 17 |
library_name: transformers
|
| 18 |
tags:
|
| 19 |
- image-to-prompt
|
|
@@ -29,13 +30,13 @@ short_description: Turn any image into a verified text-to-image prompt.
|
|
| 29 |
|
| 30 |
# Prompt Reverse Engineer
|
| 31 |
|
| 32 |
-
Turn an image into a verified text-to-image prompt. A closed-loop pipeline extracts a constrained scene graph, grounds every fact on the original, renders with a proxy model, scores each predicate with VQAScore and layout with
|
| 33 |
|
| 34 |
[](LICENSE)
|
| 35 |
[](https://github.com/glarrainv/Prompt-Reverse-Engineer/stargazers)
|
| 36 |
[](https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer)
|
| 37 |
[](https://www.python.org/)
|
| 38 |
-
[](https://pytorch.org/)
|
| 40 |
[](https://huggingface.co/docs/transformers)
|
| 41 |
[](LICENSE)
|
|
@@ -44,18 +45,19 @@ Turn an image into a verified text-to-image prompt. A closed-loop pipeline extra
|
|
| 44 |
|
| 45 |
## Overview
|
| 46 |
|
| 47 |
-
**Prompt Reverse Engineer** inverts text-to-image generation: instead of prompting a model and hoping the output matches your vision, you provide an image and get back a prompt whose
|
| 48 |
|
| 49 |
1. **Extract** a Davidsonian Scene Graph (DSG) — entities, attributes, relations, and medium/optics on a 3×3 grid
|
| 50 |
2. **Ground** every predicate on the original image; drop or re-localize facts the scorer rejects
|
| 51 |
-
3. **Render** the linearized prompt with a fast proxy model (FLUX.
|
| 52 |
-
4. **Verify** with VQAScore (predicate agreement) and
|
| 53 |
|
| 54 |
**What makes this different:**
|
| 55 |
-
|
|
|
|
| 56 |
- Targeted diff rewrites: only failed predicates are edited, preserving the rest
|
| 57 |
-
- Dual-gate stopping: both predicate agreement (S_VQA) and layout similarity (S_DINO) must clear configurable thresholds
|
| 58 |
-
- Two deployment pathways: local GPUs (Qwen3-VL + FLUX +
|
| 59 |
- Gradio UI for Hugging Face Spaces (ZeroGPU-ready) and Python CLI for batch runs
|
| 60 |
- Full JSON report with every iteration, scores, predicates, and proxy renders
|
| 61 |
|
|
@@ -74,21 +76,48 @@ Turn an image into a verified text-to-image prompt. A closed-loop pipeline extra
|
|
| 74 |
git clone https://github.com/glarrainv/Prompt-Reverse-Engineer.git
|
| 75 |
cd Prompt-Reverse-Engineer
|
| 76 |
|
| 77 |
-
# 2. Create venv and install (
|
|
|
|
| 78 |
python -m venv .venv
|
| 79 |
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
| 80 |
pip install --upgrade pip
|
| 81 |
pip install -r requirements.txt
|
| 82 |
|
| 83 |
-
# 3.
|
| 84 |
-
|
|
|
|
| 85 |
|
| 86 |
# 4. Run the Gradio UI
|
| 87 |
python app.py
|
| 88 |
# → opens at http://localhost:7860
|
| 89 |
```
|
| 90 |
|
| 91 |
-
> **GPU
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
### Option C: Python CLI (batch processing)
|
| 94 |
|
|
@@ -112,27 +141,28 @@ python cli.py medoid --input renders/ --out medoids.json --key patch --copy-to m
|
|
| 112 |
| `--seed N` | Base seed (proxy seed = base + t) | `42` |
|
| 113 |
| `--no-ground` | Skip grounding on original (not recommended) | off |
|
| 114 |
|
| 115 |
-
### Option D: Docker (
|
|
|
|
|
|
|
| 116 |
|
| 117 |
```dockerfile
|
| 118 |
-
|
| 119 |
-
FROM pytorch/pytorch:2.13.0-cuda12.1-cudnn9-runtime
|
| 120 |
WORKDIR /app
|
| 121 |
COPY requirements.txt .
|
| 122 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 123 |
COPY . .
|
| 124 |
EXPOSE 7860
|
|
|
|
| 125 |
CMD ["python", "app.py"]
|
| 126 |
```
|
| 127 |
|
| 128 |
```bash
|
| 129 |
docker build -t prompt-reverse-engineer .
|
| 130 |
-
|
| 131 |
-
docker run --gpus all -p 7860:7860 prompt-reverse-engineer
|
| 132 |
-
# CPU (slow):
|
| 133 |
-
docker run -p 7860:7860 prompt-reverse-engineer
|
| 134 |
```
|
| 135 |
|
|
|
|
|
|
|
| 136 |
### Option E: API-only pathway (no local GPU)
|
| 137 |
|
| 138 |
Set these environment variables before launching:
|
|
@@ -165,33 +195,36 @@ All model backends and runtime knobs are controlled via environment variables (s
|
|
| 165 |
| Variable | Meaning | Default | Notes |
|
| 166 |
|----------|---------|---------|-------|
|
| 167 |
| `VLM_BACKEND` | `local` or `api` | `local` | VLM for DSG extraction + rewrite |
|
| 168 |
-
| `VLM_MODEL_ID` | HF repo (local) | `Qwen/Qwen3-VL-8B-Instruct` |
|
| 169 |
| `VLM_API_MODEL` | Model name (api) | `qwen/qwen3-vl-32b-instruct` | OpenRouter format |
|
| 170 |
| `VLM_API_BASE_URL` | API base URL | `https://openrouter.ai/api/v1` | |
|
| 171 |
| `VLM_API_KEY` | API key | — | Required if `VLM_BACKEND=api` |
|
| 172 |
| `SCORER_BACKEND` | `local` or `api` | auto (matches VLM) | VQAScore backend |
|
| 173 |
| `SCORER_API_MODEL` | API model for scoring | `gpt-4o` | Needs logprobs |
|
| 174 |
| `SCORER_API_KEY` | API key for scorer | `$OPENAI_API_KEY` | |
|
|
|
|
| 175 |
| `PROXY_BACKEND` | `flux` or `fal` | `flux` | Proxy renderer |
|
| 176 |
-
| `PROXY_MODEL_ID` | HF repo (flux) | `black-forest-labs/FLUX.1-schnell`
|
| 177 |
-
| `PROXY_CPU_OFFLOAD` |
|
|
|
|
|
|
|
| 178 |
| `FAL_ENDPOINT` | FAL endpoint | `fal-ai/flux/schnell` | If `PROXY_BACKEND=fal` |
|
| 179 |
-
| `DINO_MODEL_ID` | DINO model | `facebook/
|
| 180 |
-
| `DINO_DEVICE` | `cuda`
|
| 181 |
-
| `VQA_MODE` | `normalized` or `
|
| 182 |
|
| 183 |
**EngineConfig** (Python API / CLI flags) — runtime gates per run:
|
| 184 |
|
| 185 |
-
| Key | Meaning | Default |
|
| 186 |
|-----|---------|---------|-------|
|
| 187 |
-
| `max_iters` | Max rewrite
|
| 188 |
| `vqa_gate` | S_VQA convergence threshold | `0.90` | 0.5–1.0 |
|
| 189 |
-
| `dino_gate` | S_DINO convergence threshold | `0.80` | 0.0–1.0 |
|
| 190 |
-
| `fail_threshold` |
|
| 191 |
-
| `parent_gate` | DSG
|
| 192 |
| `ground` | Enable grounding on original | `True` | — |
|
| 193 |
-
| `grounding_threshold` |
|
| 194 |
-
| `w_vqa` |
|
| 195 |
| `base_seed` | Base seed (proxy seed = base + t) | `42` | — |
|
| 196 |
| `proxy_long_side` | Proxy render long side (px) | `1024` | — |
|
| 197 |
|
|
@@ -239,7 +272,8 @@ save_run(run, "runs/my_image", og)
|
|
| 239 |
### Gradio UI (app.py)
|
| 240 |
|
| 241 |
The Space UI exposes:
|
| 242 |
-
|
|
|
|
| 243 |
- Stopping rule sliders: max iterations, S_VQA gate, S_DINO gate
|
| 244 |
- Advanced accordion: failure threshold, S_VQA weight, base seed, grounding toggle
|
| 245 |
- Live streaming: stage progress bar, per-iteration scores, predicate table, scene graph JSON, grounding log
|
|
@@ -282,7 +316,7 @@ Input image
|
|
| 282 |
┌─────────────────────────────────────┐
|
| 283 |
│ Module 4: Dual verification │ → scored[] (Predicate + raw/effective)
|
| 284 |
│ VQAScore each predicate on proxy │ • mean_vqa (S_VQA)
|
| 285 |
-
│
|
| 286 |
│ Joint = w_vqa·S_VQA + w_dino·S_DINO│
|
| 287 |
└─────────────────────────────────────┘
|
| 288 |
│
|
|
@@ -299,17 +333,20 @@ Input image
|
|
| 299 |
```json
|
| 300 |
{
|
| 301 |
"config": { ...EngineConfig... },
|
|
|
|
| 302 |
"stop_reason": "converged" | "max_iters",
|
| 303 |
"best_prompt": "verified prompt string",
|
| 304 |
"best_iteration": 3,
|
| 305 |
"best_scores": { "S_VQA": 0.92, "S_DINO_patch": 0.84, "joint": 0.88 },
|
| 306 |
"canonical_prompt": "initial linearization",
|
| 307 |
"proxy_size": [1024, 768],
|
| 308 |
-
"
|
| 309 |
-
"
|
| 310 |
-
"
|
|
|
|
| 311 |
"grounding_relocalized": [ { "node", "entity", "from", "to", "p_yes" }, ... ],
|
| 312 |
-
"iterations": [ { "t", "seed", "prompt", "S_VQA", "S_DINO_patch", "
|
|
|
|
| 313 |
}
|
| 314 |
```
|
| 315 |
|
|
@@ -317,14 +354,17 @@ Input image
|
|
| 317 |
|
| 318 |
## Performance
|
| 319 |
|
| 320 |
-
|
| 321 |
-
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
|
| 325 |
-
|
|
|
|
|
|
|
|
|
|
| 326 |
|
| 327 |
-
|
| 328 |
|
| 329 |
---
|
| 330 |
|
|
@@ -332,13 +372,14 @@ Input image
|
|
| 332 |
|
| 333 |
| Symptom | Cause | Fix |
|
| 334 |
|---------|-------|-----|
|
| 335 |
-
| `CUDA out of memory` | VRAM exhausted | Set `PROXY_CPU_OFFLOAD=1`; reduce `proxy_long_side`; use API pathway |
|
|
|
|
| 336 |
| `VLM_API_KEY not set` | API pathway selected without key | Export `VLM_API_KEY` (OpenRouter) or switch to `VLM_BACKEND=local` |
|
| 337 |
| `gpt-4o logprobs unavailable` | Scorer API key lacks logprobs access | Use OpenAI key with logprobs; or set `SCORER_BACKEND=local` |
|
| 338 |
-
| `FLUX
|
| 339 |
-
| `
|
| 340 |
| Gradio UI won't load | Port 7860 in use | `GRADIO_SERVER_PORT=7861 python app.py` |
|
| 341 |
-
|
|
| 342 |
|
| 343 |
**Logs:** Gradio console output shows per-stage status. CLI prints iteration status to stdout. Full run data in `runs/<stem>/report.json`.
|
| 344 |
|
|
@@ -354,7 +395,7 @@ Input image
|
|
| 354 |
This work builds on the following research:
|
| 355 |
|
| 356 |
```bibtex
|
| 357 |
-
@
|
| 358 |
title={Davidsonian Scene Graph: Improving Reliability in Fine-grained Evaluation for Text-to-Image Generation},
|
| 359 |
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},
|
| 360 |
booktitle={International Conference on Learning Representations (ICLR)},
|
|
|
|
| 12 |
suggested_hardware: zero-a10g
|
| 13 |
models:
|
| 14 |
- Qwen/Qwen3-VL-8B-Instruct
|
| 15 |
+
- black-forest-labs/FLUX.2-klein-4B
|
| 16 |
- black-forest-labs/FLUX.1-schnell
|
| 17 |
+
- facebook/dinov2-base
|
| 18 |
library_name: transformers
|
| 19 |
tags:
|
| 20 |
- image-to-prompt
|
|
|
|
| 30 |
|
| 31 |
# Prompt Reverse Engineer
|
| 32 |
|
| 33 |
+
Turn an image into a verified text-to-image prompt. A closed-loop pipeline extracts a constrained scene graph, grounds every fact on the original, renders with a proxy model, scores each predicate with VQAScore and layout with DINOv2, and rewrites only what fails — until both gates clear or iterations run out.
|
| 34 |
|
| 35 |
[](LICENSE)
|
| 36 |
[](https://github.com/glarrainv/Prompt-Reverse-Engineer/stargazers)
|
| 37 |
[](https://huggingface.co/spaces/glarr/Prompt-Reverse-Engineer)
|
| 38 |
[](https://www.python.org/)
|
| 39 |
+
[](https://gradio.app/)
|
| 40 |
[](https://pytorch.org/)
|
| 41 |
[](https://huggingface.co/docs/transformers)
|
| 42 |
[](LICENSE)
|
|
|
|
| 45 |
|
| 46 |
## Overview
|
| 47 |
|
| 48 |
+
**Prompt Reverse Engineer** inverts text-to-image generation: instead of prompting a model and hoping the output matches your vision, you provide an image and get back a prompt whose claims are checked, one by one, against a proxy render of that prompt. The pipeline runs four stages in a loop:
|
| 49 |
|
| 50 |
1. **Extract** a Davidsonian Scene Graph (DSG) — entities, attributes, relations, and medium/optics on a 3×3 grid
|
| 51 |
2. **Ground** every predicate on the original image; drop or re-localize facts the scorer rejects
|
| 52 |
+
3. **Render** the linearized prompt with a fast proxy model (FLUX.2-klein-4B by default; FLUX.1-schnell is supported)
|
| 53 |
+
4. **Verify** with VQAScore (predicate agreement) and DINOv2 (layout similarity); **rewrite** only failed facts
|
| 54 |
|
| 55 |
**What makes this different:**
|
| 56 |
+
|
| 57 |
+
- Grounding on the original: facts the scorer rejects on the original image are removed (or, for grid positions, re-localized) before rendering, and rewrites cannot introduce era/style buzzwords that the grounded prompt does not already contain. Grounding is only as good as the scorer: with the local backend the same model extracts and scores, so shared blind spots remain (use `SCORER_BACKEND=api` for an independent check)
|
| 58 |
- Targeted diff rewrites: only failed predicates are edited, preserving the rest
|
| 59 |
+
- Dual-gate stopping: both predicate agreement (S_VQA) and layout similarity (S_DINO) must clear configurable thresholds; if they never do, the best iteration is returned and the report says `max_iters`
|
| 60 |
+
- Two deployment pathways: local GPUs (Qwen3-VL + FLUX + DINOv2) or API-only (OpenRouter + FAL + gpt-4o)
|
| 61 |
- Gradio UI for Hugging Face Spaces (ZeroGPU-ready) and Python CLI for batch runs
|
| 62 |
- Full JSON report with every iteration, scores, predicates, and proxy renders
|
| 63 |
|
|
|
|
| 76 |
git clone https://github.com/glarrainv/Prompt-Reverse-Engineer.git
|
| 77 |
cd Prompt-Reverse-Engineer
|
| 78 |
|
| 79 |
+
# 2. Create venv and install (requirements pin torch 2.13.0; on Windows, install the CUDA build
|
| 80 |
+
# of torch 2.13.0 from pytorch.org first, since the PyPI wheel there is CPU-only)
|
| 81 |
python -m venv .venv
|
| 82 |
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
| 83 |
pip install --upgrade pip
|
| 84 |
pip install -r requirements.txt
|
| 85 |
|
| 86 |
+
# 3. Nothing is gated with the default models. Only if you set
|
| 87 |
+
# PROXY_MODEL_ID=black-forest-labs/FLUX.1-schnell: accept its license on the model page, then log in
|
| 88 |
+
hf auth login # or export HF_TOKEN=hf_...
|
| 89 |
|
| 90 |
# 4. Run the Gradio UI
|
| 91 |
python app.py
|
| 92 |
# → opens at http://localhost:7860
|
| 93 |
```
|
| 94 |
|
| 95 |
+
> **GPU memory (local pathway).** All three models stay loaded. In bf16 the default weights are ~33.9 GB (Qwen3-VL-8B 17.5 GB, FLUX.2-klein-4B 16.0 GB, DINOv2-B 0.35 GB), plus activations, so a 48 GB GPU is the practical minimum. Ways to fit smaller cards, or to use the larger proxy (estimates from weight sizes, not benchmarks):
|
| 96 |
+
>
|
| 97 |
+
> | Setting | Weights on GPU | Fits |
|
| 98 |
+
> | --- | --- | --- |
|
| 99 |
+
> | default (klein-4B, bf16) | ~33.9 GB | 48 GB GPU |
|
| 100 |
+
> | `PROXY_FP8=1` | ~30 GB | 40 GB GPU |
|
| 101 |
+
> | `PROXY_CPU_OFFLOAD=1` | ~18 GB + the active FLUX component (≤ 8 GB) | 24 GB GPU; slower |
|
| 102 |
+
> | `PROXY_BACKEND=fal` | ~18 GB | 24 GB GPU; FLUX runs on fal.ai (paid, needs `FAL_KEY`) |
|
| 103 |
+
> | `PROXY_MODEL_ID=black-forest-labs/FLUX.1-schnell` | ~51.6 GB | 80 GB GPU |
|
| 104 |
+
> | schnell + `PROXY_FP8=1` | ~40 GB | 48 GB GPU |
|
| 105 |
+
>
|
| 106 |
+
> `PROXY_FP8=1` stores the FLUX transformer in float8 and computes in bf16; proxy renders change slightly.
|
| 107 |
+
|
| 108 |
+
### Choosing the proxy model
|
| 109 |
+
|
| 110 |
+
The proxy renderer is the forward model the loop optimizes the prompt against, so the verified prompt is specific to it. `PROXY_MODEL_ID` selects it; the pipeline class, step count and guidance scale are read from the checkpoint:
|
| 111 |
+
|
| 112 |
+
| `PROXY_MODEL_ID` | Weights | Steps / guidance | License and access | Needs |
|
| 113 |
+
| --- | --- | --- | --- | --- |
|
| 114 |
+
| `black-forest-labs/FLUX.2-klein-4B` (default) | 16.0 GB (transformer 7.75, Qwen3 text encoder 8.0) | 4 / 1.0 | Apache-2.0, ungated | diffusers ≥ 0.37 |
|
| 115 |
+
| `black-forest-labs/FLUX.1-schnell` | 33.7 GB (transformer 23.8, T5-XXL 9.5) | 4 / 0.0 | Apache-2.0, gated (accept on the model page) | `HF_TOKEN` |
|
| 116 |
+
|
| 117 |
+
- Only step-distilled checkpoints work. `FLUX.2-klein-base-*` are rejected at startup (their `model_index.json` lacks `is_distilled: true`), and other pipelines raise an error listing the supported ones.
|
| 118 |
+
- With the default klein-4B no model in the stack is gated, so no `HF_TOKEN` is needed; FLUX.1-schnell requires one.
|
| 119 |
+
- Every run report records the models and proxy settings used under `"models"`. Keep one proxy for a whole stimulus bank: scores and prompts are not comparable across proxies.
|
| 120 |
+
- klein-4B is verified structurally (pipeline selection, 4 steps, guidance 1.0, fp8 casting, deterministic seeds) on a small random-weight pipeline; render quality on your stimuli has not been measured. Compare S_VQA and S_DINO against schnell on a few images before relying on either in a study.
|
| 121 |
|
| 122 |
### Option C: Python CLI (batch processing)
|
| 123 |
|
|
|
|
| 141 |
| `--seed N` | Base seed (proxy seed = base + t) | `42` |
|
| 142 |
| `--no-ground` | Skip grounding on original (not recommended) | off |
|
| 143 |
|
| 144 |
+
### Option D: Docker (GPU)
|
| 145 |
+
|
| 146 |
+
The repo has no Dockerfile; this one is a starting point and has not been tested.
|
| 147 |
|
| 148 |
```dockerfile
|
| 149 |
+
FROM pytorch/pytorch:2.13.0-cuda12.6-cudnn9-runtime
|
|
|
|
| 150 |
WORKDIR /app
|
| 151 |
COPY requirements.txt .
|
| 152 |
RUN pip install --no-cache-dir -r requirements.txt
|
| 153 |
COPY . .
|
| 154 |
EXPOSE 7860
|
| 155 |
+
ENV GRADIO_SERVER_NAME=0.0.0.0
|
| 156 |
CMD ["python", "app.py"]
|
| 157 |
```
|
| 158 |
|
| 159 |
```bash
|
| 160 |
docker build -t prompt-reverse-engineer .
|
| 161 |
+
docker run --gpus all -p 7860:7860 -e HF_TOKEN=hf_... prompt-reverse-engineer
|
|
|
|
|
|
|
|
|
|
| 162 |
```
|
| 163 |
|
| 164 |
+
The local pathway is not practical on CPU (an 8B VLM plus a 12B diffusion transformer); without a GPU, use the API pathway below.
|
| 165 |
+
|
| 166 |
### Option E: API-only pathway (no local GPU)
|
| 167 |
|
| 168 |
Set these environment variables before launching:
|
|
|
|
| 195 |
| Variable | Meaning | Default | Notes |
|
| 196 |
|----------|---------|---------|-------|
|
| 197 |
| `VLM_BACKEND` | `local` or `api` | `local` | VLM for DSG extraction + rewrite |
|
| 198 |
+
| `VLM_MODEL_ID` | HF repo (local) | `Qwen/Qwen3-VL-8B-Instruct` | ~17.5 GB in bf16 (no quantization) |
|
| 199 |
| `VLM_API_MODEL` | Model name (api) | `qwen/qwen3-vl-32b-instruct` | OpenRouter format |
|
| 200 |
| `VLM_API_BASE_URL` | API base URL | `https://openrouter.ai/api/v1` | |
|
| 201 |
| `VLM_API_KEY` | API key | — | Required if `VLM_BACKEND=api` |
|
| 202 |
| `SCORER_BACKEND` | `local` or `api` | auto (matches VLM) | VQAScore backend |
|
| 203 |
| `SCORER_API_MODEL` | API model for scoring | `gpt-4o` | Needs logprobs |
|
| 204 |
| `SCORER_API_KEY` | API key for scorer | `$OPENAI_API_KEY` | |
|
| 205 |
+
| `SCORER_API_BASE_URL` | API base URL for scorer | OpenAI | |
|
| 206 |
| `PROXY_BACKEND` | `flux` or `fal` | `flux` | Proxy renderer |
|
| 207 |
+
| `PROXY_MODEL_ID` | HF repo (flux) | `black-forest-labs/FLUX.2-klein-4B` | Also supports `black-forest-labs/FLUX.1-schnell`; see "Choosing the proxy model" |
|
| 208 |
+
| `PROXY_CPU_OFFLOAD` | Keep FLUX on CPU and move each component to GPU only while it runs | `0` | Saves ~10–24 GB of GPU memory; slower. Local GPUs only, not ZeroGPU |
|
| 209 |
+
| `PROXY_FP8` | Store the FLUX transformer in float8, compute in bf16 | `0` | Saves ~3.9 GB of resident weights with klein-4B (~33.9 → ~30 GB) and ~12 GB with schnell (~51.6 → ~40 GB); slightly changes proxy renders |
|
| 210 |
+
| `ZEROGPU_SIZE` | `auto`, `large` or `xlarge` | `auto` | Size of every `@spaces.GPU` call; `auto` picks `xlarge` when resident weights exceed 42 GB (logged at startup) |
|
| 211 |
| `FAL_ENDPOINT` | FAL endpoint | `fal-ai/flux/schnell` | If `PROXY_BACKEND=fal` |
|
| 212 |
+
| `DINO_MODEL_ID` | DINO model | `facebook/dinov2-base` | DINOv2-B (ungated). Any DINOv2/DINOv3 checkpoint works; `facebook/dinov3-*` is gated with manual approval, and the 0.80 gate is not transferable between backbones |
|
| 213 |
+
| `DINO_DEVICE` | `cuda` or `cpu` | auto (CUDA if available) | |
|
| 214 |
+
| `VQA_MODE` | `normalized` or `yes` | `normalized` | `normalized` = P(yes) / (P(yes) + P(no)); `yes` = the original VQAScore, P("Yes") only (thresholds not comparable) |
|
| 215 |
|
| 216 |
**EngineConfig** (Python API / CLI flags) — runtime gates per run:
|
| 217 |
|
| 218 |
+
| Key | Meaning | Default | UI range |
|
| 219 |
|-----|---------|---------|-------|
|
| 220 |
+
| `max_iters` | Max proxy renders (render → verify → rewrite rounds) | `5` | 1–8 |
|
| 221 |
| `vqa_gate` | S_VQA convergence threshold | `0.90` | 0.5–1.0 |
|
| 222 |
+
| `dino_gate` | S_DINO convergence threshold (`0` = stop on S_VQA alone, the research plan's rule) | `0.80` | 0.0–1.0 |
|
| 223 |
+
| `fail_threshold` | Predicates scoring below this are sent to the rewriter | `0.75` | 0.3–0.95 |
|
| 224 |
+
| `parent_gate` | DSG rule: children of an entity scoring below this score 0 | `0.5` | — |
|
| 225 |
| `ground` | Enable grounding on original | `True` | — |
|
| 226 |
+
| `grounding_threshold` | P(yes) on the original below which a predicate is pruned; also the minimum for re-localizing a grid cell | `0.5` | — |
|
| 227 |
+
| `w_vqa` / `w_dino` | Weights of the joint score used to pick the best iteration | `0.7` / `0.3` | 0.0–1.0 |
|
| 228 |
| `base_seed` | Base seed (proxy seed = base + t) | `42` | — |
|
| 229 |
| `proxy_long_side` | Proxy render long side (px) | `1024` | — |
|
| 230 |
|
|
|
|
| 272 |
### Gradio UI (app.py)
|
| 273 |
|
| 274 |
The Space UI exposes:
|
| 275 |
+
|
| 276 |
+
- Image upload (drag-drop, file picker, clipboard paste)
|
| 277 |
- Stopping rule sliders: max iterations, S_VQA gate, S_DINO gate
|
| 278 |
- Advanced accordion: failure threshold, S_VQA weight, base seed, grounding toggle
|
| 279 |
- Live streaming: stage progress bar, per-iteration scores, predicate table, scene graph JSON, grounding log
|
|
|
|
| 316 |
┌─────────────────────────────────────┐
|
| 317 |
│ Module 4: Dual verification │ → scored[] (Predicate + raw/effective)
|
| 318 |
│ VQAScore each predicate on proxy │ • mean_vqa (S_VQA)
|
| 319 |
+
│ DINOv2 patch/cls similarity │ • dino_patch (S_DINO), dino_cls
|
| 320 |
│ Joint = w_vqa·S_VQA + w_dino·S_DINO│
|
| 321 |
└─────────────────────────────────────┘
|
| 322 |
│
|
|
|
|
| 333 |
```json
|
| 334 |
{
|
| 335 |
"config": { ...EngineConfig... },
|
| 336 |
+
"models": { "vlm_model", "scorer", "vqa_mode", "dino_model", "proxy_model", "proxy_pipeline", "proxy_steps", "proxy_guidance_scale", "proxy_fp8" },
|
| 337 |
"stop_reason": "converged" | "max_iters",
|
| 338 |
"best_prompt": "verified prompt string",
|
| 339 |
"best_iteration": 3,
|
| 340 |
"best_scores": { "S_VQA": 0.92, "S_DINO_patch": 0.84, "joint": 0.88 },
|
| 341 |
"canonical_prompt": "initial linearization",
|
| 342 |
"proxy_size": [1024, 768],
|
| 343 |
+
"raw_graph": { ...DSGSceneSchema as extracted... },
|
| 344 |
+
"graph": { ...DSGSceneSchema after grounding... },
|
| 345 |
+
"predicates": [ { "id", "kind", "statement", "parents", "ref" }, ... ],
|
| 346 |
+
"grounding_dropped": [ { "id", "kind", "statement", "parents", "p_yes", "effective", "blocked_by" }, ... ],
|
| 347 |
"grounding_relocalized": [ { "node", "entity", "from", "to", "p_yes" }, ... ],
|
| 348 |
+
"iterations": [ { "t", "seed", "prompt", "S_VQA", "S_DINO_patch", "S_DINO_cls", "joint",
|
| 349 |
+
"failed", "rewrite_notes", "patch", "rewrite_error", "predicates" }, ... ]
|
| 350 |
}
|
| 351 |
```
|
| 352 |
|
|
|
|
| 354 |
|
| 355 |
## Performance
|
| 356 |
|
| 357 |
+
No runtime benchmarks have been measured yet. What is known:
|
| 358 |
+
|
| 359 |
+
- **Downloads.** The local pathway fetches ~33.9 GB of weights on first run with the default proxy (Qwen3-VL-8B 17.5 GB, FLUX.2-klein-4B diffusers components 16.0 GB, DINOv2-B 0.35 GB), or ~51.6 GB with FLUX.1-schnell (33.7 GB); later runs use the cache. A fresh Space container downloads them at every cold start.
|
| 360 |
+
- **GPU memory.** See the table under Option B.
|
| 361 |
+
- **Calls per image.** One extraction, one grounding pass on the original (plus one re-localization pass if a grid cell is rejected), then per iteration one render, one VQA pass, two DINO embeddings, and a rewrite unless it is the last iteration. On ZeroGPU each of these is its own `@spaces.GPU` allocation.
|
| 362 |
+
|
| 363 |
+
### Hugging Face Space (ZeroGPU)
|
| 364 |
+
|
| 365 |
+
ZeroGPU copies all loaded weights onto the GPU at the start of every `@spaces.GPU` call, so they must fit the slice with room for activations. With the default FLUX.2-klein-4B the weights are ~33.9 GB, which fits a `large` slice (50.87 GB) in bf16, so no variables are needed. `ZEROGPU_SIZE=auto` reads the loaded weight size at startup and requests `xlarge` (the full GPU, double quota cost per second) only above 42 GB; the chosen size is logged as `[startup] resident model weights: … -> ZeroGPU size '…'`, and with the defaults it should read `'large'`. Nothing in the default stack is gated, so no `HF_TOKEN` is needed.
|
| 366 |
|
| 367 |
+
To run the Space on FLUX.1-schnell instead, set the variables `PROXY_MODEL_ID=black-forest-labs/FLUX.1-schnell` and `PROXY_FP8=1` (~40 GB, fits `large`; without fp8 it is ~51.6 GB and `auto` requests `xlarge`), accept its license on the model page, and add `HF_TOKEN` as a Space secret. `PROXY_FP8=1` also applies to klein-4B (~30 GB), so remove it to render in bf16.
|
| 368 |
|
| 369 |
---
|
| 370 |
|
|
|
|
| 372 |
|
| 373 |
| Symptom | Cause | Fix |
|
| 374 |
|---------|-------|-----|
|
| 375 |
+
| `CUDA out of memory` | VRAM exhausted | Set `PROXY_FP8=1` or `PROXY_CPU_OFFLOAD=1`; reduce `proxy_long_side`; use `PROXY_BACKEND=fal` or the API pathway |
|
| 376 |
+
| ZeroGPU: `memory allocation failed with OOM ... total: 50868518912` then `NVML_SUCCESS == r INTERNAL ASSERT FAILED` in `pack_to_cuda` | ZeroGPU copies all resident weights onto the GPU at the start of every call; with FLUX.1-schnell in bf16 they are ~51.6 GB and a `large` slice holds 50.87 GB | Use the default FLUX.2-klein-4B (~33.9 GB), or schnell with `PROXY_FP8=1` (~40 GB, fits `large`), or keep bf16 with `ZEROGPU_SIZE=auto`, which then requests `xlarge`; check the `[startup] ... ZeroGPU size` log line |
|
| 377 |
| `VLM_API_KEY not set` | API pathway selected without key | Export `VLM_API_KEY` (OpenRouter) or switch to `VLM_BACKEND=local` |
|
| 378 |
| `gpt-4o logprobs unavailable` | Scorer API key lacks logprobs access | Use OpenAI key with logprobs; or set `SCORER_BACKEND=local` |
|
| 379 |
+
| `Access denied` / 401 / 403 for FLUX.1-schnell (only if you set it as `PROXY_MODEL_ID`) | Gated repo | Accept the license on the model page, then `hf auth login` locally or add `HF_TOKEN` as a Space secret; or use the ungated default FLUX.2-klein-4B |
|
| 380 |
+
| `Access denied` for `facebook/dinov3-*` | Gated with manual approval | Use the default `facebook/dinov2-base` until access is granted |
|
| 381 |
| Gradio UI won't load | Port 7860 in use | `GRADIO_SERVER_PORT=7861 python app.py` |
|
| 382 |
+
| Space slow to start | Cold start downloads ~34 GB of weights (~52 GB with schnell), then ZeroGPU packs them | Normal; the first run after startup also waits for a GPU allocation |
|
| 383 |
|
| 384 |
**Logs:** Gradio console output shows per-stage status. CLI prints iteration status to stdout. Full run data in `runs/<stem>/report.json`.
|
| 385 |
|
|
|
|
| 395 |
This work builds on the following research:
|
| 396 |
|
| 397 |
```bibtex
|
| 398 |
+
@inproceedings{cho2024dsg,
|
| 399 |
title={Davidsonian Scene Graph: Improving Reliability in Fine-grained Evaluation for Text-to-Image Generation},
|
| 400 |
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},
|
| 401 |
booktitle={International Conference on Learning Representations (ICLR)},
|
app.py
CHANGED
|
@@ -1,47 +1,56 @@
|
|
| 1 |
import html
|
| 2 |
import json
|
| 3 |
import tempfile
|
|
|
|
| 4 |
|
| 5 |
import gradio as gr
|
| 6 |
import spaces
|
| 7 |
|
| 8 |
from inversion import EngineConfig, iter_inversion
|
| 9 |
-
from inversion.backends import BackendSettings, load_components
|
| 10 |
from inversion.engine import Backends
|
| 11 |
|
| 12 |
SETTINGS = BackendSettings()
|
| 13 |
C = load_components(SETTINGS)
|
| 14 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 15 |
|
| 16 |
# Each model call gets its own (short) ZeroGPU allocation instead of one long one
|
| 17 |
# for the whole loop. Outside Spaces/ZeroGPU, @spaces.GPU is a no-op.
|
| 18 |
-
@spaces.GPU(duration=180)
|
| 19 |
def gpu_extract(image):
|
| 20 |
return C.vlm.extract_dsg(image)
|
| 21 |
|
| 22 |
|
| 23 |
-
@spaces.GPU(duration=90)
|
| 24 |
def gpu_vqa(image, statements, template):
|
| 25 |
return C.scorer.vqa_scores(image, statements, template)
|
| 26 |
|
| 27 |
|
| 28 |
-
@spaces.GPU(duration=120)
|
| 29 |
def gpu_rewrite(og, proxy, prompt, failed):
|
| 30 |
return C.vlm.rewrite(og, proxy, prompt, failed)
|
| 31 |
|
| 32 |
|
| 33 |
-
@spaces.GPU(duration=60)
|
| 34 |
def gpu_render(prompt, seed, width, height):
|
| 35 |
return C.renderer(prompt, seed, width, height)
|
| 36 |
|
| 37 |
|
| 38 |
-
@spaces.GPU(duration=30)
|
| 39 |
def gpu_embed(image):
|
| 40 |
return C.dino.embed(image)
|
| 41 |
|
| 42 |
|
| 43 |
BACKENDS = Backends(extract_dsg=gpu_extract, vqa_scores=gpu_vqa, rewrite=gpu_rewrite,
|
| 44 |
-
render=gpu_render, embed=gpu_embed)
|
| 45 |
|
| 46 |
|
| 47 |
# --------------------------------------------------------------------------- look
|
|
@@ -99,82 +108,7 @@ THEME = gr.themes.Base(
|
|
| 99 |
section_header_text_weight="600",
|
| 100 |
)
|
| 101 |
|
| 102 |
-
|
| 103 |
-
:root{--pre-text:#14171F;--pre-muted:#5B6270;--pre-line:#E3E6EB;--pre-track:#EEF0F3;--pre-card:#FFFFFF;
|
| 104 |
-
--pre-accent:#2B59C3;--pre-accent-soft:#EAF0FC;--pre-pass:#176B45;--pre-pass-bg:#E6F4EC;
|
| 105 |
-
--pre-warn:#9A4508;--pre-warn-bg:#FDF0E3}
|
| 106 |
-
.dark{--pre-text:#E8EAEE;--pre-muted:#A3AAB8;--pre-line:#2E333D;--pre-track:#2A2F38;--pre-card:#171A20;
|
| 107 |
-
--pre-accent:#7FA2F0;--pre-accent-soft:#1D2A45;--pre-pass:#7AD3A4;--pre-pass-bg:#16332A;
|
| 108 |
-
--pre-warn:#F3B37A;--pre-warn-bg:#3A2716}
|
| 109 |
-
.gradio-container{max-width:1280px !important;margin:0 auto !important}
|
| 110 |
-
footer{display:none !important}
|
| 111 |
-
.pre-header{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:8px 0 4px}
|
| 112 |
-
.pre-brand{display:flex;align-items:center;gap:12px}
|
| 113 |
-
.pre-logo{width:32px;height:32px;border-radius:8px;background:var(--pre-text);display:flex;align-items:center;justify-content:center}
|
| 114 |
-
.pre-logo svg{stroke:var(--pre-card)}
|
| 115 |
-
.pre-title{font-weight:600;font-size:15px;line-height:1.2;color:var(--pre-text)}
|
| 116 |
-
.pre-sub{font-size:12px;color:var(--pre-muted)}
|
| 117 |
-
.pre-nav{display:flex;align-items:center;gap:20px;font-size:13px}
|
| 118 |
-
.pre-nav a{text-decoration:none;font-weight:500;color:var(--pre-accent)}
|
| 119 |
-
.pre-chip{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border:1px solid var(--pre-line);border-radius:999px;color:var(--pre-muted);font-size:12px}
|
| 120 |
-
.pre-dot{width:6px;height:6px;border-radius:999px;background:#1F8A5B}
|
| 121 |
-
.pre-step-title{margin:0 0 2px;font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--pre-muted)}
|
| 122 |
-
.pre-card{background:var(--pre-card);border:1px solid var(--pre-line);border-radius:12px;padding:20px 24px;color:var(--pre-text)}
|
| 123 |
-
.pre-row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px}
|
| 124 |
-
.pre-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;font-size:13px;font-weight:600}
|
| 125 |
-
.pre-badge.ok{background:var(--pre-pass-bg);color:var(--pre-pass)}
|
| 126 |
-
.pre-badge.warn{background:var(--pre-warn-bg);color:var(--pre-warn)}
|
| 127 |
-
.pre-badge.run{background:var(--pre-accent-soft);color:var(--pre-accent)}
|
| 128 |
-
.pre-muted{color:var(--pre-muted)}
|
| 129 |
-
.pre-stages{list-style:none;margin:20px 0;padding:0;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px}
|
| 130 |
-
.pre-stages li{display:flex;flex-direction:column;gap:6px;margin:0}
|
| 131 |
-
.pre-bar{height:4px;border-radius:999px;background:var(--pre-track)}
|
| 132 |
-
.pre-stages li.done .pre-bar{background:var(--pre-accent)}
|
| 133 |
-
.pre-stages li.active .pre-bar{background:var(--pre-accent);opacity:.45;animation:pre-pulse 1.2s ease-in-out infinite}
|
| 134 |
-
@keyframes pre-pulse{50%{opacity:1}}
|
| 135 |
-
.pre-n{font-family:var(--font-mono);font-size:12px;color:var(--pre-muted)}
|
| 136 |
-
.pre-stage-label{font-size:13px;font-weight:500;line-height:1.3}
|
| 137 |
-
.pre-stages li.pending .pre-stage-label{color:var(--pre-muted)}
|
| 138 |
-
.pre-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
|
| 139 |
-
.pre-tile{border:1px solid var(--pre-line);border-radius:10px;padding:14px 16px;display:flex;flex-direction:column;gap:8px}
|
| 140 |
-
.pre-tile-label{font-size:12px;color:var(--pre-muted)}
|
| 141 |
-
.pre-tile-value{font-family:var(--font-mono);font-size:28px;font-weight:600;letter-spacing:-.02em}
|
| 142 |
-
.pre-meter{position:relative;height:6px;border-radius:999px;background:var(--pre-track)}
|
| 143 |
-
.pre-meter-fill{position:absolute;left:0;top:0;bottom:0;border-radius:999px;background:var(--pre-accent)}
|
| 144 |
-
.pre-meter-gate{position:absolute;top:-3px;width:2px;height:12px;background:var(--pre-text)}
|
| 145 |
-
.pre-intro h1{margin:0 0 8px;font-size:26px;line-height:1.25;font-weight:600;letter-spacing:-.01em}
|
| 146 |
-
.pre-intro p{margin:0;max-width:62ch;font-size:15px;color:var(--pre-muted)}
|
| 147 |
-
.pre-how{list-style:none;margin:24px 0 0;padding:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
| 148 |
-
.pre-how li{border:1px solid var(--pre-line);border-radius:10px;padding:18px;display:flex;flex-direction:column;gap:6px;margin:0}
|
| 149 |
-
.pre-how .pre-n{color:var(--pre-accent);font-weight:500}
|
| 150 |
-
.pre-how b{font-weight:600}
|
| 151 |
-
.pre-how span{font-size:13px;color:var(--pre-muted)}
|
| 152 |
-
.pre-placeholder{margin-top:16px;border:1.5px dashed var(--pre-line);border-radius:12px;min-height:180px;display:flex;
|
| 153 |
-
flex-direction:column;align-items:center;justify-content:center;gap:6px;text-align:center;padding:32px}
|
| 154 |
-
.pre-placeholder span{font-size:13px;color:var(--pre-muted);max-width:46ch}
|
| 155 |
-
/* Gradio component polish */
|
| 156 |
-
.pre-group{border-radius:12px !important;overflow:hidden}
|
| 157 |
-
.pre-group-title{background:var(--block-background-fill) !important;padding:0 !important;min-height:0 !important}
|
| 158 |
-
.pre-group-title .pre-step-title{margin:0;padding:14px 12px 8px}
|
| 159 |
-
.pre-image{border:1.5px dashed var(--pre-drop) !important;border-radius:8px !important}
|
| 160 |
-
:root{--pre-drop:#B9C0CC}.dark{--pre-drop:#4A5160}
|
| 161 |
-
.pre-dl{max-width:240px !important;margin-left:auto !important;border:1px solid var(--input-border-color) !important}
|
| 162 |
-
.pre-panel{background:var(--block-background-fill) !important;border:1px solid var(--block-border-color) !important;
|
| 163 |
-
border-radius:12px !important;padding:4px 16px 16px !important}
|
| 164 |
-
.pre-results table,.pre-results table *,.pre-results td,.pre-results td *,.pre-results th *{
|
| 165 |
-
font-family:var(--font) !important;font-variant-numeric:tabular-nums}
|
| 166 |
-
@media (max-width:720px){
|
| 167 |
-
.pre-how{grid-template-columns:repeat(1,minmax(0,1fr))}
|
| 168 |
-
.pre-card{padding:16px}
|
| 169 |
-
.pre-stages{gap:4px}
|
| 170 |
-
.pre-stage-label{display:none}
|
| 171 |
-
.pre-tiles{gap:8px}
|
| 172 |
-
.pre-tile{padding:10px}
|
| 173 |
-
.pre-tile-label{font-size:11px}
|
| 174 |
-
.pre-tile-value{font-size:20px}
|
| 175 |
-
.pre-tile-value + .pre-muted{display:none}
|
| 176 |
-
}
|
| 177 |
-
"""
|
| 178 |
|
| 179 |
LOGO = ('<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" '
|
| 180 |
'stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15.5-6.2L21 8"/><path d="M21 3v5h-5"/>'
|
|
@@ -468,4 +402,4 @@ with gr.Blocks(title="Prompt Reverse Engineer") as demo:
|
|
| 468 |
)
|
| 469 |
|
| 470 |
if __name__ == "__main__":
|
| 471 |
-
demo.launch(theme=THEME,
|
|
|
|
| 1 |
import html
|
| 2 |
import json
|
| 3 |
import tempfile
|
| 4 |
+
from pathlib import Path
|
| 5 |
|
| 6 |
import gradio as gr
|
| 7 |
import spaces
|
| 8 |
|
| 9 |
from inversion import EngineConfig, iter_inversion
|
| 10 |
+
from inversion.backends import BackendSettings, choose_gpu_size, load_components
|
| 11 |
from inversion.engine import Backends
|
| 12 |
|
| 13 |
SETTINGS = BackendSettings()
|
| 14 |
C = load_components(SETTINGS)
|
| 15 |
|
| 16 |
+
# ZeroGPU copies ALL resident weights onto the GPU at the start of every @spaces.GPU call, so the slice
|
| 17 |
+
# must hold all of them plus activations. With the default FLUX.2-klein-4B the weights are ~33.9 GB and fit a
|
| 18 |
+
# "large" slice (50.87 GB). Qwen3-VL-8B + FLUX.1-schnell + DINOv2 in bf16 is ~51.6 GB, which fails with a CUDA
|
| 19 |
+
# OOM before any code runs, so choose_gpu_size() requests "xlarge" for it (or set PROXY_FP8=1 to fit "large").
|
| 20 |
+
RESIDENT_BYTES = C.resident_bytes()
|
| 21 |
+
GPU_SIZE = choose_gpu_size(SETTINGS.zerogpu_size, RESIDENT_BYTES)
|
| 22 |
+
print(f"[startup] resident model weights: {RESIDENT_BYTES / 1e9:.1f} GB -> ZeroGPU size '{GPU_SIZE}'", flush=True)
|
| 23 |
+
|
| 24 |
|
| 25 |
# Each model call gets its own (short) ZeroGPU allocation instead of one long one
|
| 26 |
# for the whole loop. Outside Spaces/ZeroGPU, @spaces.GPU is a no-op.
|
| 27 |
+
@spaces.GPU(duration=180, size=GPU_SIZE)
|
| 28 |
def gpu_extract(image):
|
| 29 |
return C.vlm.extract_dsg(image)
|
| 30 |
|
| 31 |
|
| 32 |
+
@spaces.GPU(duration=90, size=GPU_SIZE)
|
| 33 |
def gpu_vqa(image, statements, template):
|
| 34 |
return C.scorer.vqa_scores(image, statements, template)
|
| 35 |
|
| 36 |
|
| 37 |
+
@spaces.GPU(duration=120, size=GPU_SIZE)
|
| 38 |
def gpu_rewrite(og, proxy, prompt, failed):
|
| 39 |
return C.vlm.rewrite(og, proxy, prompt, failed)
|
| 40 |
|
| 41 |
|
| 42 |
+
@spaces.GPU(duration=60, size=GPU_SIZE)
|
| 43 |
def gpu_render(prompt, seed, width, height):
|
| 44 |
return C.renderer(prompt, seed, width, height)
|
| 45 |
|
| 46 |
|
| 47 |
+
@spaces.GPU(duration=30, size=GPU_SIZE)
|
| 48 |
def gpu_embed(image):
|
| 49 |
return C.dino.embed(image)
|
| 50 |
|
| 51 |
|
| 52 |
BACKENDS = Backends(extract_dsg=gpu_extract, vqa_scores=gpu_vqa, rewrite=gpu_rewrite,
|
| 53 |
+
render=gpu_render, embed=gpu_embed, meta=C.info)
|
| 54 |
|
| 55 |
|
| 56 |
# --------------------------------------------------------------------------- look
|
|
|
|
| 108 |
section_header_text_weight="600",
|
| 109 |
)
|
| 110 |
|
| 111 |
+
CSS_PATH = Path(__file__).parent / "app" / "theme.css" # custom styles; loaded via launch(css_paths=...)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 112 |
|
| 113 |
LOGO = ('<svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke-width="2" stroke-linecap="round" '
|
| 114 |
'stroke-linejoin="round" aria-hidden="true"><path d="M3 12a9 9 0 0 1 15.5-6.2L21 8"/><path d="M21 3v5h-5"/>'
|
|
|
|
| 402 |
)
|
| 403 |
|
| 404 |
if __name__ == "__main__":
|
| 405 |
+
demo.launch(theme=THEME, css_paths=[CSS_PATH])
|
app/theme.css
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
:root{--pre-text:#14171F;--pre-muted:#5B6270;--pre-line:#E3E6EB;--pre-track:#EEF0F3;--pre-card:#FFFFFF;
|
| 2 |
+
--pre-accent:#2B59C3;--pre-accent-soft:#EAF0FC;--pre-pass:#176B45;--pre-pass-bg:#E6F4EC;
|
| 3 |
+
--pre-warn:#9A4508;--pre-warn-bg:#FDF0E3}
|
| 4 |
+
.dark{--pre-text:#E8EAEE;--pre-muted:#A3AAB8;--pre-line:#2E333D;--pre-track:#2A2F38;--pre-card:#171A20;
|
| 5 |
+
--pre-accent:#7FA2F0;--pre-accent-soft:#1D2A45;--pre-pass:#7AD3A4;--pre-pass-bg:#16332A;
|
| 6 |
+
--pre-warn:#F3B37A;--pre-warn-bg:#3A2716}
|
| 7 |
+
.gradio-container{max-width:1280px !important;margin:0 auto !important}
|
| 8 |
+
footer{display:none !important}
|
| 9 |
+
.pre-header{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:8px 0 4px}
|
| 10 |
+
.pre-brand{display:flex;align-items:center;gap:12px}
|
| 11 |
+
.pre-logo{width:32px;height:32px;border-radius:8px;background:var(--pre-text);display:flex;align-items:center;justify-content:center}
|
| 12 |
+
.pre-logo svg{stroke:var(--pre-card)}
|
| 13 |
+
.pre-title{font-weight:600;font-size:15px;line-height:1.2;color:var(--pre-text)}
|
| 14 |
+
.pre-sub{font-size:12px;color:var(--pre-muted)}
|
| 15 |
+
.pre-nav{display:flex;align-items:center;gap:20px;font-size:13px}
|
| 16 |
+
.pre-nav a{text-decoration:none;font-weight:500;color:var(--pre-accent)}
|
| 17 |
+
.pre-chip{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border:1px solid var(--pre-line);border-radius:999px;color:var(--pre-muted);font-size:12px}
|
| 18 |
+
.pre-dot{width:6px;height:6px;border-radius:999px;background:#1F8A5B}
|
| 19 |
+
.pre-step-title{margin:0 0 2px;font-size:12px;font-weight:600;letter-spacing:.04em;text-transform:uppercase;color:var(--pre-muted)}
|
| 20 |
+
.pre-card{background:var(--pre-card);border:1px solid var(--pre-line);border-radius:12px;padding:20px 24px;color:var(--pre-text)}
|
| 21 |
+
.pre-row{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px}
|
| 22 |
+
.pre-badge{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;font-size:13px;font-weight:600}
|
| 23 |
+
.pre-badge.ok{background:var(--pre-pass-bg);color:var(--pre-pass)}
|
| 24 |
+
.pre-badge.warn{background:var(--pre-warn-bg);color:var(--pre-warn)}
|
| 25 |
+
.pre-badge.run{background:var(--pre-accent-soft);color:var(--pre-accent)}
|
| 26 |
+
.pre-muted{color:var(--pre-muted)}
|
| 27 |
+
.pre-stages{list-style:none;margin:20px 0;padding:0;display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:8px}
|
| 28 |
+
.pre-stages li{display:flex;flex-direction:column;gap:6px;margin:0}
|
| 29 |
+
.pre-bar{height:4px;border-radius:999px;background:var(--pre-track)}
|
| 30 |
+
.pre-stages li.done .pre-bar{background:var(--pre-accent)}
|
| 31 |
+
.pre-stages li.active .pre-bar{background:var(--pre-accent);opacity:.45;animation:pre-pulse 1.2s ease-in-out infinite}
|
| 32 |
+
@keyframes pre-pulse{50%{opacity:1}}
|
| 33 |
+
.pre-n{font-family:var(--font-mono);font-size:12px;color:var(--pre-muted)}
|
| 34 |
+
.pre-stage-label{font-size:13px;font-weight:500;line-height:1.3}
|
| 35 |
+
.pre-stages li.pending .pre-stage-label{color:var(--pre-muted)}
|
| 36 |
+
.pre-tiles{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}
|
| 37 |
+
.pre-tile{border:1px solid var(--pre-line);border-radius:10px;padding:14px 16px;display:flex;flex-direction:column;gap:8px}
|
| 38 |
+
.pre-tile-label{font-size:12px;color:var(--pre-muted)}
|
| 39 |
+
.pre-tile-value{font-family:var(--font-mono);font-size:28px;font-weight:600;letter-spacing:-.02em}
|
| 40 |
+
.pre-meter{position:relative;height:6px;border-radius:999px;background:var(--pre-track)}
|
| 41 |
+
.pre-meter-fill{position:absolute;left:0;top:0;bottom:0;border-radius:999px;background:var(--pre-accent)}
|
| 42 |
+
.pre-meter-gate{position:absolute;top:-3px;width:2px;height:12px;background:var(--pre-text)}
|
| 43 |
+
.pre-intro h1{margin:0 0 8px;font-size:26px;line-height:1.25;font-weight:600;letter-spacing:-.01em}
|
| 44 |
+
.pre-intro p{margin:0;max-width:62ch;font-size:15px;color:var(--pre-muted)}
|
| 45 |
+
.pre-how{list-style:none;margin:24px 0 0;padding:0;display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:16px}
|
| 46 |
+
.pre-how li{border:1px solid var(--pre-line);border-radius:10px;padding:18px;display:flex;flex-direction:column;gap:6px;margin:0}
|
| 47 |
+
.pre-how .pre-n{color:var(--pre-accent);font-weight:500}
|
| 48 |
+
.pre-how b{font-weight:600}
|
| 49 |
+
.pre-how span{font-size:13px;color:var(--pre-muted)}
|
| 50 |
+
.pre-placeholder{margin-top:16px;border:1.5px dashed var(--pre-line);border-radius:12px;min-height:180px;display:flex;
|
| 51 |
+
flex-direction:column;align-items:center;justify-content:center;gap:6px;text-align:center;padding:32px}
|
| 52 |
+
.pre-placeholder span{font-size:13px;color:var(--pre-muted);max-width:46ch}
|
| 53 |
+
/* Gradio component polish */
|
| 54 |
+
.pre-group{border-radius:12px !important;overflow:hidden}
|
| 55 |
+
.pre-group-title{background:var(--block-background-fill) !important;padding:0 !important;min-height:0 !important}
|
| 56 |
+
.pre-group-title .pre-step-title{margin:0;padding:14px 12px 8px}
|
| 57 |
+
.pre-image{border:1.5px dashed var(--pre-drop) !important;border-radius:8px !important}
|
| 58 |
+
:root{--pre-drop:#B9C0CC}.dark{--pre-drop:#4A5160}
|
| 59 |
+
.pre-dl{max-width:240px !important;margin-left:auto !important;border:1px solid var(--input-border-color) !important}
|
| 60 |
+
.pre-panel{background:var(--block-background-fill) !important;border:1px solid var(--block-border-color) !important;
|
| 61 |
+
border-radius:12px !important;padding:4px 16px 16px !important}
|
| 62 |
+
.pre-results table,.pre-results table *,.pre-results td,.pre-results td *,.pre-results th *{
|
| 63 |
+
font-family:var(--font) !important;font-variant-numeric:tabular-nums}
|
| 64 |
+
@media (max-width:720px){
|
| 65 |
+
.pre-how{grid-template-columns:repeat(1,minmax(0,1fr))}
|
| 66 |
+
.pre-card{padding:16px}
|
| 67 |
+
.pre-stages{gap:4px}
|
| 68 |
+
.pre-stage-label{display:none}
|
| 69 |
+
.pre-tiles{gap:8px}
|
| 70 |
+
.pre-tile{padding:10px}
|
| 71 |
+
.pre-tile-label{font-size:11px}
|
| 72 |
+
.pre-tile-value{font-size:20px}
|
| 73 |
+
.pre-tile-value + .pre-muted{display:none}
|
| 74 |
+
}
|
inversion/backends.py
CHANGED
|
@@ -47,8 +47,12 @@ class BackendSettings:
|
|
| 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.
|
| 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"))
|
|
@@ -64,6 +68,27 @@ class Components:
|
|
| 64 |
scorer: VLMBase
|
| 65 |
renderer: Callable[[str, int, int, int], Image.Image]
|
| 66 |
dino: DinoEmbedder
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
def backends(self) -> Backends:
|
| 69 |
return Backends(
|
|
@@ -72,9 +97,24 @@ class Components:
|
|
| 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
|
|
@@ -98,8 +138,8 @@ def load_components(settings: BackendSettings | None = None) -> Components:
|
|
| 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
|
| 102 |
-
renderer =
|
| 103 |
elif s.proxy_backend == "fal":
|
| 104 |
from .proxy import FalRenderer
|
| 105 |
renderer = FalRenderer(s.fal_endpoint)
|
|
@@ -107,4 +147,11 @@ def load_components(settings: BackendSettings | None = None) -> Components:
|
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.2-klein-4B"))
|
| 51 |
proxy_cpu_offload: bool = field(default_factory=lambda: _env("PROXY_CPU_OFFLOAD", "0") == "1")
|
| 52 |
+
proxy_fp8: bool = field(default_factory=lambda: _env("PROXY_FP8", "0") == "1")
|
| 53 |
+
# ZeroGPU slice: "auto" picks "xlarge" when the resident weights would not leave room for activations
|
| 54 |
+
# in a "large" slice (half an RTX PRO 6000, ~50.9 GB). Override with "large" or "xlarge".
|
| 55 |
+
zerogpu_size: str = field(default_factory=lambda: _env("ZEROGPU_SIZE", "auto").lower())
|
| 56 |
fal_endpoint: str = field(default_factory=lambda: _env("FAL_ENDPOINT", "fal-ai/flux/schnell"))
|
| 57 |
|
| 58 |
vqa_mode: str = field(default_factory=lambda: _env("VQA_MODE", "normalized"))
|
|
|
|
| 68 |
scorer: VLMBase
|
| 69 |
renderer: Callable[[str, int, int, int], Image.Image]
|
| 70 |
dino: DinoEmbedder
|
| 71 |
+
info: dict = field(default_factory=dict) # model ids / proxy settings, written into every run report
|
| 72 |
+
|
| 73 |
+
def resident_bytes(self) -> int:
|
| 74 |
+
"""Bytes of model weights held by the local components (what ZeroGPU packs and moves per call)."""
|
| 75 |
+
modules, seen = [], set()
|
| 76 |
+
for obj in (self.vlm, self.scorer, self.renderer, self.dino):
|
| 77 |
+
candidates = [getattr(obj, "model", None)]
|
| 78 |
+
pipe = getattr(obj, "pipe", None)
|
| 79 |
+
if pipe is not None:
|
| 80 |
+
candidates += list(getattr(pipe, "components", {}).values())
|
| 81 |
+
for m in candidates:
|
| 82 |
+
if m is not None and hasattr(m, "parameters") and id(m) not in seen:
|
| 83 |
+
seen.add(id(m))
|
| 84 |
+
modules.append(m)
|
| 85 |
+
total, counted = 0, set()
|
| 86 |
+
for m in modules:
|
| 87 |
+
for t in list(m.parameters()) + list(m.buffers()):
|
| 88 |
+
if id(t) not in counted:
|
| 89 |
+
counted.add(id(t))
|
| 90 |
+
total += t.numel() * t.element_size()
|
| 91 |
+
return total
|
| 92 |
|
| 93 |
def backends(self) -> Backends:
|
| 94 |
return Backends(
|
|
|
|
| 97 |
rewrite=self.vlm.rewrite,
|
| 98 |
render=self.renderer,
|
| 99 |
embed=self.dino.embed,
|
| 100 |
+
meta=self.info,
|
| 101 |
)
|
| 102 |
|
| 103 |
|
| 104 |
+
# A ZeroGPU "large" slice is half an RTX PRO 6000 (50.87 GB observed). Every @spaces.GPU call first copies
|
| 105 |
+
# all resident weights onto it, so they must leave room for activations (FLUX at 1024 px, Qwen3-VL decoding).
|
| 106 |
+
LARGE_SLICE_WEIGHT_BUDGET = 42e9
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def choose_gpu_size(setting: str, resident_bytes: int) -> str:
|
| 110 |
+
"""ZeroGPU size for every @spaces.GPU call: an explicit 'large'/'xlarge', or 'auto' by weight size."""
|
| 111 |
+
if setting in ("large", "xlarge"):
|
| 112 |
+
return setting
|
| 113 |
+
if setting != "auto":
|
| 114 |
+
raise ValueError(f"ZEROGPU_SIZE must be 'auto', 'large' or 'xlarge', got {setting!r}")
|
| 115 |
+
return "xlarge" if resident_bytes > LARGE_SLICE_WEIGHT_BUDGET else "large"
|
| 116 |
+
|
| 117 |
+
|
| 118 |
def load_components(settings: BackendSettings | None = None) -> Components:
|
| 119 |
s = settings or BackendSettings()
|
| 120 |
from .dino import DinoEmbedder
|
|
|
|
| 138 |
raise ValueError(f"SCORER_BACKEND must be 'local' or 'api', got {scorer_backend!r}")
|
| 139 |
|
| 140 |
if s.proxy_backend == "flux":
|
| 141 |
+
from .proxy import FluxRenderer
|
| 142 |
+
renderer = FluxRenderer(s.proxy_model_id, cpu_offload=s.proxy_cpu_offload, fp8=s.proxy_fp8)
|
| 143 |
elif s.proxy_backend == "fal":
|
| 144 |
from .proxy import FalRenderer
|
| 145 |
renderer = FalRenderer(s.fal_endpoint)
|
|
|
|
| 147 |
raise ValueError(f"PROXY_BACKEND must be 'flux' or 'fal', got {s.proxy_backend!r}")
|
| 148 |
|
| 149 |
dino = DinoEmbedder(s.dino_model_id, device=s.dino_device)
|
| 150 |
+
info = {
|
| 151 |
+
"vlm_model": s.vlm_model_id if s.vlm_backend == "local" else s.vlm_api_model,
|
| 152 |
+
"scorer": "local (shares the VLM)" if scorer is vlm else s.scorer_api_model,
|
| 153 |
+
"vqa_mode": s.vqa_mode,
|
| 154 |
+
"dino_model": s.dino_model_id,
|
| 155 |
+
**getattr(renderer, "info", {}),
|
| 156 |
+
}
|
| 157 |
+
return Components(vlm=vlm, scorer=scorer, renderer=renderer, dino=dino, info=info)
|
inversion/engine.py
CHANGED
|
@@ -46,6 +46,7 @@ class Backends:
|
|
| 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
|
|
@@ -80,6 +81,7 @@ class IterationRecord:
|
|
| 80 |
@dataclass
|
| 81 |
class InversionRun:
|
| 82 |
config: EngineConfig
|
|
|
|
| 83 |
status: str = ""
|
| 84 |
raw_graph: DSGSceneSchema | None = None
|
| 85 |
graph: DSGSceneSchema | None = None
|
|
@@ -105,6 +107,7 @@ class InversionRun:
|
|
| 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,
|
|
@@ -149,7 +152,7 @@ def iter_inversion(og_image: Image.Image, backends: Backends,
|
|
| 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"
|
|
|
|
| 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 |
+
meta: dict = field(default_factory=dict) # which models produced the run; copied into the report
|
| 50 |
|
| 51 |
|
| 52 |
@dataclass
|
|
|
|
| 81 |
@dataclass
|
| 82 |
class InversionRun:
|
| 83 |
config: EngineConfig
|
| 84 |
+
models: dict = field(default_factory=dict)
|
| 85 |
status: str = ""
|
| 86 |
raw_graph: DSGSceneSchema | None = None
|
| 87 |
graph: DSGSceneSchema | None = None
|
|
|
|
| 107 |
best = self.best
|
| 108 |
return {
|
| 109 |
"config": asdict(self.config),
|
| 110 |
+
"models": self.models,
|
| 111 |
"stop_reason": self.stop_reason,
|
| 112 |
"best_prompt": self.best_prompt,
|
| 113 |
"best_iteration": best.t if best else None,
|
|
|
|
| 152 |
if cfg.max_iters < 1:
|
| 153 |
raise ValueError("max_iters must be >= 1")
|
| 154 |
og = og_image.convert("RGB")
|
| 155 |
+
run = InversionRun(config=cfg, models=dict(backends.meta))
|
| 156 |
|
| 157 |
# ---- Module 1: constrained DSG extraction
|
| 158 |
run.status = "Module 1 · extracting constrained scene graph"
|
inversion/proxy.py
CHANGED
|
@@ -19,30 +19,70 @@ def proxy_size(og_size: tuple[int, int], long_side: int = 1024, multiple: int =
|
|
| 19 |
return snap(w), snap(h)
|
| 20 |
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
import torch
|
| 28 |
-
from diffusers import
|
| 29 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
self.torch = torch
|
| 31 |
-
self.pipe =
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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.
|
|
|
|
| 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,
|
| 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 |
|
|
@@ -50,6 +90,7 @@ class FalRenderer:
|
|
| 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={
|
|
|
|
| 19 |
return snap(w), snap(h)
|
| 20 |
|
| 21 |
|
| 22 |
+
# Step-distilled proxies the renderer knows how to drive: diffusers pipeline class -> (steps, guidance_scale).
|
| 23 |
+
# The pipeline defaults (50 steps, guidance 4.0 for FLUX.2) are wrong for distilled weights, so both are explicit.
|
| 24 |
+
SUPPORTED_PROXY_PIPELINES: dict[str, tuple[int, float]] = {
|
| 25 |
+
"FluxPipeline": (4, 0.0), # black-forest-labs/FLUX.1-schnell
|
| 26 |
+
"Flux2KleinPipeline": (4, 1.0), # black-forest-labs/FLUX.2-klein-4B (step-distilled; needs diffusers >= 0.37)
|
| 27 |
+
}
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def proxy_defaults(class_name: str, is_distilled: bool | None = None) -> tuple[int, float]:
|
| 31 |
+
"""(steps, guidance_scale) for a proxy pipeline, rejecting ones this renderer cannot drive correctly."""
|
| 32 |
+
if class_name not in SUPPORTED_PROXY_PIPELINES:
|
| 33 |
+
raise ValueError(f"PROXY_MODEL_ID uses pipeline {class_name!r}; supported: "
|
| 34 |
+
f"{', '.join(SUPPORTED_PROXY_PIPELINES)} (FLUX.1-schnell, FLUX.2-klein-4B).")
|
| 35 |
+
if class_name == "Flux2KleinPipeline" and is_distilled is not True:
|
| 36 |
+
# The klein *base* models are not step-distilled: they need ~50 steps and classifier-free guidance.
|
| 37 |
+
raise ValueError("This FLUX.2 klein checkpoint is not step-distilled (`is_distilled` is not true in its "
|
| 38 |
+
"model_index.json), so 4-step rendering would be poor. Use black-forest-labs/FLUX.2-klein-4B.")
|
| 39 |
+
return SUPPORTED_PROXY_PIPELINES[class_name]
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class FluxRenderer:
|
| 43 |
+
"""Step-distilled FLUX proxy via diffusers: FLUX.1-schnell (default) or FLUX.2-klein-4B.
|
| 44 |
+
|
| 45 |
+
The pipeline class, step count and guidance scale come from the checkpoint's model_index.json, so
|
| 46 |
+
`PROXY_MODEL_ID` is the only switch.
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
def __init__(self, model_id: str = "black-forest-labs/FLUX.2-klein-4B", device: str | None = None,
|
| 50 |
+
cpu_offload: bool = False, steps: int | None = None, max_sequence_length: int = 512,
|
| 51 |
+
fp8: bool = False):
|
| 52 |
import torch
|
| 53 |
+
from diffusers import DiffusionPipeline
|
| 54 |
|
| 55 |
+
config = DiffusionPipeline.load_config(model_id) # model_index.json only; no weights yet
|
| 56 |
+
self.pipeline_class = config["_class_name"]
|
| 57 |
+
default_steps, self.guidance_scale = proxy_defaults(self.pipeline_class, config.get("is_distilled"))
|
| 58 |
+
self.steps = default_steps if steps is None else steps
|
| 59 |
+
self.max_sequence_length = max_sequence_length
|
| 60 |
self.torch = torch
|
| 61 |
+
self.pipe = DiffusionPipeline.from_pretrained(model_id, dtype=torch.bfloat16)
|
| 62 |
+
if fp8:
|
| 63 |
+
# Store the transformer in float8 and upcast each layer to bf16 when it runs (FLUX.1-schnell:
|
| 64 |
+
# ~24 GB -> ~12 GB). Norms and positional embeddings stay bf16. Opt-in: it slightly changes renders.
|
| 65 |
+
self.pipe.transformer.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn,
|
| 66 |
+
compute_dtype=torch.bfloat16)
|
| 67 |
if cpu_offload:
|
| 68 |
self.pipe.enable_model_cpu_offload()
|
| 69 |
else:
|
| 70 |
self.pipe.to(device or ("cuda" if torch.cuda.is_available() else "cpu"))
|
| 71 |
+
self.info = {"proxy_model": model_id, "proxy_pipeline": self.pipeline_class, "proxy_steps": self.steps,
|
| 72 |
+
"proxy_guidance_scale": self.guidance_scale, "proxy_fp8": bool(fp8)}
|
| 73 |
|
| 74 |
def __call__(self, prompt: str, seed: int, width: int, height: int) -> Image.Image:
|
| 75 |
generator = self.torch.Generator(device="cpu").manual_seed(int(seed))
|
| 76 |
+
# `prompt=` by keyword: Flux2KleinPipeline's first positional parameter is `image`, not `prompt`.
|
| 77 |
return self.pipe(
|
| 78 |
+
prompt=prompt, width=width, height=height, num_inference_steps=self.steps,
|
| 79 |
+
guidance_scale=self.guidance_scale, max_sequence_length=self.max_sequence_length, generator=generator,
|
| 80 |
).images[0]
|
| 81 |
|
| 82 |
|
| 83 |
+
FluxSchnellRenderer = FluxRenderer # backwards-compatible name
|
| 84 |
+
|
| 85 |
+
|
| 86 |
class FalRenderer:
|
| 87 |
"""fal-ai/flux/schnell over the fal.ai API (reads FAL_KEY from the environment)."""
|
| 88 |
|
|
|
|
| 90 |
import fal_client
|
| 91 |
|
| 92 |
self.fal, self.endpoint, self.steps = fal_client, endpoint, steps
|
| 93 |
+
self.info = {"proxy_model": endpoint, "proxy_pipeline": "fal", "proxy_steps": steps}
|
| 94 |
|
| 95 |
def __call__(self, prompt: str, seed: int, width: int, height: int) -> Image.Image:
|
| 96 |
result = self.fal.subscribe(self.endpoint, arguments={
|
requirements.txt
CHANGED
|
@@ -2,7 +2,7 @@ spaces
|
|
| 2 |
torch==2.13.0
|
| 3 |
torchvision==0.28.0
|
| 4 |
transformers==5.22.1
|
| 5 |
-
diffusers
|
| 6 |
accelerate
|
| 7 |
sentencepiece
|
| 8 |
protobuf
|
|
|
|
| 2 |
torch==2.13.0
|
| 3 |
torchvision==0.28.0
|
| 4 |
transformers==5.22.1
|
| 5 |
+
diffusers>=0.37.0
|
| 6 |
accelerate
|
| 7 |
sentencepiece
|
| 8 |
protobuf
|
tests/test_engine.py
CHANGED
|
@@ -152,6 +152,45 @@ def test_apply_patch_rejects_injected_buzzwords():
|
|
| 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}}
|
|
|
|
| 152 |
assert sum("unverified" in s["reason"] for s in res.skipped) == 2
|
| 153 |
|
| 154 |
|
| 155 |
+
def test_choose_gpu_size():
|
| 156 |
+
from inversion.backends import choose_gpu_size
|
| 157 |
+
assert choose_gpu_size("auto", int(51.6e9)) == "xlarge" # Qwen3-VL-8B + FLUX bf16 + DINOv2: OOM on 'large'
|
| 158 |
+
assert choose_gpu_size("auto", int(39.7e9)) == "large" # with PROXY_FP8=1
|
| 159 |
+
assert choose_gpu_size("large", int(80e9)) == "large" # explicit override wins
|
| 160 |
+
with pytest.raises(ValueError):
|
| 161 |
+
choose_gpu_size("huge", 0)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def test_resident_bytes_counts_shared_weights_once():
|
| 165 |
+
from types import SimpleNamespace
|
| 166 |
+
from inversion.backends import Components
|
| 167 |
+
vlm = SimpleNamespace(model=torch.nn.Linear(10, 10)) # 110 fp32 params = 440 bytes
|
| 168 |
+
pipe = SimpleNamespace(components={"transformer": torch.nn.Linear(4, 4, dtype=torch.bfloat16), "tok": "x"})
|
| 169 |
+
comps = Components(vlm=vlm, scorer=vlm, renderer=SimpleNamespace(pipe=pipe),
|
| 170 |
+
dino=SimpleNamespace(model=torch.nn.Embedding(2, 3)))
|
| 171 |
+
assert comps.resident_bytes() == 440 + 20 * 2 + 6 * 4
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
def test_proxy_defaults_and_rejections():
|
| 175 |
+
from inversion.proxy import proxy_defaults
|
| 176 |
+
assert proxy_defaults("FluxPipeline") == (4, 0.0) # FLUX.1-schnell
|
| 177 |
+
assert proxy_defaults("Flux2KleinPipeline", True) == (4, 1.0) # FLUX.2-klein-4B (model_index: is_distilled true)
|
| 178 |
+
for distilled in (None, False): # klein *base* checkpoints have no is_distilled key
|
| 179 |
+
with pytest.raises(ValueError, match="not step-distilled"):
|
| 180 |
+
proxy_defaults("Flux2KleinPipeline", distilled)
|
| 181 |
+
with pytest.raises(ValueError, match="supported"):
|
| 182 |
+
proxy_defaults("StableDiffusionXLPipeline")
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def test_run_report_records_the_models_used():
|
| 186 |
+
world = StubWorld()
|
| 187 |
+
backends = world.backends()
|
| 188 |
+
backends.meta = {"proxy_model": "black-forest-labs/FLUX.2-klein-4B", "proxy_steps": 4, "proxy_guidance_scale": 1.0}
|
| 189 |
+
report = invert_image_to_verified_prompt(world.og, backends, EngineConfig(max_iters=3)).to_dict()
|
| 190 |
+
assert report["models"] == backends.meta
|
| 191 |
+
assert invert_image_to_verified_prompt(world.og, world.backends(), EngineConfig(max_iters=1)).to_dict()["models"] == {}
|
| 192 |
+
|
| 193 |
+
|
| 194 |
def test_extract_json_handles_fences_and_think():
|
| 195 |
raw = "<think>hmm</think>```json\n{\"a\": {\"b\": 1}}\n```"
|
| 196 |
assert json.loads(extract_json(raw)) == {"a": {"b": 1}}
|