File size: 27,359 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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
#!/usr/bin/env python3
"""Source-anchored editing with the exact conditional NF likelihood ratio.

Optimizes the scaled VAE latent using summed densities, gradient descent,
and Armijo backtracking. No NF inverse, CFG, masks, or parameter training.
"""

import argparse
from dataclasses import asdict, dataclass
from io import BytesIO
from itertools import chain, islice
import json
import math
import os
from pathlib import Path
import sys
import time

import torch
from torch.utils.checkpoint import checkpoint


ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
DEFAULT_DATASET = Path('/mnt/bn/jiangzhongtao/lingmin/dataset/PIE_Bench_pp')


@dataclass
class SolverConfig:
    kappa: float = 100.0
    penalty_weight: float = 1.0
    target_gain: float | None = None
    target_penalty_weight: float = 1.0
    target_tol: float = 1e-4
    max_step_rms: float = 0.0
    max_steps: int = 50
    step_size: float = 1e-3
    backtrack_factor: float = 0.5
    armijo: float = 1e-4
    max_backtracks: int = 20
    min_step_size: float = 1e-12
    loss_tol: float = 1e-6
    grad_tol: float = 1e-5
    ratio_tol: float = 1e-4
    gradient_checkpointing: bool = True


def conditional_density(model, latent, condition, gradient_checkpointing=False):
    def forward_density(u, c):
        z, _, _, logdets = model(u, c)
        flat_z = z.flatten(1).double()
        prior_nll = 0.5 * flat_z.square().sum(1)
        prior_nll = prior_nll + 0.5 * flat_z.shape[1] * math.log(2 * math.pi)
        log_abs_det = torch.zeros_like(prior_nll)
        for logdet in logdets:
            log_abs_det = log_abs_det + logdet.flatten(1).double().sum(1)
        return torch.stack((log_abs_det - prior_nll, prior_nll, log_abs_det), dim=1)

    if gradient_checkpointing and torch.is_grad_enabled() and latent.requires_grad:
        # Checkpoint the density call while retaining eval mode and input gradients.
        return checkpoint(forward_density, latent, condition, use_reentrant=False)
    return forward_density(latent, condition)


@torch.enable_grad()
def density_gradients(model, latent, source_condition, target_condition, gradient_checkpointing):
    gradients = []
    # Release each condition's graph before building the next one.
    for condition in (source_condition, target_condition):
        u = latent.detach().requires_grad_(True)
        density = conditional_density(model, u, condition, gradient_checkpointing)
        condition_gradient, = torch.autograd.grad(density[:, 0].sum(), u)
        gradients.append(condition_gradient.detach())
    return gradients


@torch.no_grad()
def optimize_latent(model, source_latent, source_condition, target_condition, config,
                    same_condition=False, verbose=True):
    if source_latent.shape[0] != 1:
        raise ValueError('Optimize one image at a time so line search and selection are per image')
    source = source_latent.detach().float().clone()
    current = source.clone()
    nf_forward_calls = 0
    target_enabled = config.target_gain is not None
    initial_target = initial_source = None
    rejections = {'armijo': 0, 'target_floor': 0, 'step_limit': 0}

    def evaluate(u, initial_ratio, threshold, step):
        nonlocal nf_forward_calls
        if not torch.isfinite(u).all():
            return None
        source_scores = conditional_density(model, u, source_condition)[0]
        target_scores = conditional_density(model, u, target_condition)[0]
        nf_forward_calls += 2
        cost = 0.5 * (u.double() - source.double()).square().sum().item()
        values = torch.cat((source_scores, target_scores))
        if not torch.isfinite(values).all() or not math.isfinite(cost):
            return None
        ell_s, prior_s, logdet_s, ell_t, prior_t, logdet_t = values.tolist()
        ratio = ell_t - ell_s
        gap = max(0.0, threshold - ratio) if threshold is not None else config.kappa
        target_delta = ell_t - initial_target if initial_target is not None else 0.0
        target_gap = max(0.0, config.target_gain - target_delta) if target_enabled else 0.0
        loss = cost + 0.5 * config.penalty_weight * gap ** 2
        loss += 0.5 * config.target_penalty_weight * target_gap ** 2
        if not math.isfinite(loss):
            return None
        return {
            'step': step, 'source_log_density': ell_s, 'target_log_density': ell_t,
            'source_prior_nll': prior_s, 'target_prior_nll': prior_t,
            'source_log_abs_det': logdet_s, 'target_log_abs_det': logdet_t,
            'ratio': ratio, 'delta_ratio': ratio - initial_ratio if initial_ratio is not None else 0.0,
            'cost': cost, 'violation': gap, 'loss': loss,
            'ratio_violation': gap, 'target_violation': target_gap,
            'delta_source_log_density': ell_s - initial_source if initial_source is not None else 0.0,
            'delta_target_log_density': target_delta,
            'ratio_feasible': gap <= config.ratio_tol,
            'target_feasible': target_gap <= config.target_tol,
            'target_floor_satisfied': not target_enabled or target_delta >= -config.target_tol,
            'feasible': gap <= config.ratio_tol and target_gap <= config.target_tol,
        }

    initial = evaluate(current, None, None, 0)
    if initial is None:
        raise FloatingPointError('Non-finite source density: no valid initial candidate')
    initial_ratio = initial['ratio']
    initial_target = initial['target_log_density']
    initial_source = initial['source_log_density']
    threshold = initial_ratio + config.kappa
    state = initial.copy()
    trajectory = [state]
    best_loss = (current.clone(), state.copy())
    best_feasible = (current.clone(), state.copy()) if state['feasible'] else None
    stop_reason = 'max_steps'
    if same_condition:
        stop_reason = 'same_condition_infeasible' if config.kappa > 0 else 'same_condition_no_edit'
    elif config.kappa == 0 and (not target_enabled or config.target_gain == 0):
        stop_reason = 'zero_kappa'
    else:
        for _ in range(config.max_steps):
            gs, gt = density_gradients(model, current, source_condition, target_condition,
                                       config.gradient_checkpointing)
            nf_forward_calls += 2
            # All terms use sums and the original source anchor throughout.
            gradient = (current - source) - config.penalty_weight * state['violation'] * (gt - gs)
            if target_enabled:
                gradient -= config.target_penalty_weight * state['target_violation'] * gt
            if not torch.isfinite(gradient).all():
                stop_reason = 'nonfinite_gradient'
                break
            norm_sq = gradient.double().square().sum().item()
            state['gradient_norm'] = math.sqrt(norm_sq)
            state['target_directional_derivative'] = -(gradient.double() * gt.double()).sum().item()
            state['ratio_directional_derivative'] = -(gradient.double() * (gt - gs).double()).sum().item()
            if state['gradient_norm'] <= config.grad_tol:
                stop_reason = 'gradient_tolerance'
                break

            eta = config.step_size
            if config.max_step_rms:
                eta = min(eta, config.max_step_rms * math.sqrt(source.numel() / norm_sq))
            step_limited = eta < config.step_size
            accepted = False
            step_rejections = {'armijo': 0, 'target_floor': 0, 'step_limit': 0}
            trials = 0
            for backtracks in range(config.max_backtracks + 1):
                if eta < config.min_step_size:
                    break
                trial = current - eta * gradient
                step_rms = (trial.double() - current.double()).square().mean().sqrt().item()
                if config.max_step_rms and step_rms > config.max_step_rms * (1 + 1e-6):
                    rejections['step_limit'] += 1
                    step_rejections['step_limit'] += 1
                    eta *= config.backtrack_factor
                    continue
                candidate = evaluate(trial, initial_ratio, threshold, state['step'] + 1)
                trials += 1
                if candidate is None:
                    stop_reason = 'nonfinite_trial'
                    break
                armijo_ok = (candidate['loss'] < state['loss'] and
                             candidate['loss'] <= state['loss'] - config.armijo * eta * norm_sq)
                floor_ok = candidate['target_floor_satisfied']
                if armijo_ok and floor_ok:
                    accepted = True
                    break
                if not armijo_ok:
                    rejections['armijo'] += 1
                    step_rejections['armijo'] += 1
                if not floor_ok:
                    rejections['target_floor'] += 1
                    step_rejections['target_floor'] += 1
                eta *= config.backtrack_factor
            if not accepted:
                if stop_reason != 'nonfinite_trial':
                    stop_reason = ('target_floor_blocked' if trials and step_rejections['target_floor'] == trials
                                   else 'line_search_failed')
                break

            loss_change = state['loss'] - candidate['loss']
            current = trial.detach()
            state = candidate
            state.update(step_size=eta, backtracks=backtracks, loss_decrease=loss_change,
                         step_rms=step_rms, step_limited=step_limited, line_search_rejections=step_rejections)
            trajectory.append(state)
            if state['loss'] < best_loss[1]['loss']:
                best_loss = (current.clone(), state.copy())
            if state['feasible'] and (best_feasible is None or state['cost'] < best_feasible[1]['cost']):
                best_feasible = (current.clone(), state.copy())
            if verbose:
                print(f"  step={state['step']} L={state['loss']:.6g} "
                      f"delta_R={state['delta_ratio']:.6g} C={state['cost']:.6g} "
                      f"gap={state['violation']:.6g} eta={eta:.3g} "
                      f"target_gain={state['delta_target_log_density']:.6g} "
                      f"target_gap={state['target_violation']:.6g} "
                      f"step_rms={step_rms:.3g} backtracks={backtracks}", flush=True)
            if loss_change <= config.loss_tol:
                stop_reason = 'loss_tolerance'
                break

    selected_latent, final = best_feasible if best_feasible is not None else best_loss
    final = final.copy()
    final['delta_source_log_density'] = final['source_log_density'] - initial['source_log_density']
    final['delta_target_log_density'] = final['target_log_density'] - initial['target_log_density']
    result = {
        'initial': initial, 'final': final, 'threshold': threshold,
        'target_constraint_enabled': target_enabled,
        'target_threshold': initial_target + config.target_gain if target_enabled else None,
        'latent_dim': source.numel(), 'stop_reason': stop_reason,
        'selection': 'nearest_feasible' if best_feasible is not None else 'lowest_loss_infeasible',
        'constraint_satisfied': final['feasible'],
        'ratio_constraint_satisfied': final['ratio_feasible'],
        'target_constraint_satisfied': final['target_feasible'] if target_enabled else None,
        'strict_constraint_satisfied': (final['ratio'] >= threshold and
                                        (not target_enabled or final['delta_target_log_density'] >= config.target_gain)),
        'selected_step': final['step'], 'accepted_steps': trajectory[-1]['step'],
        'nf_forward_calls': nf_forward_calls,
        'line_search_rejections': rejections,
        'forward_calls_exclude_checkpoint_recomputation': True,
    }
    return selected_latent.detach(), result, trajectory


def parse_args():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--image-path', type=Path, help='Single image; omit to use PIE-Bench++')
    parser.add_argument('--source-prompt')
    parser.add_argument('--target-prompt')
    parser.add_argument('--dataset', type=Path, default=DEFAULT_DATASET)
    parser.add_argument('--category', action='append', help='Repeatable PIE category filter')
    parser.add_argument('--image-id', type=int, action='append', help='Repeatable PIE image ID filter')
    parser.add_argument('--start-index', type=int, default=0)
    parser.add_argument('--max-samples', '--max-sample', type=int, default=0, help='0: all selected images')
    parser.add_argument('--output-dir', type=Path, default=ROOT / 'result/nf_likelihood_ratio',
                        help='Must not already exist')
    parser.add_argument('--model-config-path', default=str(ROOT / 'configs/starflow_3B_t2i_256x256.yaml'))
    parser.add_argument('--checkpoint-path', default=str(ROOT / 'ckpts/starflow_3B_t2i_256x256.pth'))
    parser.add_argument('--seed', type=int, default=999)
    parser.add_argument('--vae-latent', choices=('mean', 'sample'), default='mean')
    parser.add_argument('--input-noise-std', type=float, default=0.0)
    parser.add_argument('--kappa', type=float, default=SolverConfig.kappa, help='Evidence growth in summed nats')
    parser.add_argument('--penalty-weight', type=float, default=SolverConfig.penalty_weight, help='lambda')
    parser.add_argument('--target-gain', type=float, default=None,
                        help='Minimum target log-density gain in summed nats; omit to disable, 0 enables a floor')
    parser.add_argument('--target-penalty-weight', type=float, default=SolverConfig.target_penalty_weight)
    parser.add_argument('--target-tol', type=float, default=SolverConfig.target_tol,
                        help='Target feasibility and initialization density-floor tolerance, in nats')
    parser.add_argument('--max-step-rms', type=float, default=SolverConfig.max_step_rms,
                        help='Maximum RMS latent displacement per update; 0 disables the limit')
    parser.add_argument('--max-steps', type=int, default=SolverConfig.max_steps)
    parser.add_argument('--step-size', type=float, default=SolverConfig.step_size)
    parser.add_argument('--backtrack-factor', type=float, default=SolverConfig.backtrack_factor)
    parser.add_argument('--armijo', type=float, default=SolverConfig.armijo)
    parser.add_argument('--max-backtracks', type=int, default=SolverConfig.max_backtracks,
                        help='Maximum shrink operations per update (trials = this + 1)')
    parser.add_argument('--min-step-size', type=float, default=SolverConfig.min_step_size)
    parser.add_argument('--loss-tol', type=float, default=SolverConfig.loss_tol, help='Absolute loss change')
    parser.add_argument('--grad-tol', type=float, default=SolverConfig.grad_tol)
    parser.add_argument('--ratio-tol', type=float, default=SolverConfig.ratio_tol, help='Feasibility tolerance in nats')
    parser.add_argument('--no-gradient-checkpointing', dest='gradient_checkpointing', action='store_false')
    cli = parser.parse_args()
    cli.precision = 'fp32'
    if cli.image_path is not None:
        if not cli.image_path.is_file():
            parser.error('--image-path must be an existing file')
        if not cli.source_prompt or not cli.source_prompt.strip() or not cli.target_prompt or not cli.target_prompt.strip():
            parser.error('Single-image mode requires nonempty --source-prompt and --target-prompt')
        if cli.category or cli.image_id or cli.start_index or cli.max_samples:
            parser.error('PIE selection options cannot be used with --image-path')
    elif cli.source_prompt is not None or cli.target_prompt is not None:
        parser.error('Prompt overrides require --image-path; PIE mode uses dataset prompts')
    positive = ('penalty_weight', 'target_penalty_weight', 'step_size', 'min_step_size')
    nonnegative = ('kappa', 'input_noise_std', 'loss_tol', 'grad_tol', 'ratio_tol', 'target_tol', 'max_step_rms')
    for name in positive + nonnegative + ('backtrack_factor', 'armijo'):
        if not math.isfinite(getattr(cli, name)):
            parser.error(f'--{name.replace("_", "-")} must be finite')
    if any(getattr(cli, name) <= 0 for name in positive):
        parser.error('Penalty weights, step-size and min-step-size must be positive')
    if any(getattr(cli, name) < 0 for name in nonnegative):
        parser.error('kappa, input-noise-std, max-step-rms and tolerances must be nonnegative')
    if cli.target_gain is not None and (not math.isfinite(cli.target_gain) or cli.target_gain < 0):
        parser.error('target-gain must be finite and nonnegative')
    if not 0 < cli.backtrack_factor < 1 or not 0 < cli.armijo < 1:
        parser.error('backtrack-factor and armijo must be strictly between 0 and 1')
    if cli.min_step_size > cli.step_size:
        parser.error('min-step-size must not exceed step-size')
    if min(cli.max_steps, cli.max_backtracks, cli.start_index, cli.max_samples) < 0:
        parser.error('Step/sample counts and start-index must be nonnegative')
    if cli.image_id and min(cli.image_id) < 0:
        parser.error('image-id must be nonnegative')
    if int(os.environ.get('WORLD_SIZE', '1')) != 1:
        parser.error('Use one process/GPU')
    for name in ('image_path', 'dataset', 'output_dir', 'model_config_path', 'checkpoint_path'):
        value = getattr(cli, name)
        if value is not None:
            setattr(cli, name, Path(value).resolve())
    return cli


def iter_inputs(cli):
    if cli.image_path is not None:
        yield {'category': 'single', 'id': cli.image_path.stem,
               'image_bytes': cli.image_path.read_bytes(),
               'source_prompt': cli.source_prompt.strip(), 'target_prompt': cli.target_prompt.strip()}
        return

    import pyarrow.parquet as pq

    paths = sorted(cli.dataset.glob('*/*.parquet'))
    categories = {path.parent.name for path in paths}
    if cli.category:
        unknown = set(cli.category) - categories
        if unknown:
            raise ValueError(f'Unknown categories: {sorted(unknown)}; available: {sorted(categories)}')
        paths = [path for path in paths if path.parent.name in cli.category]
    if not paths:
        raise FileNotFoundError(f'No PIE-Bench++ Parquet files under {cli.dataset}')
    index = 0
    requested = set(cli.image_id or [])
    found = set()
    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():
                index += 1
                if index <= cli.start_index or (requested and int(row['id']) not in requested):
                    continue
                found.add(int(row['id']))
                yield {'category': path.parent.name, 'id': str(row['id']),
                       'image_bytes': row['image']['bytes'],
                       'source_prompt': row['source_prompt'].strip(),
                       'target_prompt': row['target_prompt'].replace('[', '').replace(']', '').strip()}
    if requested - found:
        raise ValueError(f'IDs missing after category/start-index filters: {sorted(requested - found)}')


def preprocess_image(image_bytes, image_size):
    from PIL import Image, ImageOps
    import torchvision.transforms as transforms

    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):
    from PIL import Image

    if not torch.isfinite(tensor).all():
        raise FloatingPointError(f'Non-finite decoded image: {path}')
    path.parent.mkdir(parents=True, exist_ok=True)
    pixels = ((tensor[0].detach().float().cpu().clamp(-1, 1) + 1) * 127.5)
    Image.fromarray(pixels.round().byte().permute(1, 2, 0).numpy()).save(path)


def main():
    cli = parse_args()
    if cli.output_dir.exists():
        raise FileExistsError(f'Choose a new --output-dir: {cli.output_dir}')
    inputs = iter_inputs(cli)
    if cli.image_id:
        inputs = iter(list(inputs))
    if cli.max_samples:
        inputs = islice(inputs, cli.max_samples)
    first = next(inputs, None)
    if first is None:
        raise ValueError('No images selected')
    if not torch.cuda.is_available():
        raise RuntimeError('STARFlow 3B editing requires a CUDA GPU')

    from pie_bench_nf_components import load_components
    from utils import encode_text

    os.chdir(ROOT)
    args, model, vae, tokenizer, text_encoder, dist, device = load_components(cli)
    for component in (model, vae, text_encoder):
        component.eval().requires_grad_(False)
    config = SolverConfig(**{key: getattr(cli, key) for key in SolverConfig.__dataclass_fields__})
    cli.output_dir.mkdir(parents=True, exist_ok=False)
    run_config = {key: str(value) if isinstance(value, Path) else value for key, value in vars(cli).items()}
    run_config.update(solver=asdict(config), nf_precision='fp32', density_reduction='sum',
                      density_accumulation='fp64', guidance=0, torch_version=torch.__version__,
                      gpu=torch.cuda.get_device_name(device),
                      density_space='scaled VAE latent before decoding',
                      preprocessing='resize shortest side then center crop to model image size')
    (cli.output_dir / 'run_config.json').write_text(json.dumps(run_config, indent=2, ensure_ascii=False) + '\n')
    previous_tf32 = (torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32)
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False
    reports = []
    try:
        for item in chain([first], inputs):
            started = time.perf_counter()
            category, image_id = item['category'], item['id']
            if not item['source_prompt'] or not item['target_prompt']:
                raise ValueError(f'Missing prompt: {category}/{image_id}')
            print(f'Processing {category}/{image_id}', flush=True)
            image_size = args.img_size * vae.downsample_factor
            image = preprocess_image(item['image_bytes'], image_size).to(device)
            item_seed = cli.seed + sum(ord(c) for c in category) + (
                int(image_id) if image_id.isdigit() else sum(ord(c) for c in image_id))
            generator = torch.Generator(device=device).manual_seed(item_seed)
            with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16):
                posterior = vae.vae.encode(image).latent_dist
                encoded = posterior.sample(generator=generator) if cli.vae_latent == 'sample' else posterior.mode()
                encoded = encoded * vae.scaling_factor
                conditions = encode_text(text_encoder, tokenizer,
                                         [item['source_prompt'], item['target_prompt']], args.txt_size, device).float()
                vae_only = vae.decode(encoded)
            source_latent = encoded.detach().float()
            if cli.input_noise_std:
                source_latent = source_latent + cli.input_noise_std * torch.randn(
                    source_latent.shape, generator=generator, device=device, dtype=torch.float32)
            same_condition = (item['source_prompt'] == item['target_prompt'] or
                              torch.equal(conditions[:1], conditions[1:]))
            with torch.autocast('cuda', enabled=False):
                edited_latent, result, trajectory = optimize_latent(
                    model, source_latent, conditions[:1], conditions[1:], config, same_condition)
            with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16):
                edited = image if same_condition else vae.decode(edited_latent)
            stem = Path(category) / image_id
            for kind, pixels in (('source', image), ('vae_only', vae_only), ('editing', edited)):
                save_image(pixels, cli.output_dir / kind / stem.with_name(stem.name + '.png'))
            for folder in ('metadata', 'trajectory', 'latents'):
                (cli.output_dir / folder / stem.parent).mkdir(parents=True, exist_ok=True)
            result.update(category=category, id=image_id, source_prompt=item['source_prompt'],
                          target_prompt=item['target_prompt'], item_seed=item_seed,
                          identity_bypass=same_condition, elapsed_seconds=time.perf_counter() - started)
            (cli.output_dir / 'metadata' / stem.with_name(stem.name + '.json')).write_text(
                json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False) + '\n')
            with (cli.output_dir / 'trajectory' / stem.with_name(stem.name + '.jsonl')).open('x') as handle:
                for state in trajectory:
                    handle.write(json.dumps(state, allow_nan=False) + '\n')
            torch.save({'source_latent': source_latent.cpu(), 'edited_latent': edited_latent.cpu()},
                       cli.output_dir / 'latents' / stem.with_name(stem.name + '.pt'))
            reports.append({'category': category, 'id': image_id, **result['final'],
                            'stop_reason': result['stop_reason']})
            print(f"  selected step={result['selected_step']} feasible={result['constraint_satisfied']} "
                  f"stop={result['stop_reason']}", flush=True)
    finally:
        torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = previous_tf32
        if dist.distributed:
            torch.distributed.destroy_process_group()
    summary = {'count': len(reports), 'feasible_count': sum(report['feasible'] for report in reports),
               'target_constraint_enabled': config.target_gain is not None,
               'ratio_feasible_count': sum(report['ratio_feasible'] for report in reports),
               'target_feasible_count': (sum(report['target_feasible'] for report in reports)
                                         if config.target_gain is not None else None),
               'mean_delta_ratio': sum(report['delta_ratio'] for report in reports) / len(reports),
               'mean_violation': sum(report['violation'] for report in reports) / len(reports),
               'mean_target_violation': sum(report['target_violation'] for report in reports) / len(reports),
               'mean_delta_target_log_density': sum(report['delta_target_log_density'] for report in reports) / len(reports),
               'mean_delta_source_log_density': sum(report['delta_source_log_density'] for report in reports) / len(reports),
               'mean_cost': sum(report['cost'] for report in reports) / len(reports), 'images': reports}
    (cli.output_dir / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False, allow_nan=False) + '\n')
    print(f"Finished {len(reports)} images; feasible={summary['feasible_count']}/{len(reports)}; "
          f"output={cli.output_dir}", flush=True)


if __name__ == '__main__':
    main()