SADAE / scripts /pie_bench_nf_precision.py
Lingmin-Ran's picture
Upload SADAE source snapshot (82ceb4d)
2cf4a54 verified
Raw History Blame Contribute Delete
11 kB
#!/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()