File size: 10,846 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
#!/usr/bin/env python3
"""Compare source/target prompt token NLLs for selected PIE-Bench++ images."""

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

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

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

def token_nll(model, latent, condition):
    z, _, _, logdets = model(latent, condition)
    z_tokens = model.patchify(z).double()
    nll = 0.5 * (z_tokens.square() + math.log(2 * math.pi)).sum(dim=-1)
    for block, logdet in zip(model.blocks, logdets):
        if logdet.ndim == 1:  # IdentityBlock has zero log determinant.
            continue
        # A block may reverse the token order; put its logdet back on the image grid.
        nll -= block.permutation(logdet, inverse=True).double().sum(dim=-1)
    if not torch.isfinite(nll).all():
        raise FloatingPointError('Non-finite token NLL')
    return nll[0].detach().cpu().numpy()


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('--dataset', type=Path,
                        default=Path('/mnt/bn/jiangzhongtao/lingmin/dataset/PIE_Bench_pp'))
    parser.add_argument('--category', default='0_random_140')
    parser.add_argument('--image-id', type=int, action='append',
                        help='PIE-Bench++ image ID; repeat for multiple images (default: 0)')
    parser.add_argument('--max-samples', type=int,
                        help='Process the first N images in the category instead of specifying IDs')
    parser.add_argument('--output-dir', type=Path,
                        help='One image: exact output directory; multiple images: parent directory')
    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('--training-noise', action='store_true',
                        help='Add checkpoint training noise to the scaled VAE latent before NF scoring')
    cli = parser.parse_args()
    if cli.image_id and cli.max_samples is not None:
        parser.error('Choose --image-id or --max-samples, not both')
    if cli.image_id and (min(cli.image_id) < 0 or len(cli.image_id) != len(set(cli.image_id))):
        parser.error('--image-id values must be distinct and nonnegative')
    if cli.max_samples is not None and cli.max_samples < 1:
        parser.error('--max-samples must be positive')
    cli.precision = 'fp32'
    if int(os.environ.get('WORLD_SIZE', '1')) != 1:
        raise ValueError('Use one process/GPU')

    paths = sorted((cli.dataset / cli.category).glob('*.parquet'))
    if not paths:
        raise FileNotFoundError(f'No Parquet files in {cli.dataset / cli.category}')
    requested_ids = cli.image_id if cli.image_id else ([0] if cli.max_samples is None else None)
    limit = len(requested_ids) if requested_ids is not None else cli.max_samples
    rows_by_id = {}
    for path in paths:
        parquet = pq.ParquetFile(path)
        for batch in parquet.iter_batches(batch_size=32,
                                          columns=['id', 'image', 'source_prompt', 'target_prompt']):
            for row in batch.to_pylist():
                image_id = int(row['id'])
                if requested_ids is None or image_id in requested_ids:
                    rows_by_id[image_id] = row
                if len(rows_by_id) == limit:
                    break
            if len(rows_by_id) == limit:
                break
        if len(rows_by_id) == limit:
            break
    if requested_ids is not None:
        missing = set(requested_ids) - rows_by_id.keys()
        if missing:
            raise ValueError(f'Image IDs not found in category {cli.category}: {sorted(missing)}')
        rows = [rows_by_id[image_id] for image_id in requested_ids]
    else:
        rows = list(rows_by_id.values())
    if not rows:
        raise ValueError(f'No images found in category {cli.category}')

    output_dirs = []
    for row in rows:
        source_prompt = row['source_prompt']
        target_prompt = row['target_prompt'].replace('[', '').replace(']', '')
        if not source_prompt or not target_prompt:
            raise ValueError(f'Image {row["id"]} has an empty source or target prompt')
        if cli.output_dir is None:
            output_dir = ROOT / 'result/token_nll_delta' / cli.category / row['id']
        elif len(rows) == 1:
            output_dir = cli.output_dir
        else:
            output_dir = cli.output_dir / row['id']
        if output_dir.exists():
            raise FileExistsError(f'Output directory already exists: {output_dir}')
        output_dirs.append(output_dir)
    if not torch.cuda.is_available():
        raise RuntimeError('STARFlow 3B scoring requires a CUDA GPU')

    os.environ.setdefault('HF_HUB_CACHE', str(ROOT / 'ckpts/hf_cache'))
    os.environ.setdefault('HF_HUB_OFFLINE', '1')
    os.environ.setdefault('TRANSFORMERS_OFFLINE', '1')
    from pie_bench_nf_components import add_training_noise, load_components
    from utils import encode_text

    args, model, vae, tokenizer, text_encoder, _, device = load_components(cli)
    input_noise_std = args.noise_std if cli.training_noise else 0.0
    text_kwargs = {'noise_std': input_noise_std} if args.cond_noise_level and cli.training_noise else {}
    image_size = args.img_size * vae.downsample_factor
    import matplotlib
    matplotlib.use('Agg')
    import matplotlib.pyplot as plt

    old_matmul = torch.backends.cuda.matmul.allow_tf32
    old_cudnn = torch.backends.cudnn.allow_tf32
    torch.backends.cuda.matmul.allow_tf32 = False
    torch.backends.cudnn.allow_tf32 = False
    try:
        with torch.inference_mode():
            for row, output_dir in zip(rows, output_dirs):
                source_prompt = row['source_prompt']
                target_prompt = row['target_prompt'].replace('[', '').replace(']', '')
                with Image.open(BytesIO(row['image']['bytes'])) as raw:
                    source_image = ImageOps.exif_transpose(raw).convert('RGB')
                scale = max(image_size / source_image.height, image_size / source_image.width)
                transform = transforms.Compose([
                    transforms.Resize((int(source_image.height * scale), int(source_image.width * scale))),
                    transforms.CenterCrop((image_size, image_size)),
                    transforms.ToTensor(),
                    transforms.Normalize([0.5] * 3, [0.5] * 3),
                ])
                image = transform(source_image).unsqueeze(0)

                with torch.autocast('cuda', dtype=torch.bfloat16):
                    posterior = vae.vae.encode(image.to(device)).latent_dist
                    latent = posterior.mode() * vae.scaling_factor
                    source_condition = encode_text(text_encoder, tokenizer, [source_prompt],
                                                   args.txt_size, device, **text_kwargs)
                    target_condition = encode_text(text_encoder, tokenizer, [target_prompt],
                                                   args.txt_size, device, **text_kwargs)
                latent = latent.float()
                noise_seed = cli.seed + sum(ord(c) for c in cli.category) + int(row['id']) + 1_000_003
                if cli.training_noise:
                    latent = add_training_noise(latent, args, noise_seed)
                source_map = token_nll(model, latent, source_condition.float())
                target_map = token_nll(model, latent, target_condition.float())
                delta_map = target_map - source_map
                summary = {
                    'category': cli.category,
                    'image_id': row['id'],
                    'source_prompt': source_prompt,
                    'target_prompt': target_prompt,
                    'source_nll': float(source_map.sum()),
                    'target_nll': float(target_map.sum()),
                    'delta_nll_target_minus_source': float(delta_map.sum()),
                    'token_map_shape': list(delta_map.shape),
                    'likelihood_space': 'scaled VAE latent',
                    'vae_latent': 'posterior mean',
                    'guidance': 0.0,
                    'training_noise': cli.training_noise,
                    'input_noise_std': input_noise_std,
                    'noise_seed': noise_seed if cli.training_noise else None,
                    'shared_source_target_noise': True,
                    'delta_definition': 'target token NLL - source token NLL; negative favors target',
                    'token_values': 'additive joint-NLL contributions, not conditional token probabilities',
                }
                output_dir.mkdir(parents=True, exist_ok=False)
                np.savez_compressed(output_dir / 'token_nll.npz', source=source_map,
                                    target=target_map, delta=delta_map)

                rgb = ((image[0].float().cpu().clamp(-1, 1) + 1) * 127.5)
                rgb = rgb.round().byte().permute(1, 2, 0).numpy()
                color_limit = max(float(np.abs(delta_map).max()), 1e-12)
                figure, axes = plt.subplots(1, 2, figsize=(11, 4.5), constrained_layout=True)
                axes[0].imshow(rgb)
                axes[0].set_title('Input image')
                axes[0].axis('off')
                heatmap = axes[1].imshow(delta_map, cmap='coolwarm', vmin=-color_limit,
                                         vmax=color_limit, interpolation='nearest')
                axes[1].set_title('Target NLL - source NLL')
                axes[1].set_xlabel('Latent token column')
                axes[1].set_ylabel('Latent token row')
                figure.colorbar(heatmap, ax=axes[1], label='NLL difference (nats/token)')
                figure.suptitle(f'{cli.category}/{row["id"]}: blue = target NLL lower')
                figure.savefig(output_dir / 'token_nll_delta.png', dpi=180)
                plt.close(figure)
                (output_dir / 'summary.json').write_text(
                    json.dumps(summary, ensure_ascii=False, indent=2) + '\n', encoding='utf-8')
                print(f'{cli.category}/{row["id"]}: source={summary["source_nll"]:.6f}, '
                      f'target={summary["target_nll"]:.6f}, '
                      f'delta={summary["delta_nll_target_minus_source"]:.6f} -> {output_dir}',
                      flush=True)
    finally:
        torch.backends.cuda.matmul.allow_tf32 = old_matmul
        torch.backends.cudnn.allow_tf32 = old_cudnn


if __name__ == '__main__':
    main()