File size: 12,652 Bytes
d13a83d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
#!/usr/bin/env python3
"""Assess, edit, and evaluate one image with the released MR-IQA-2 models.

Actor, Editor, and Judge run sequentially, so all three stages can reuse one
physical GPU without sharing model memory.
"""

from __future__ import annotations

import argparse
import json
import math
import os
import shutil
import subprocess
import sys
from pathlib import Path
from typing import Any, Callable


REPO_ID = "RobinY99/MR-IQA-2"
SEED = 764952063587760
ROOT = Path(__file__).resolve().parents[1]
if str(ROOT) not in sys.path:
    sys.path.insert(0, str(ROOT))


def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
    parser = argparse.ArgumentParser(
        description="Run MR-IQA-2 Actor, Editor, and Judge on one GPU."
    )
    parser.add_argument("image", help="Input image")
    parser.add_argument("--output-dir", default="outputs/quick_start")
    parser.add_argument("--gpu", default="0", help="Physical GPU index")
    parser.add_argument("--actor-env", default="mr_iqa_actor_judge")
    parser.add_argument("--editor-env", default="mr_iqa_editor")
    parser.add_argument("--actor-python", default="")
    parser.add_argument("--editor-python", default="")
    parser.add_argument("--actor-model", default=REPO_ID)
    parser.add_argument("--actor-subfolder", default="actor")
    parser.add_argument("--judge-model", default=REPO_ID)
    parser.add_argument("--judge-subfolder", default="judge")
    parser.add_argument(
        "--editor-model",
        default="",
        help="Local Editor directory; omitted means REPO_ID/editor",
    )
    parser.add_argument(
        "--revision",
        default="",
        help="Optional Hugging Face revision; defaults to the current model release",
    )
    parser.add_argument("--max-pixels", type=int, default=196608)
    parser.add_argument("--local-files-only", action="store_true")
    parser.add_argument(
        "--stage",
        choices=("actor", "editor", "judge"),
        help=argparse.SUPPRESS,
    )
    args = parser.parse_args(argv)
    if args.max_pixels < 256:
        parser.error("--max-pixels must be at least 256")
    return args


def _actor_stage(args: argparse.Namespace, image_path: Path, output_dir: Path) -> None:
    from actor_to_editor import (
        atomic_write_json,
        atomic_write_text,
        generate_actor_completion,
        parse_valid_actor_output,
    )

    actor_args = argparse.Namespace(
        actor_model=args.actor_model,
        actor_subfolder=args.actor_subfolder,
        actor_revision=(
            ""
            if Path(args.actor_model).expanduser().is_dir()
            else args.revision
        ),
        device="cuda:0",
        dtype="bfloat16",
        attn_implementation="sdpa",
        max_new_tokens=512,
        max_pixels=args.max_pixels,
        seed=SEED,
        local_files_only=args.local_files_only,
    )
    completion = generate_actor_completion(image_path, actor_args)
    payload = parse_valid_actor_output(completion)
    atomic_write_text(output_dir / "actor_raw.txt", completion)
    atomic_write_json(output_dir / "assessment.json", payload)
    print(json.dumps(payload, ensure_ascii=False, indent=2))


def _editor_size(width: int, height: int, max_pixels: int) -> tuple[int, int]:
    scale = min(1.0, math.sqrt(float(max_pixels) / float(width * height)))
    resized_width = max(16, int(width * scale) // 16 * 16)
    resized_height = max(16, int(height * scale) // 16 * 16)
    return resized_width, resized_height


def _editor_stage(args: argparse.Namespace, image_path: Path, output_dir: Path) -> None:
    import torch
    from diffusers import Flux2KleinPipeline
    from huggingface_hub import snapshot_download
    from PIL import Image

    from actor_to_editor import atomic_write_json

    assessment_path = output_dir / "assessment.json"
    assessment = json.loads(assessment_path.read_text(encoding="utf-8"))
    reasoning = assessment.get("reasoning")
    if not isinstance(reasoning, dict):
        raise ValueError("assessment.json has no reasoning object")
    solution = reasoning.get("solution")
    if not isinstance(solution, str) or not solution.strip():
        raise ValueError("assessment.json has no usable solution")

    if args.editor_model:
        editor_path = Path(args.editor_model).expanduser().resolve(strict=True)
    else:
        download_kwargs: dict[str, Any] = {
            "repo_id": REPO_ID,
            "allow_patterns": ["editor/**"],
            "local_files_only": args.local_files_only,
        }
        if args.revision:
            download_kwargs["revision"] = args.revision
        snapshot = Path(
            snapshot_download(**download_kwargs)
        )
        editor_path = snapshot / "editor"
    editor = Flux2KleinPipeline.from_pretrained(
        editor_path,
        torch_dtype=torch.bfloat16,
        local_files_only=True,
    ).to("cuda")

    with Image.open(image_path) as opened:
        source = opened.convert("RGB")
    edit_width, edit_height = _editor_size(
        source.width,
        source.height,
        args.max_pixels,
    )
    editor_input = source.resize(
        (edit_width, edit_height),
        Image.Resampling.LANCZOS,
    )
    with torch.inference_mode():
        edited = editor(
            prompt=solution,
            image=editor_input,
            width=edit_width,
            height=edit_height,
            num_inference_steps=4,
            sigmas=[1.0, 0.75, 0.5, 0.25],
            guidance_scale=1.0,
            generator=torch.Generator(device="cuda").manual_seed(SEED),
            max_sequence_length=512,
            text_encoder_out_layers=(9, 18, 27),
        ).images[0].convert("RGB")
    if edited.size != source.size:
        edited = edited.resize(source.size, Image.Resampling.LANCZOS)

    edited_path = output_dir / "edited.png"
    edited.save(edited_path)
    result = {
        "input_image": str(image_path),
        "assessment": assessment,
        "edited_image": str(edited_path),
        "actor_model": (
            f"{args.actor_model}/{args.actor_subfolder}"
            if args.actor_subfolder and not Path(args.actor_model).expanduser().is_dir()
            else args.actor_model
        ),
        "editor_model": args.editor_model or f"{REPO_ID}/editor",
        "revision": args.revision or None,
        "seed": SEED,
        "original_size": [source.width, source.height],
        "inference_size": [edit_width, edit_height],
        "solution_forwarded_verbatim": (
            solution == assessment["reasoning"]["solution"]
        ),
        "judge": None,
    }
    atomic_write_json(output_dir / "result.json", result)


def _quality_delta(original: dict[str, Any], edited: dict[str, Any]) -> float:
    original_score = original.get("mean")
    edited_score = edited.get("mean")
    if not isinstance(original_score, (int, float)):
        raise ValueError("Judge did not return a valid score for the input image")
    if not isinstance(edited_score, (int, float)):
        raise ValueError("Judge did not return a valid score for the edited image")
    return float(edited_score) - float(original_score)


def _resolve_model_subfolder(
    model: str,
    subfolder: str,
    revision: str,
    local_files_only: bool,
) -> Path:
    from huggingface_hub import snapshot_download

    local_path = Path(model).expanduser()
    if local_path.is_dir():
        candidate = (
            local_path
            if (local_path / "config.json").is_file()
            else local_path / subfolder
        )
        return candidate.resolve(strict=True)
    download_kwargs: dict[str, Any] = {
        "repo_id": model,
        "allow_patterns": [f"{subfolder}/**"],
        "local_files_only": local_files_only,
    }
    if revision:
        download_kwargs["revision"] = revision
    snapshot = Path(snapshot_download(**download_kwargs))
    return (snapshot / subfolder).resolve(strict=True)


def _judge_stage(args: argparse.Namespace, image_path: Path, output_dir: Path) -> None:
    from actor_to_editor import atomic_write_json

    judge_path = _resolve_model_subfolder(
        args.judge_model,
        args.judge_subfolder,
        args.revision,
        args.local_files_only,
    )
    os.environ["VF_JUDGE_MODEL_PATH"] = str(judge_path)
    os.environ["VF_JUDGE_MODEL_ID"] = "mr-iqa-2-e5-judge"
    os.environ["VF_JUDGE_PROMPT_SCHEMA"] = "e5_training_reasoning_v5"
    os.environ["VF_JUDGER_MAX_BATCH_SIZE"] = "1"

    from judge.server import FrozenJudger

    edited_path = (output_dir / "edited.png").resolve(strict=True)
    judger = FrozenJudger(str(judge_path))
    original = judger.score_image(str(image_path), repeats=1)
    edited = judger.score_image(str(edited_path), repeats=1)
    delta = _quality_delta(original, edited)
    evaluation = {
        "j0": original["mean"],
        "j1": edited["mean"],
        "j1_minus_j0": delta,
        "original": original,
        "edited": edited,
        "judge_model": str(judge_path),
        "revision": args.revision or None,
    }
    atomic_write_json(output_dir / "evaluation.json", evaluation)

    result_path = output_dir / "result.json"
    result = json.loads(result_path.read_text(encoding="utf-8"))
    result["judge"] = evaluation
    atomic_write_json(result_path, result)


def _stage_command(
    *,
    conda: str,
    environment: str,
    python_executable: str,
    stage: str,
    args: argparse.Namespace,
    image_path: Path,
    output_dir: Path,
) -> list[str]:
    command = (
        [python_executable]
        if python_executable
        else [conda, "run", "--no-capture-output", "-n", environment, "python"]
    )
    command.extend(
        [
            str(Path(__file__).resolve()),
            str(image_path),
            "--output-dir",
            str(output_dir),
            "--gpu",
            "0",
            "--max-pixels",
            str(args.max_pixels),
            "--actor-model",
            args.actor_model,
            "--actor-subfolder",
            args.actor_subfolder,
            "--judge-model",
            args.judge_model,
            "--judge-subfolder",
            args.judge_subfolder,
            "--editor-model",
            args.editor_model,
            "--stage",
            stage,
        ]
    )
    if args.local_files_only:
        command.append("--local-files-only")
    if args.revision:
        command.extend(["--revision", args.revision])
    return command


def run_sequential(
    args: argparse.Namespace,
    *,
    command_runner: Callable[..., Any] = subprocess.run,
) -> dict[str, Any]:
    image_path = Path(args.image).expanduser().resolve(strict=True)
    if not image_path.is_file():
        raise FileNotFoundError(f"input image is not a file: {image_path}")
    output_dir = Path(args.output_dir).expanduser().resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    conda = shutil.which("conda") or ""
    if not conda and (not args.actor_python or not args.editor_python):
        raise RuntimeError("conda is required to run the two validated environments")

    child_environment = os.environ.copy()
    child_environment["CUDA_VISIBLE_DEVICES"] = str(args.gpu)
    child_environment["PYTHONUNBUFFERED"] = "1"
    for stage, environment, python_executable in (
        ("actor", args.actor_env, args.actor_python),
        ("editor", args.editor_env, args.editor_python),
        ("judge", args.actor_env, args.actor_python),
    ):
        command_runner(
            _stage_command(
                conda=conda,
                environment=environment,
                python_executable=python_executable,
                stage=stage,
                args=args,
                image_path=image_path,
                output_dir=output_dir,
            ),
            check=True,
            env=child_environment,
        )
    return json.loads((output_dir / "result.json").read_text(encoding="utf-8"))


def main(argv: list[str] | None = None) -> int:
    args = parse_args(argv)
    image_path = Path(args.image).expanduser().resolve(strict=True)
    output_dir = Path(args.output_dir).expanduser().resolve()
    output_dir.mkdir(parents=True, exist_ok=True)
    if args.stage == "actor":
        _actor_stage(args, image_path, output_dir)
        return 0
    if args.stage == "editor":
        _editor_stage(args, image_path, output_dir)
        return 0
    if args.stage == "judge":
        _judge_stage(args, image_path, output_dir)
        return 0

    result = run_sequential(args)
    print(json.dumps(result, ensure_ascii=False, indent=2))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())