File size: 24,464 Bytes
2cf4a54
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
#!/usr/bin/env python3
"""PIE-Bench++ source-caption inversion, reconstruction, and direct prompt edit.

Run with scripts/run_pie_bench_nf_baseline.sh so the same cached models and
checkpoint used by scripts/sample_image.sh are available offline.
"""

import argparse
from contextlib import nullcontext
import os
import sys
import json
import math
from io import BytesIO
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parents[1]))

import pyarrow.parquet as pq
import torch
import torchvision.transforms as transforms
from PIL import Image, ImageOps

from utils import encode_text, process_denoising
from pie_bench_nf_components import load_components


DEFAULT_DATASET = Path('/mnt/bn/jiangzhongtao/lingmin/dataset/PIE_Bench_pp')


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--dataset', type=Path, default=DEFAULT_DATASET)
    parser.add_argument('--output-dir', type=Path, default=Path('result/baseline'))
    parser.add_argument('--model-config-path', default='configs/starflow_3B_t2i_256x256.yaml')
    parser.add_argument('--checkpoint-path', default='ckpts/starflow_3B_t2i_256x256.pth')
    parser.add_argument('--category', action='append', help='Category directory name; repeat to select several (default: all)')
    parser.add_argument('--precision', choices=('fp32', 'bf16'), default='fp32',
                        help='NF precision; fp32 matches the successful reconstruction experiment')
    parser.add_argument('--image-id', type=int, action='append', help='Actual dataset ID; repeatable')
    parser.add_argument('--batch-size', type=int, default=1,
                        help='Images per model call (default: 1); reconstruction/editing CFG doubles the batch internally')
    parser.add_argument('--max-samples', type=int, default=0, help='Maximum images, 0 for the complete dataset')
    parser.add_argument('--start-index', type=int, default=0, help='Skip this many dataset rows before processing')
    parser.add_argument('--seed', type=int, default=999)
    parser.add_argument('--vae-latent', choices=('mean', 'sample'), default='mean',
                        help='VAE posterior mean is deterministic; sample matches training')
    noise = parser.add_mutually_exclusive_group()
    noise.add_argument('--input-noise-std', type=float, default=0.0,
                       help='Gaussian noise added to VAE latent before inversion; training used 0.3')
    noise.add_argument('--training-noise', action='store_true',
                       help='Add latent noise at the model-config noise_std and apply official '
                            'one-step self-denoising before reconstruction/editing VAE decode')
    noise.add_argument('--training-noise-subtract', action='store_true',
                       help='Add latent noise at the model-config noise_std and subtract the same '
                            'noise before reconstruction/editing VAE decode, without self-denoising')
    parser.add_argument('--reconstruct-cfg', type=float, default=0.0,
                        help='Guidance for both source-caption forward and reverse (default: 0, disabled)')
    parser.add_argument('--reconstruct-encoder', choices=('parallel', 'closed-loop'), default='parallel',
                        help='Closed-loop uses sequential decoder feedback and FP64 deep-block affine arithmetic (FP32 model only)')
    parser.add_argument('--edit-cfg', type=float, default=3.6,
                        help='Guidance for target-caption reverse (default: 3.6); 0 disables CFG')
    parser.add_argument('--diagnose-cfg', action='store_true',
                        help='Record deep-block reconstruction diagnostics; closed-loop compares independent decoding with encoder feedback (FP32 only)')
    parser.add_argument('--save-z', action='store_true',
                        help='Save editing source z; closed-loop also saves FP64 reconstruction z separately')
    parser.add_argument('--overwrite', action='store_true')
    return parser.parse_args()


def iter_examples(dataset, categories):
    paths = sorted(dataset.glob('*/*.parquet'))
    if categories:
        names = {p.parent.name for p in paths}
        unknown = set(categories) - names
        if unknown:
            raise ValueError(f'Unknown categories: {sorted(unknown)}; available: {sorted(names)}')
        paths = [p for p in paths if p.parent.name in categories]
    if not paths:
        raise FileNotFoundError(f'No PIE-Bench++ Parquet files found under {dataset}')
    for path in paths:
        parquet = pq.ParquetFile(path)
        for batch in parquet.iter_batches(batch_size=64, columns=['image', 'id', 'source_prompt', 'target_prompt']):
            for row in batch.to_pylist():
                yield path.parent.name, row


def target_caption(marked_prompt):
    # PIE-Bench++ uses brackets to mark inserted or replaced words.
    return marked_prompt.replace('[', '').replace(']', '')


def preprocess_image(image_bytes, image_size):
    with Image.open(BytesIO(image_bytes)) as raw:
        image = ImageOps.exif_transpose(raw).convert('RGB')
    scale = max(image_size / image.height, image_size / image.width)
    transform = transforms.Compose([
        transforms.Resize((int(image.height * scale), int(image.width * scale))),
        transforms.CenterCrop((image_size, image_size)),
        transforms.ToTensor(),
        transforms.Normalize([0.5] * 3, [0.5] * 3),
    ])
    return transform(image).unsqueeze(0)


def save_image(tensor, path):
    path.parent.mkdir(parents=True, exist_ok=True)
    image = ((tensor[0].detach().float().cpu().clamp(-1, 1) + 1) * 127.5)
    image = image.round().byte().permute(1, 2, 0).numpy()
    Image.fromarray(image).save(path)


def pixel_metrics(prediction, reference):
    mse = (prediction.float().clamp(-1, 1) - reference.float()).square().mean().item() / 4
    return {'mse': mse, 'psnr_db': -10 * math.log10(mse) if mse > 0 else None}


def encode_vae(vae, images, mode, generators):
    posterior = vae.vae.encode(images).latent_dist
    # Per-image generators keep VAE samples unchanged when the batch size changes.
    latent = posterior.sample(generator=generators) if mode == 'sample' else posterior.mode()
    return latent * vae.scaling_factor


def batch_noise(latents, generators):
    shape = (1, *latents.shape[1:])
    return torch.cat([
        torch.randn(shape, generator=generator, device=latents.device, dtype=latents.dtype)
        for generator in generators
    ])


def output_paths(output_dir, category, image_id):
    if not image_id.isdigit():
        raise ValueError(f'Unexpected PIE-Bench++ image id: {image_id!r}')
    stem = Path(category) / image_id
    return {
        'source': output_dir / 'source' / stem.with_suffix('.png'),
        'vae_only': output_dir / 'vae_only' / stem.with_suffix('.png'),
        'reconstruct': output_dir / 'reconstruct' / stem.with_suffix('.png'),
        'editing': output_dir / 'editing' / stem.with_suffix('.png'),
        'metadata': output_dir / 'metadata' / stem.with_suffix('.json'),
        'z': output_dir / 'z' / stem.with_suffix('.pt'),
        'z_reconstruct': output_dir / 'z_reconstruct' / stem.with_suffix('.pt'),
    }


def iter_pending_batches(examples, output_dir, batch_size, max_samples, save_z, overwrite,
                         precision=None, reconstruction_forward_cfg=None, diagnose_cfg=False,
                         input_noise_std=None, self_denoising_steps=None, subtract_input_noise=None,
                         reconstruction_encoder=None):
    batch = []
    scheduled = 0
    required = ('source', 'vae_only', 'reconstruct', 'editing', 'metadata')
    if save_z:
        required += ('z',)
        if reconstruction_encoder == 'closed-loop':
            required += ('z_reconstruct',)
    for category, row in examples:
        if max_samples and scheduled >= max_samples:
            break
        paths = output_paths(output_dir, category, row['id'])
        metadata = None
        if not overwrite and paths['metadata'].exists():
            metadata = json.loads(paths['metadata'].read_text())
            previous_encoder = metadata.get('encoder', 'parallel')
            if reconstruction_encoder is not None and previous_encoder != reconstruction_encoder:
                raise ValueError(f"{paths['metadata']} uses reconstruction encoder={previous_encoder}; "
                                 "choose a new --output-dir or pass --overwrite to replace previous results")
        if not overwrite and all(paths[name].exists() for name in required):
            previous_precision = metadata.get('precision', 'bf16')
            if precision is not None and previous_precision != precision:
                raise ValueError(f"{paths['metadata']} uses {previous_precision}; choose a new "
                                 "--output-dir or pass --overwrite to replace previous results")
            previous_forward_cfg = metadata.get('reconstruction_forward_cfg', 0.0)
            if reconstruction_forward_cfg is not None and previous_forward_cfg != reconstruction_forward_cfg:
                raise ValueError(f"{paths['metadata']} uses reconstruction forward CFG={previous_forward_cfg}; "
                                 "choose a new --output-dir or pass --overwrite to replace previous results")
            for name, value in (('input_noise_std', input_noise_std),
                                ('self_denoising_steps', self_denoising_steps),
                                ('subtract_input_noise', subtract_input_noise)):
                previous = metadata.get(name, 0)
                if value is not None and previous != value:
                    raise ValueError(f"{paths['metadata']} uses {name}={previous}; choose a new "
                                     "--output-dir or pass --overwrite to replace previous results")
            diagnostic_key = ('closed_loop_diagnostics' if reconstruction_encoder == 'closed-loop'
                              else 'cfg_diagnostics')
            if diagnose_cfg and diagnostic_key not in metadata:
                raise ValueError(f"{paths['metadata']} has no CFG diagnostics; choose a new "
                                 "--output-dir or pass --overwrite to replace previous results")
            print(f'Skip existing: {category}/{row["id"]}', flush=True)
            continue
        batch.append((category, row, paths))
        scheduled += 1
        if len(batch) == batch_size:
            yield batch
            batch = []
    if batch:
        yield batch


def main():
    cli = parse_args()
    if (cli.batch_size < 1 or cli.max_samples < 0 or cli.start_index < 0
            or cli.input_noise_std < 0 or cli.reconstruct_cfg < 0 or cli.edit_cfg < 0):
        raise ValueError('batch-size must be positive; max-samples, start-index, input-noise-std, '
                         'reconstruct-cfg, and edit-cfg must be nonnegative')
    if cli.diagnose_cfg and cli.precision != 'fp32':
        raise ValueError('--diagnose-cfg requires --precision fp32')
    if cli.reconstruct_encoder == 'closed-loop' and cli.precision != 'fp32':
        raise ValueError('--reconstruct-encoder closed-loop requires --precision fp32')
    if not torch.cuda.is_available():
        raise RuntimeError('STARFlow 3B inference requires a CUDA GPU')

    # Check the dataset and selected categories before loading the large model.
    examples = iter_examples(cli.dataset, cli.category)
    first = next(examples, None)
    if first is None:
        raise FileNotFoundError(f'No examples found in {cli.dataset}')
    from itertools import chain, islice
    selected = islice(chain([first], examples), cli.start_index, None)

    if int(os.environ.get('WORLD_SIZE', '1')) != 1:
        raise ValueError('Use one GPU/process')
    if cli.image_id:
        requested = set(cli.image_id)
        if min(requested) < 0:
            raise ValueError('image-id must be nonnegative')
        selected = [(category, row) for category, row in selected if int(row['id']) in requested]
        missing = requested - {int(row['id']) for _, row in selected}
        if missing:
            raise ValueError(f'IDs not found after category/start-index filters: {sorted(missing)}')

    args, model, vae, tokenizer, text_encoder, dist, device = load_components(cli)
    if cli.training_noise or cli.training_noise_subtract:
        if args.noise_type != 'gaussian':
            raise ValueError('Training-noise modes require a Gaussian-noise model configuration')
        cli.input_noise_std = args.noise_std
    image_size = args.img_size * vae.downsample_factor
    completed = 0

    with torch.no_grad():
        batches = iter_pending_batches(selected, cli.output_dir, cli.batch_size,
                                       cli.max_samples, cli.save_z, cli.overwrite, cli.precision,
                                       reconstruction_forward_cfg=cli.reconstruct_cfg,
                                       diagnose_cfg=cli.diagnose_cfg,
                                       input_noise_std=cli.input_noise_std,
                                       self_denoising_steps=int(cli.training_noise),
                                       subtract_input_noise=cli.training_noise_subtract,
                                       reconstruction_encoder=cli.reconstruct_encoder)
        for batch in batches:
            print(f'Processing batch of {len(batch)} images, starting at '
                  f'{batch[0][0]}/{batch[0][1]["id"]}', flush=True)
            source_captions = [row['source_prompt'] for _, row, _ in batch]
            edited_captions = [target_caption(row['target_prompt']) for _, row, _ in batch]
            if any(not caption for caption in source_captions + edited_captions):
                raise ValueError(f'Missing caption in batch starting at {batch[0][0]}/{batch[0][1]["id"]}')
            images = torch.cat([
                preprocess_image(row['image']['bytes'], image_size) for _, row, _ in batch
            ]).to(device)
            # Separate RNG streams preserve each item's VAE/noise draw across
            # different batch sizes and resumed runs.
            generators = [
                torch.Generator(device=device).manual_seed(
                    cli.seed + int(row['id']) + sum(ord(c) for c in category)
                )
                for category, row, _ in batch
            ]

            with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
                vae_latent = encode_vae(vae, images, cli.vae_latent, generators)
                latent_input = vae_latent
                input_noise = torch.zeros_like(vae_latent)
                if cli.input_noise_std:
                    input_noise = cli.input_noise_std * batch_noise(vae_latent, generators)
                    latent_input = vae_latent + input_noise
                source_prompts = source_captions + [''] * len(batch) if cli.reconstruct_cfg > 0 else source_captions
                reconstruct_y = encode_text(text_encoder, tokenizer, source_prompts, args.txt_size, device)
                source_y = reconstruct_y[:len(batch)]
                editing_prompts = edited_captions + [''] * len(batch) if cli.edit_cfg > 0 else edited_captions
                target_y = encode_text(text_encoder, tokenizer, editing_prompts, args.txt_size, device)
                vae_only = vae.decode(vae_latent)

            amp = torch.autocast('cuda', dtype=torch.bfloat16) if cli.precision == 'bf16' else nullcontext()
            old_matmul = torch.backends.cuda.matmul.allow_tf32
            old_cudnn = torch.backends.cudnn.allow_tf32
            if cli.precision == 'fp32':
                torch.backends.cuda.matmul.allow_tf32 = False
                torch.backends.cudnn.allow_tf32 = False
            try:
                with amp:
                    if cli.reconstruct_encoder == 'closed-loop':
                        from nf_roundtrip import closed_loop_forward, closed_loop_reverse
                        z_reconstruct, forward_states, simulated_top = closed_loop_forward(
                            model, latent_input.float(), reconstruct_y.float(), cli.reconstruct_cfg)
                        reconstruction_output = closed_loop_reverse(
                            model, z_reconstruct, reconstruct_y.float(), cli.reconstruct_cfg,
                            return_sequence=cli.diagnose_cfg)
                    elif cli.reconstruct_cfg > 0:
                        # Pair the same input with source/empty captions; guided z is duplicated.
                        z_reconstruct, _, forward_states, _ = model(torch.cat([latent_input, latent_input]).float(),
                                                                    reconstruct_y.float(), guidance=cli.reconstruct_cfg)
                        z_reconstruct = z_reconstruct[:len(batch)]
                    else:
                        z_reconstruct, _, forward_states, _ = model(latent_input.float(), source_y.float())
                    if cli.reconstruct_encoder == 'parallel':
                        reconstruction_output = model(z_reconstruct, reconstruct_y.float(), reverse=True,
                                                      guidance=cli.reconstruct_cfg, jacobi=False,
                                                      return_sequence=cli.diagnose_cfg)
                    if cli.diagnose_cfg:
                        reconstructed_latent = reconstruction_output[-1]
                        if cli.reconstruct_encoder == 'closed-loop':
                            from nf_roundtrip import error_metrics
                            expected_top = model.unpatchify(forward_states[-2])
                            diagnostics = [{
                                'block_index': len(model.blocks) - 1,
                                'guidance': cli.reconstruct_cfg,
                                'deep_reconstruction_error': error_metrics(reconstruction_output[1][i], expected_top[i]),
                                'decoder_vs_simulated_prefix_error': error_metrics(
                                    reconstruction_output[1][i].float(), simulated_top[i]),
                            } for i in range(len(batch))]
                        else:
                            from nf_roundtrip import cfg_diagnostics
                            diagnostics = cfg_diagnostics(model, forward_states[-2], z_reconstruct,
                                                          reconstruct_y.float(), cli.reconstruct_cfg,
                                                          reconstruction_output[1])
                    else:
                        reconstructed_latent = reconstruction_output
                    z_edit, _, _, _ = model(latent_input.float(), source_y.float())
                    edited_latent = model(z_edit, target_y.float(), reverse=True, guidance=cli.edit_cfg, jacobi=False)
                    reconstructed_decode_latent, edited_decode_latent = reconstructed_latent, edited_latent
                    if cli.training_noise:
                        reconstructed_decode_latent = process_denoising(
                            reconstructed_latent, source_y.float(), args, model, text_encoder,
                            tokenizer, {}, cli.input_noise_std)
                        edited_decode_latent = process_denoising(
                            edited_latent, target_y[:len(batch)].float(), args, model, text_encoder,
                            tokenizer, {}, cli.input_noise_std)
                    elif cli.training_noise_subtract:
                        reconstructed_decode_latent = reconstructed_latent.float() - input_noise.float()
                        edited_decode_latent = edited_latent.float() - input_noise.float()
            finally:
                if cli.training_noise:
                    # Official self_denoise switches the model to train mode.
                    model.eval()
                torch.backends.cuda.matmul.allow_tf32 = old_matmul
                torch.backends.cudnn.allow_tf32 = old_cudnn
            if not all(torch.isfinite(t).all() for t in (z_reconstruct, reconstructed_latent, edited_latent,
                                                        reconstructed_decode_latent, edited_decode_latent)):
                raise FloatingPointError('Non-finite NF output; inspect precision and checkpoint')
            with torch.autocast(device_type='cuda', dtype=torch.bfloat16):
                reconstructed = vae.decode(reconstructed_decode_latent.to(vae_latent.dtype))
                edited = vae.decode(edited_decode_latent.to(vae_latent.dtype))

            for index, (category, row, paths) in enumerate(batch):
                item = slice(index, index + 1)
                save_image(images[item], paths['source'])
                save_image(vae_only[item], paths['vae_only'])
                save_image(reconstructed[item], paths['reconstruct'])
                save_image(edited[item], paths['editing'])
                if cli.save_z:
                    paths['z'].parent.mkdir(parents=True, exist_ok=True)
                    torch.save(z_edit[item].detach().float().cpu(), paths['z'])
                    if cli.reconstruct_encoder == 'closed-loop':
                        paths['z_reconstruct'].parent.mkdir(parents=True, exist_ok=True)
                        torch.save(z_reconstruct[item].detach().cpu(), paths['z_reconstruct'])
                metadata = {
                    'precision': cli.precision,
                    'encoder': cli.reconstruct_encoder,
                    'reconstruction_affine_precision': ('fp64' if cli.reconstruct_encoder == 'closed-loop' else 'fp32'),
                    'reconstruction_z_dtype': str(z_reconstruct.dtype),
                    'reconstruction_batch_ids': [r['id'] for _, r, _ in batch],
                    'attention': 'default',
                    'reconstruction_forward_cfg': cli.reconstruct_cfg,
                    'reconstruction_cfg': cli.reconstruct_cfg,
                    'category': category,
                    'id': row['id'],
                    'source_prompt': source_captions[index],
                    'target_prompt_marked': row['target_prompt'],
                    'target_prompt': edited_captions[index],
                    'vae_latent_mode': cli.vae_latent,
                    'input_noise_std': cli.input_noise_std,
                    'self_denoising_steps': int(cli.training_noise),
                    'subtract_input_noise': cli.training_noise_subtract,
                    'edit_cfg': cli.edit_cfg,
                    'source_image_size': image_size,
                    'roundtrip_latent_mae': (reconstructed_latent[item].float() - latent_input[item].float()).abs().mean().item(),
                    'repeat_z_max_abs': ((z_reconstruct[item].float() - z_edit[item].float()).abs().max().item()
                                         if cli.reconstruct_cfg == 0 else None),
                    'vae_only_vs_source': pixel_metrics(vae_only[item], images[item]),
                    'reconstruct_vs_vae': pixel_metrics(reconstructed[item], vae_only[item].float().clamp(-1, 1)),
                    'reconstruct_vs_source': pixel_metrics(reconstructed[item], images[item]),
                    'files': {name: str(path) for name, path in paths.items()
                              if name != 'metadata' and (name not in ('z', 'z_reconstruct') or cli.save_z)
                              and (name != 'z_reconstruct' or cli.reconstruct_encoder == 'closed-loop')},
                }
                if cli.diagnose_cfg:
                    key = 'closed_loop_diagnostics' if cli.reconstruct_encoder == 'closed-loop' else 'cfg_diagnostics'
                    metadata[key] = diagnostics[index]
                paths['metadata'].parent.mkdir(parents=True, exist_ok=True)
                paths['metadata'].write_text(json.dumps(metadata, indent=2, ensure_ascii=False) + '\n')
                completed += 1
                print(f'{category}/{row["id"]}: reconstruction PSNR={metadata["reconstruct_vs_source"]["psnr_db"]} dB, '
                      f'latent MAE={metadata["roundtrip_latent_mae"]:.6g}', flush=True)
    if dist.distributed and torch.distributed.is_initialized():
        torch.distributed.destroy_process_group()
        dist.distributed = False
    print(f'Processed {completed} examples; results under {cli.output_dir}', flush=True)


if __name__ == '__main__':
    main()