File size: 4,932 Bytes
24baf68
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Evaluate a trained DWD tail on one GPU: generated images (DWD head vs the original and adapted VAE outputs) and,
with --val-root, reconstruction of held-out real images. Writes <out>/results.json and comparison grids.

    python scripts/evaluate.py --ckpt checkpoints/my-run/latest --out eval/my-run --prompts 64 --val-root ./data

--ckpt takes a training checkpoint (.pt; the EMA weights are used unless --no-ema), a run directory or its `latest`
pointer file, or a safetensors file holding the student tail's state dict.
"""

from __future__ import annotations

import argparse
import json
import os
import sys
import time

sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "src"))

import torch  # noqa: E402

from dwd_klein.encoders import BASE_MODEL  # noqa: E402


def resolve_ckpt(path: str) -> str:
    """Run dir or its `latest` file -> the checkpoint it names; anything else passes through."""
    if os.path.isdir(path):
        path = os.path.join(path, "latest")
    if os.path.basename(path) == "latest" and os.path.isfile(path):
        with open(path) as fh:
            return os.path.join(os.path.dirname(path), fh.read().strip())
    return path


def build_prompts(n: int, seed: int, val_root: str | None) -> list[dict]:
    """n prompts: the built-in list, or with val_root every odd prompt replaced by a held-out caption."""
    from dwd_klein.data import val_subset
    from dwd_klein.evaluate import default_prompts

    prompts = default_prompts(n, seed)
    for p in prompts:
        p["source"] = "builtin"
    if val_root:
        pool = val_subset(val_root, n, seed=seed + 1)  # a separate draw from the reconstruction images
        for i, p in enumerate(prompts):
            j = i // 2
            if i % 2 == 1 and j < len(pool):
                p["prompt"], p["source"] = pool[j][2], pool[j][3]
    return prompts


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0],
                                 formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    ap.add_argument("--ckpt", required=True, help="training checkpoint (.pt), run dir, `latest` file or .safetensors")
    ap.add_argument("--out", required=True, help="output directory")
    ap.add_argument("--model-path", default=BASE_MODEL, help="Hugging Face repo id or local diffusers directory")
    ap.add_argument("--prompts", type=int, default=64, help="number of generated images")
    ap.add_argument("--val-root", default=None, help="dataset root with val shards (optional)")
    ap.add_argument("--n-val", type=int, default=32, help="held-out images to reconstruct (with --val-root)")
    ap.add_argument("--grids", type=int, default=6, help="comparison grids written per kind")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--no-ema", action="store_true", help="use the raw student weights instead of the EMA")
    ap.add_argument("--no-stock", action="store_true", help="skip the stock bf16 reference images")
    a = ap.parse_args(argv)

    from diffusers import FlowMatchEulerDiscreteScheduler

    from dwd_klein.build import load_trained
    from dwd_klein.data import val_subset
    from dwd_klein.encoders import VAE, TextEncoder, resolve
    from dwd_klein.evaluate import Sampler, evaluate

    if not torch.cuda.is_available():
        raise SystemExit("evaluation needs a CUDA GPU")
    t0 = time.perf_counter()
    dev = torch.device("cuda")
    torch.backends.cuda.matmul.allow_tf32 = True
    ckpt = resolve_ckpt(a.ckpt)
    mp = resolve(a.model_path)
    model, info = load_trained(ckpt, dev, mp, use_ema=not a.no_ema)
    sampler = Sampler(model, TextEncoder(mp, dev), VAE(mp, dev),
                      FlowMatchEulerDiscreteScheduler.from_pretrained(mp, subfolder="scheduler"), dev)
    prompts = build_prompts(a.prompts, a.seed, a.val_root)
    val = val_subset(a.val_root, a.n_val, seed=a.seed) if a.val_root and a.n_val > 0 else []
    summary, grids = evaluate(sampler, prompts, val, n_grids=a.grids, log=lambda m: print(m, flush=True),
                              stock=not a.no_stock)
    res = {"ckpt": ckpt, **info, "n_prompts": len(prompts), "n_val": len(val),
           "prompt_sources": {s: sum(p["source"] == s for p in prompts) for s in sorted({p["source"] for p in prompts})},
           "val_strata": sorted({f"{v[3]}/{v[4]}" for v in val}), "summary": summary,
           "wall_s": round(time.perf_counter() - t0, 1)}
    os.makedirs(a.out, exist_ok=True)
    with open(os.path.join(a.out, "results.json"), "w") as fh:
        json.dump(res, fh, indent=1)
    for n, b in grids.items():
        with open(os.path.join(a.out, n), "wb") as fh:
            fh.write(b)
    print(json.dumps(summary, indent=1), flush=True)
    print(f"wrote {os.path.join(a.out, 'results.json')} and {len(grids)} grids", flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())