File size: 11,015 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
#!/usr/bin/env python3
"""PIE-Bench++ NF reconstruction: original BF16 versus true FP32 inversion.

See the NF reconstruction precision experiments section of README.md.
"""

import argparse
from contextlib import nullcontext
import json
import os
from pathlib import Path
import sys
import time

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

import torch
from torch.nn.attention import SDPBackend, sdpa_kernel

from utils import encode_text
from pie_bench_nf_components import load_components
from pie_bench_nf_baseline import (DEFAULT_DATASET, encode_vae, iter_examples,
                                   pixel_metrics, preprocess_image, save_image,
                                   target_caption)
from nf_roundtrip import block_diagnostics, error_metrics, sequential_forward


def parse_args():
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument('--dataset', type=Path, default=DEFAULT_DATASET)
    p.add_argument('--output-dir', type=Path, default=None)
    p.add_argument('--baseline-dir', type=Path, default=Path('result/baseline'))
    p.add_argument('--model-config-path', default='configs/starflow_3B_t2i_256x256.yaml')
    p.add_argument('--checkpoint-path', default='ckpts/starflow_3B_t2i_256x256.pth')
    p.add_argument('--precision', choices=['fp32', 'bf16'], default='fp32')
    p.add_argument('--encoder', choices=['parallel', 'sequential'], default='parallel')
    p.add_argument('--attention', choices=['default', 'math'], default='default')
    p.add_argument('--category', action='append')
    p.add_argument('--image-id', type=int, action='append', help='Actual dataset ID, e.g. 48; repeatable')
    p.add_argument('--max-samples', type=int, default=1, help='Default 1; 0 means all selected images')
    p.add_argument('--start-index', type=int, default=0)
    p.add_argument('--batch-size', type=int, default=1)
    p.add_argument('--seed', type=int, default=999)
    p.add_argument('--edit', action='store_true', help='Also decode the same z with the target caption')
    p.add_argument('--edit-cfg', type=float, default=3.6)
    p.add_argument('--save-z', action='store_true')
    p.add_argument('--overwrite', action='store_true')
    cli = p.parse_args()
    if cli.batch_size < 1 or min(cli.max_samples, cli.start_index, cli.edit_cfg) < 0:
        p.error('batch-size must be positive; sample limits, start-index and edit-cfg must be nonnegative')
    if cli.encoder == 'sequential' and cli.precision != 'fp32':
        p.error('sequential encoding is supported only for the unwrapped FP32 model')
    if int(os.environ.get('WORLD_SIZE', '1')) != 1:
        p.error('Use one process/GPU')
    if cli.output_dir is None:
        cli.output_dir = Path(f'result/nf_{cli.precision}_{cli.encoder}_{cli.attention}')
    if cli.image_id and any(i < 0 for i in cli.image_id):
        p.error('image-id must be nonnegative')
    return cli




def main():
    cli = parse_args()
    from itertools import islice
    examples = islice(iter_examples(cli.dataset, cli.category), cli.start_index, None)
    requested = set(cli.image_id or [])
    selected = [(cat, row) for cat, row in examples if not requested or 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)}')
    if cli.max_samples:
        selected = selected[:cli.max_samples]
    if not selected:
        raise ValueError('No selected examples')
    manifest = cli.output_dir / 'run_config.json'
    if manifest.exists() and not cli.overwrite:
        raise FileExistsError(f'{manifest} exists; choose a new output directory or pass --overwrite')
    if not torch.cuda.is_available():
        raise RuntimeError('The 3B experiment requires a CUDA GPU; use scripts/test_nf_roundtrip.py for CPU checks')

    # Apply only to NF so VAE/text encoding follows the same baseline path.
    args, model, vae, tokenizer, text_encoder, dist, device = load_components(cli)
    run_config = {k: str(v) if isinstance(v, Path) else v for k, v in vars(cli).items()}
    cli.output_dir.mkdir(parents=True, exist_ok=True)
    manifest.write_text(json.dumps(run_config, indent=2) + '\n')
    records = []
    try:
        with torch.no_grad():
            for offset in range(0, len(selected), cli.batch_size):
                batch = selected[offset:offset + cli.batch_size]
                print(f'Processing {[cat + "/" + row["id"] for cat, row in batch]}', flush=True)
                images = torch.cat([preprocess_image(row['image']['bytes'], args.img_size * vae.downsample_factor)
                                    for _, row in batch]).to(device)
                captions = [row['source_prompt'] for _, row in batch]
                if any(not caption for caption in captions):
                    raise ValueError('Missing source caption')
                with torch.autocast('cuda', dtype=torch.bfloat16):
                    latent = encode_vae(vae, images, 'mean', None)
                    y = encode_text(text_encoder, tokenizer, captions, args.txt_size, device)
                    vae_images = vae.decode(latent)
                    if cli.edit:
                        targets = [target_caption(row['target_prompt']) for _, row in batch]
                        prompts = targets + [''] * len(batch) if cli.edit_cfg > 0 else targets
                        edit_y = encode_text(text_encoder, tokenizer, prompts, args.txt_size, device)

                old_matmul, old_cudnn = torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32
                if cli.precision == 'fp32':
                    torch.backends.cuda.matmul.allow_tf32 = False
                    torch.backends.cudnn.allow_tf32 = False
                torch.cuda.synchronize()
                started = time.perf_counter()
                amp = torch.autocast('cuda', dtype=torch.bfloat16) if cli.precision == 'bf16' else nullcontext()
                attention = sdpa_kernel(SDPBackend.MATH) if cli.attention == 'math' else nullcontext()
                try:
                    with amp, attention:
                        encode = model if cli.encoder == 'parallel' else lambda x, c: sequential_forward(model, x, c)
                        z, _, states, logdets = encode(latent.float(), y.float())
                        # No forward KV cache or source prefix is given to reverse.
                        sequence = model(z, y.float(), reverse=True, guidance=0, jacobi=False, return_sequence=True)
                        recovered = sequence[-1]
                        if not torch.isfinite(recovered).all():
                            raise FloatingPointError('Non-finite NF reconstruction; inspect precision and checkpoint')
                        torch.cuda.synchronize()
                        seconds = time.perf_counter() - started
                        if cli.edit:
                            edit_latent = model(z, edit_y.float(), reverse=True, guidance=cli.edit_cfg, jacobi=False)
                finally:
                    torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = old_matmul, old_cudnn
                with torch.autocast('cuda', dtype=torch.bfloat16):
                    # Match the baseline decoder's input precision in all experiments.
                    recon_images = vae.decode(recovered.to(latent.dtype))
                    if cli.edit:
                        edit_images = vae.decode(edit_latent.to(latent.dtype))

                for i, (category, row) in enumerate(batch):
                    item = slice(i, i + 1)
                    relative = Path(category) / row['id']
                    for name, tensors in [('source', images), ('vae_only', vae_images), ('reconstruct', recon_images)]:
                        save_image(tensors[item], cli.output_dir / name / relative.with_suffix('.png'))
                    if cli.edit:
                        save_image(edit_images[item], cli.output_dir / 'editing' / relative.with_suffix('.png'))
                    if cli.save_z:
                        path = cli.output_dir / 'z' / relative.with_suffix('.pt')
                        path.parent.mkdir(parents=True, exist_ok=True)
                        torch.save(z[item].float().cpu(), path)
                    record = {
                        'category': category, 'id': row['id'], 'source_prompt': captions[i],
                        'precision': cli.precision, 'encoder': cli.encoder, 'attention': cli.attention,
                        'vae_latent_mode': 'mean', 'input_noise_std': 0, 'reconstruction_cfg': 0,
                        'edit_cfg': cli.edit_cfg if cli.edit else None,
                        'target_prompt': target_caption(row['target_prompt']) if cli.edit else None,
                        'latent_error': error_metrics(recovered[item], latent[item]),
                        'vae_only_vs_source': pixel_metrics(vae_images[item], images[item]),
                        'reconstruct_vs_source': pixel_metrics(recon_images[item], images[item]),
                        'reconstruct_vs_vae': pixel_metrics(recon_images[item], vae_images[item].float().clamp(-1, 1)),
                        'blocks': block_diagnostics(model, states, logdets, sequence, item),
                        'roundtrip_seconds_for_batch': seconds,
                        'batch_ids': [r['id'] for _, r in batch],
                        'torch_version': torch.__version__, 'gpu': torch.cuda.get_device_name(device),
                    }
                    baseline = cli.baseline_dir / 'metadata' / relative.with_suffix('.json')
                    if baseline.exists():
                        previous = json.loads(baseline.read_text())
                        record['historical_baseline'] = {
                            k: previous[k] for k in ('roundtrip_latent_mae', 'vae_only_vs_source',
                                                     'reconstruct_vs_source', 'vae_latent_mode', 'input_noise_std')
                        }
                    path = cli.output_dir / 'metadata' / relative.with_suffix('.json')
                    path.parent.mkdir(parents=True, exist_ok=True)
                    path.write_text(json.dumps(record, indent=2, allow_nan=False) + '\n')
                    records.append(record)
                    print(f'{category}/{row["id"]}: latent MAE={record["latent_error"]["mae"]:.6g}, '
                          f'PSNR={record["reconstruct_vs_source"]["psnr_db"]}, '
                          f'NF-vs-VAE PSNR={record["reconstruct_vs_vae"]["psnr_db"]}', flush=True)
                del z, states, logdets, sequence, recovered
        (cli.output_dir / 'summary.json').write_text(json.dumps(records, indent=2, allow_nan=False) + '\n')
    finally:
        if dist.distributed and torch.distributed.is_initialized():
            torch.distributed.destroy_process_group()
            dist.distributed = False


if __name__ == '__main__':
    main()