File size: 9,441 Bytes
b0d8bdd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# Copyright 2026 Nikhil Raghavendra
# SPDX-License-Identifier: Apache-2.0
"""Reference evaluation for SEN-Bridge.

Usage::

    python scripts/evaluate.py SAMPLES.npy --data DATASET_DIR_OR_REPO
        [--split test] [--fid-stats stats/fid_test.npz] [--framework torch|jax]
        [--bootstrap 1000] [--out results.json]

``SAMPLES.npy`` holds one generated optical image per example of the split, in
dataset order: uint8 ``[N, 128, 128, 3]`` or float in [-1, 1]. The script reports
FID (against the statistics file, or against the split's targets if none is given)
and per-image PSNR, SSIM and LPIPS as mean and std, with 95% bootstrap intervals
resampled by geographic cluster. Never use the test split to choose models.
"""

from __future__ import annotations

import argparse
import json
from pathlib import Path
from typing import TYPE_CHECKING, Any, Protocol

import numpy as np
from datasets import load_dataset

if TYPE_CHECKING:
    from numpy.typing import NDArray

_HALF_RANGE = 127.5
_METRICS = ("psnr", "ssim", "lpips")
_CI = (2.5, 97.5)


class Backend(Protocol):
    """A metrics backend (PyTorch or JAX) behind a common interface."""

    def paired(
        self, gen: NDArray[Any], tgt: NDArray[Any]
    ) -> tuple[NDArray[Any], NDArray[Any], NDArray[Any]]:
        """Score generated images against targets.

        Args:
            gen: Generated images, uint8 or float in [-1, 1], ``[B, H, W, 3]``.
            tgt: Target images, same shape.

        Returns:
            PSNR, SSIM and LPIPS for each image.
        """
        ...

    def feed(self, images: NDArray[Any], *, real: bool) -> None:
        """Add images to the FID accumulator.

        Args:
            images: Images, uint8 or float in [-1, 1], ``[B, H, W, 3]``.
            real: Whether they are real targets.
        """
        ...

    def fid(self) -> float:
        """Compute the FID.

        Returns:
            The Frechet Inception Distance.
        """
        ...


def to_float(x: NDArray[Any]) -> NDArray[np.float32]:
    """Map images to float32 in [-1, 1].

    Args:
        x: uint8 images, or floats that are already in [-1, 1].

    Returns:
        Float32 images in [-1, 1].
    """
    if x.dtype == np.uint8:
        return x.astype(np.float32) / _HALF_RANGE - 1
    return x.astype(np.float32)


class TorchBackend:
    """Metrics from ``sen_bridge.torch``."""

    def __init__(self, stats: Path | None) -> None:
        """Create the backend.

        Args:
            stats: Real-target statistics file, or ``None`` to featurise the
                targets.
        """
        # torch is an optional dependency, imported only when selected.
        import torch  # ruff: ignore[import-outside-top-level]

        # Same optional dependency as the import above.
        from sen_bridge import torch as sb  # ruff: ignore[import-outside-top-level]

        self._torch, self._sb = torch, sb
        self._fid = sb.FID.from_stats(stats) if stats else sb.FID()

    # Returns a framework tensor, which has no common static type.
    def _prep(self, x: NDArray[Any]) -> Any:  # ruff: ignore[any-type]
        batch = self._torch.from_numpy(to_float(x)).permute(0, 3, 1, 2)
        return batch.to(
            self._fid.device
        )  # LPIPS-VGG on 30k pairs is far too slow on CPU

    def paired(
        self, gen: NDArray[Any], tgt: NDArray[Any]
    ) -> tuple[NDArray[Any], NDArray[Any], NDArray[Any]]:
        """Score generated images against targets.

        Args:
            gen: Generated images, ``[B, H, W, 3]``.
            tgt: Target images, same shape.

        Returns:
            PSNR, SSIM and LPIPS for each image.
        """
        a, b = self._prep(gen), self._prep(tgt)
        return (
            self._sb.psnr(a, b).cpu().numpy(),
            self._sb.ssim(a, b).cpu().numpy(),
            self._sb.lpips(a, b).cpu().numpy(),
        )

    def feed(self, images: NDArray[Any], *, real: bool) -> None:
        """Add images to the FID accumulator.

        Args:
            images: Images, ``[B, H, W, 3]``.
            real: Whether they are real targets.
        """
        self._fid.update(self._prep(images), real=real)

    def fid(self) -> float:
        """Compute the FID.

        Returns:
            The Frechet Inception Distance.
        """
        return self._fid.compute()


class JaxBackend:
    """Metrics from ``sen_bridge.jax``."""

    def __init__(self, stats: Path | None) -> None:
        """Create the backend.

        Args:
            stats: Real-target statistics file, or ``None`` to featurise the
                targets.
        """
        # jax is an optional dependency, imported only when selected.
        import jax  # ruff: ignore[import-outside-top-level]

        # Same optional dependency as the import above.
        import jax.numpy as jnp  # ruff: ignore[import-outside-top-level]

        # Same optional dependency as the import above.
        from sen_bridge import jax as sb  # ruff: ignore[import-outside-top-level]

        self._jnp = jnp
        self._fns = [jax.jit(jax.vmap(f)) for f in (sb.psnr, sb.ssim, sb.lpips)]
        self._fid = sb.FID.from_stats(stats) if stats else sb.FID()

    def paired(
        self, gen: NDArray[Any], tgt: NDArray[Any]
    ) -> tuple[NDArray[Any], NDArray[Any], NDArray[Any]]:
        """Score generated images against targets.

        Args:
            gen: Generated images, ``[B, H, W, 3]``.
            tgt: Target images, same shape.

        Returns:
            PSNR, SSIM and LPIPS for each image.
        """
        a, b = self._jnp.asarray(to_float(gen)), self._jnp.asarray(to_float(tgt))
        psnr, ssim, lpips = (np.asarray(f(a, b)) for f in self._fns)
        return psnr, ssim, lpips

    def feed(self, images: NDArray[Any], *, real: bool) -> None:
        """Add images to the FID accumulator.

        Args:
            images: Images, ``[B, H, W, 3]``.
            real: Whether they are real targets.
        """
        self._fid.update(self._jnp.asarray(to_float(images)), real=real)

    def fid(self) -> float:
        """Compute the FID.

        Returns:
            The Frechet Inception Distance.
        """
        return self._fid.compute()


def cluster_bootstrap(
    values: dict[str, NDArray[Any]],
    clusters: NDArray[Any],
    n: int,
) -> dict[str, tuple[float, float]]:
    """Bootstrap 95% intervals of per-image means, resampling whole clusters.

    Args:
        values: Per-image scores by metric name.
        clusters: Cluster id of each image.
        n: Number of bootstrap resamples.

    Returns:
        The lower and upper bound for each metric.
    """
    unique = np.unique(clusters)
    members = {c: np.flatnonzero(clusters == c) for c in unique}
    rng = np.random.default_rng(0)
    draws = []
    for _ in range(n):
        picked = np.concatenate([
            members[c] for c in rng.choice(unique, len(unique))
        ])
        draws.append([v[picked].mean() for v in values.values()])
    low, high = np.percentile(draws, _CI, axis=0)
    return {
        k: (float(a), float(b)) for k, a, b in zip(values, low, high, strict=True)
    }


def main() -> None:
    """Evaluate a set of generated samples and print the metrics as JSON.

    Raises:
        SystemExit: If the number of samples differs from the split size.
    """
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("samples", type=Path)
    parser.add_argument("--data", required=True)
    parser.add_argument("--split", default="test")
    parser.add_argument("--fid-stats", type=Path)
    parser.add_argument("--framework", choices=["torch", "jax"], default="torch")
    parser.add_argument("--bootstrap", type=int, default=1000)
    parser.add_argument("--batch", type=int, default=100)
    parser.add_argument("--out", type=Path)
    args = parser.parse_args()

    ds = load_dataset(args.data, split=args.split)
    generated = np.load(args.samples)
    if len(generated) != len(ds):
        msg = f"{len(generated)} samples for {len(ds)} examples"
        raise SystemExit(msg)
    backend: Backend = (
        TorchBackend(args.fid_stats)
        if args.framework == "torch"
        else JaxBackend(args.fid_stats)
    )

    scores: dict[str, list[NDArray[Any]]] = {m: [] for m in _METRICS}
    for start in range(0, len(ds), args.batch):
        stop = min(start + args.batch, len(ds))
        targets = np.stack([
            np.asarray(r["optical"]) for r in ds.select(range(start, stop))
        ])
        gen = generated[start:stop]
        for name, value in zip(_METRICS, backend.paired(gen, targets), strict=True):
            scores[name].append(value)
        backend.feed(gen, real=False)
        if args.fid_stats is None:
            backend.feed(targets, real=True)
    per_image = {k: np.concatenate(v) for k, v in scores.items()}

    intervals = cluster_bootstrap(
        per_image, np.asarray(ds["cluster_id"]), args.bootstrap
    )
    result: dict[str, Any] = {"n": len(ds), "fid": backend.fid()}
    for name, values in per_image.items():
        result[name] = {
            "mean": float(values.mean()),
            "std": float(values.std()),
            "ci95_cluster_bootstrap": list(intervals[name]),
        }
    print(json.dumps(result, indent=2))
    if args.out:
        args.out.write_text(json.dumps(result, indent=2), encoding="utf-8")


if __name__ == "__main__":
    main()