SADAE / scripts /compare_nf_target_nll.py
Lingmin-Ran's picture
Upload SADAE source snapshot (82ceb4d)
2cf4a54 verified
Raw History Blame Contribute Delete
16.5 kB
#!/usr/bin/env python3
"""Compare NF target NLLs or source/target log-likelihood ratios of saved images.
NLL is measured in the scaled VAE latent space, in nats. Both image groups
use the VAE posterior mean, no added noise, and the standard FP32 NF forward
without classifier-free guidance. This is not a pixel-space likelihood.
Ratio mode measures R = NLL(source) - NLL(target); positive delta_R means
editing increased the preference for the target relative to the source prompt.
"""
import argparse
import csv
import json
import math
import os
from pathlib import Path
import statistics
import sys
import torch
from PIL import Image, ImageOps
import torchvision.transforms as transforms
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.webp', '.bmp', '.tif', '.tiff'}
def parse_args():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--baseline-dir', type=Path, default=ROOT / 'result/baseline_fp32')
parser.add_argument('--category', default='0_random_140')
parser.add_argument('--score-mode', choices=('target', 'ratio'), default='target',
help='target: original target NLL comparison; ratio: also compute R and delta_R')
parser.add_argument('--output-dir', type=Path,
help='Must not exist; default: BASELINE_DIR/nll_<score-mode>/CATEGORY')
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('--batch-size', type=int, default=4)
parser.add_argument('--max-samples', type=int, default=0, help='0: all pairs; positive: first N pairs')
parser.add_argument('--seed', type=int, default=999)
parser.set_defaults(precision='fp32')
cli = parser.parse_args()
if cli.batch_size < 1 or cli.max_samples < 0:
parser.error('batch-size must be positive; max-samples must be nonnegative')
if int(os.environ.get('WORLD_SIZE', '1')) != 1:
parser.error('Use one process/GPU')
if cli.output_dir is None:
cli.output_dir = cli.baseline_dir / f'nll_{cli.score_mode}' / cli.category
return cli
def collect_pairs(baseline_dir, category, score_mode='target'):
groups = {}
for kind in ('reconstruct', 'editing'):
directory = baseline_dir / kind / category
if not directory.is_dir():
raise FileNotFoundError(f'Image directory not found: {directory}')
images = {}
for path in sorted(directory.iterdir()):
if path.is_file() and path.suffix.lower() in IMAGE_EXTENSIONS:
if path.stem in images:
raise ValueError(f'Duplicate image ID in {directory}: {path.stem}')
images[path.stem] = path
groups[kind] = images
reconstruct_ids, editing_ids = set(groups['reconstruct']), set(groups['editing'])
if reconstruct_ids != editing_ids:
raise ValueError(
f'Unpaired images: reconstruct-only={sorted(reconstruct_ids - editing_ids)}, '
f'editing-only={sorted(editing_ids - reconstruct_ids)}'
)
if not reconstruct_ids:
raise ValueError('No image pairs found')
pairs = []
for image_id in sorted(reconstruct_ids):
metadata_path = baseline_dir / 'metadata' / category / f'{image_id}.json'
metadata = json.loads(metadata_path.read_text(encoding='utf-8'))
prompt = metadata.get('target_prompt')
if not isinstance(prompt, str) or not prompt.strip():
raise ValueError(f'Missing or empty target_prompt in {metadata_path}')
source_prompt = metadata.get('source_prompt')
if score_mode == 'ratio' and (not isinstance(source_prompt, str) or not source_prompt.strip()):
raise ValueError(f'Missing or empty source_prompt in {metadata_path}')
if metadata['id'] != image_id or metadata['category'] != category:
raise ValueError(f'Metadata ID/category does not match image: {metadata_path}')
pairs.append({
'id': image_id,
'source_prompt': source_prompt,
'target_prompt': prompt,
'metadata_path': str(metadata_path.resolve()),
**{kind: images[image_id] for kind, images in groups.items()},
})
return pairs
def preprocess_image(path, image_size):
with Image.open(path) 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)
def compute_nll(z, logdets):
# Reduce each sample separately; model.get_loss() averages over the batch
# and omits the Gaussian normalizing constant.
flat_z = z.flatten(start_dim=1).double()
latent_dim = flat_z.shape[1]
prior_nll = 0.5 * flat_z.square().sum(dim=1) + 0.5 * latent_dim * math.log(2 * math.pi)
log_abs_det = torch.zeros_like(prior_nll)
for logdet in logdets:
log_abs_det += logdet.flatten(start_dim=1).double().sum(dim=1)
nll = prior_nll - log_abs_det
values = torch.stack([
nll, nll / latent_dim, nll / latent_dim - 0.5 * math.log(2 * math.pi),
prior_nll, log_abs_det,
], dim=1)
if not torch.isfinite(values).all():
raise FloatingPointError('Non-finite NF NLL; inspect input images and checkpoint')
names = ('nll', 'nll_per_dim', 'nf_loss_per_dim', 'prior_nll', 'log_abs_det')
return [dict(zip(names, row), latent_dim=latent_dim) for row in values.cpu().tolist()]
def build_report(pairs, scores, score_mode):
comparisons = []
for pair in pairs:
reconstruct = scores['reconstruct']['target'][pair['id']]
editing = scores['editing']['target'][pair['id']]
delta = editing['nll'] - reconstruct['nll']
row = {
'id': pair['id'], 'target_prompt': pair['target_prompt'],
'reconstruct_image': str(pair['reconstruct'].resolve()),
'editing_image': str(pair['editing'].resolve()),
'latent_dim': reconstruct['latent_dim'],
'reconstruct_nll': reconstruct['nll'], 'editing_nll': editing['nll'],
'delta_nll': delta,
'reconstruct_nll_per_dim': reconstruct['nll_per_dim'],
'editing_nll_per_dim': editing['nll_per_dim'],
'delta_nll_per_dim': editing['nll_per_dim'] - reconstruct['nll_per_dim'],
'lower_nll': 'editing' if delta < 0 else 'reconstruct' if delta > 0 else 'tie',
}
if score_mode == 'ratio':
row['source_prompt'] = pair['source_prompt']
for kind, target in [('reconstruct', reconstruct), ('editing', editing)]:
source = scores[kind]['source'][pair['id']]
row[f'{kind}_source_nll'] = source['nll']
row[f'{kind}_source_nll_per_dim'] = source['nll_per_dim']
row[f'{kind}_r'] = source['nll'] - target['nll']
row[f'{kind}_r_per_dim'] = row[f'{kind}_r'] / target['latent_dim']
row['delta_r'] = row['editing_r'] - row['reconstruct_r']
row['delta_r_per_dim'] = row['delta_r'] / row['latent_dim']
row['higher_r'] = ('editing' if row['delta_r'] > 0 else
'reconstruct' if row['delta_r'] < 0 else 'tie')
comparisons.append(row)
deltas = [row['delta_nll'] for row in comparisons]
summary = {
'count': len(pairs),
'reconstruct_mean_nll': statistics.mean(row['reconstruct_nll'] for row in comparisons),
'editing_mean_nll': statistics.mean(row['editing_nll'] for row in comparisons),
'reconstruct_mean_nll_per_dim': statistics.mean(row['reconstruct_nll_per_dim'] for row in comparisons),
'editing_mean_nll_per_dim': statistics.mean(row['editing_nll_per_dim'] for row in comparisons),
'mean_delta_nll': statistics.mean(deltas),
'median_delta_nll': statistics.median(deltas),
'std_delta_nll_population': statistics.pstdev(deltas),
'mean_delta_nll_per_dim': statistics.mean(row['delta_nll_per_dim'] for row in comparisons),
'editing_lower_count': sum(delta < 0 for delta in deltas),
'reconstruct_lower_count': sum(delta > 0 for delta in deltas),
'tie_count': sum(delta == 0 for delta in deltas),
'editing_lower_fraction': sum(delta < 0 for delta in deltas) / len(deltas),
}
if score_mode == 'ratio':
for kind in ('reconstruct', 'editing'):
for field in ('source_nll', 'source_nll_per_dim', 'r', 'r_per_dim'):
summary[f'{kind}_mean_{field}'] = statistics.mean(row[f'{kind}_{field}'] for row in comparisons)
delta_rs = [row['delta_r'] for row in comparisons]
summary.update({
'mean_delta_r': statistics.mean(delta_rs),
'median_delta_r': statistics.median(delta_rs),
'std_delta_r_population': statistics.pstdev(delta_rs),
'mean_delta_r_per_dim': statistics.mean(row['delta_r_per_dim'] for row in comparisons),
'r_improved_count': sum(delta > 0 for delta in delta_rs),
'r_decreased_count': sum(delta < 0 for delta in delta_rs),
'r_tie_count': sum(delta == 0 for delta in delta_rs),
'r_improved_fraction': sum(delta > 0 for delta in delta_rs) / len(delta_rs),
})
return comparisons, summary
def main():
cli = parse_args()
pairs = collect_pairs(cli.baseline_dir, cli.category, cli.score_mode)
if cli.max_samples:
pairs = pairs[:cli.max_samples]
if cli.output_dir.exists():
raise FileExistsError(f'{cli.output_dir} exists; choose a new --output-dir')
conditions = ('source', 'target') if cli.score_mode == 'ratio' else ('target',)
print(f'Found {len(pairs)} pairs; scoring saved images with {conditions} prompts', flush=True)
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 utils import encode_text
from pie_bench_nf_components import load_components
args, model, vae, tokenizer, text_encoder, dist, device = load_components(cli)
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:
image_size = args.img_size * vae.downsample_factor
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({
'likelihood_space': 'scaled VAE latent',
'nll_unit': 'nats',
'nll_per_dim_unit': 'nats/latent dimension',
'nll_formula': '0.5 * sum(z**2) + D/2 * log(2*pi) - sum(logdets)',
'nf_loss_per_dim': 'nll_per_dim - 0.5 * log(2*pi)',
'vae_latent_mode': 'mean',
'input_noise_std': 0.0,
'guidance': 0.0,
'vae_text_autocast': 'bf16 (same as baseline)',
'tf32': False,
'image_size': image_size,
'delta_definition': 'editing - reconstruct; negative favors editing',
'torch_version': torch.__version__,
'gpu': torch.cuda.get_device_name(device),
})
if cli.score_mode == 'ratio':
run_config.update({
'r_formula': 'NLL(source_prompt) - NLL(target_prompt)',
'r_unit': 'nats',
'r_per_dim_unit': 'nats/latent dimension',
'delta_r_definition': 'editing_r - reconstruct_r; positive favors editing',
'nll_columns_condition': 'unqualified NLL fields retain target_prompt scores',
})
scores = {kind: {condition: {} for condition in conditions} for kind in ('reconstruct', 'editing')}
with torch.inference_mode(), (cli.output_dir / 'scores.jsonl').open('x', encoding='utf-8') as output:
for kind in ('reconstruct', 'editing'):
for offset in range(0, len(pairs), cli.batch_size):
batch = pairs[offset:offset + cli.batch_size]
images = torch.stack([preprocess_image(pair[kind], image_size)
for pair in batch]).to(device)
with torch.autocast('cuda', dtype=torch.bfloat16):
posterior = vae.vae.encode(images).latent_dist
latent = posterior.mode() * vae.scaling_factor
# Evaluate both prompts on exactly the same VAE latent without doubling the NF batch.
latent = latent.float()
for prompt_kind in conditions:
prompts = [pair[f'{prompt_kind}_prompt'] for pair in batch]
with torch.autocast('cuda', dtype=torch.bfloat16):
condition = encode_text(text_encoder, tokenizer, prompts, args.txt_size, device)
z, _, states, logdets = model(latent, condition.float())
batch_scores = compute_nll(z, logdets)
for pair, score in zip(batch, batch_scores):
scores[kind][prompt_kind][pair['id']] = score
record = {
'id': pair['id'], 'category': cli.category, 'kind': kind,
'image_path': str(pair[kind].resolve()),
'metadata_path': pair['metadata_path'],
'target_prompt': pair['target_prompt'], **score,
}
if cli.score_mode == 'ratio':
record.update({
'source_prompt': pair['source_prompt'],
'condition': prompt_kind,
'conditioning_prompt': pair[f'{prompt_kind}_prompt'],
})
output.write(json.dumps(record, ensure_ascii=False, allow_nan=False) + '\n')
print(f'{kind}/{pair["id"]} [{prompt_kind}]: NLL={score["nll"]:.6f}, '
f'NLL/dim={score["nll_per_dim"]:.6f}', flush=True)
output.flush()
del z, states, logdets, condition
del posterior, latent, images
comparisons, summary = build_report(pairs, scores, cli.score_mode)
with (cli.output_dir / 'comparison.csv').open('x', encoding='utf-8', newline='') as output:
writer = csv.DictWriter(output, fieldnames=list(comparisons[0]))
writer.writeheader()
writer.writerows(comparisons)
summary = {'run_config': run_config, **summary}
with (cli.output_dir / 'summary.json').open('x', encoding='utf-8') as output:
output.write(json.dumps(summary, indent=2, ensure_ascii=False, allow_nan=False) + '\n')
print(f'Compared {len(pairs)} pairs: mean NLL delta={summary["mean_delta_nll"]:.6f}; '
f'editing lower={summary["editing_lower_count"]}, '
f'reconstruct lower={summary["reconstruct_lower_count"]}, ties={summary["tie_count"]}', flush=True)
if cli.score_mode == 'ratio':
print(f'Mean delta_R={summary["mean_delta_r"]:.6f}; '
f'R improved={summary["r_improved_count"]}/{summary["count"]}, '
f'decreased={summary["r_decreased_count"]}, ties={summary["r_tie_count"]}', flush=True)
print(f'Results: {cli.output_dir.resolve()}', flush=True)
finally:
torch.backends.cuda.matmul.allow_tf32 = old_matmul
torch.backends.cudnn.allow_tf32 = old_cudnn
if dist.distributed and torch.distributed.is_initialized():
torch.distributed.destroy_process_group()
dist.distributed = False
if __name__ == '__main__':
main()