File size: 14,709 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 | #!/usr/bin/env python3
"""Visualize source-to-target conditional Gaussian KL at fixed source prefixes.
The distributions describe the input tokens of STARFlow's deepest block,
after the text-independent shallow flow. Their KL sum at one observed set
of prefixes is not the KL between the full image distributions.
"""
import argparse
from io import BytesIO
import json
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 torch.nn.functional as F
import torchvision.transforms as transforms
from PIL import Image, ImageOps
from transformer_flow import INV_SOFTPLUS_1
def diagonal_gaussian_kl(source_mu, source_sigma, target_mu, target_sigma):
source_mu, source_sigma, target_mu, target_sigma = [
value.double() for value in (source_mu, source_sigma, target_mu, target_sigma)]
if (not all(torch.isfinite(value).all() for value in
(source_mu, source_sigma, target_mu, target_sigma))
or (source_sigma <= 0).any() or (target_sigma <= 0).any()):
raise FloatingPointError('Gaussian parameters must be finite with positive scales')
log_ratio = 2 * (source_sigma.log() - target_sigma.log())
# expm1(a) - a equals sigma_s^2/sigma_t^2 - 1 - log(sigma_s^2/sigma_t^2),
# avoiding cancellation for nearly equal scales.
variance_term = 0.5 * (torch.expm1(log_ratio) - log_ratio).sum(dim=-1)
mean_term = 0.5 * ((source_mu - target_mu) / target_sigma).square().sum(dim=-1)
kl = mean_term + variance_term
if not torch.isfinite(kl).all():
raise FloatingPointError('Non-finite conditional Gaussian KL')
return kl, mean_term, variance_term
@torch.no_grad()
def conditional_kl_maps(model, latent, source_condition, target_condition):
if latent.ndim != 4 or not model.cond_top_only or model.temporal_causal or model.shallow_block_local:
raise ValueError('Requires an image flow with cond_top_only=True')
if latent.dtype != torch.float32 or next(model.parameters()).dtype != torch.float32:
raise ValueError('NF inputs and weights must use FP32')
source_state = model.patchify(latent)
for block in model.blocks[:-1]:
source_state, _, _ = block(source_state, source_condition, model.feat_rope)
block = model.blocks[-1]
projections = []
hook = block.proj_out.register_forward_hook(
lambda module, inputs, output: projections.append(output.detach()))
try:
# Only text changes: both branches teacher-force the same source state.
block(torch.cat([source_state, source_state]),
torch.cat([source_condition, target_condition]), model.feat_rope_gen, guidance=0)
finally:
hook.remove()
raw = projections[0]
if block.soft_clip > 0:
raw = block.soft_clip * torch.tanh(raw / block.soft_clip)
if not block.use_sos:
raw = torch.cat([torch.zeros_like(raw[:, :1]), raw[:, :-1]], dim=1)
raw_scale, mu = raw.float().chunk(2, dim=-1)
# Forward standardizes (h - mu) / sigma; inverse multiplies noise by sigma.
sigma = F.softplus(raw_scale + INV_SOFTPLUS_1) if block.use_softplus else raw_scale.exp()
source_mu, target_mu = mu.chunk(2)
source_sigma, target_sigma = sigma.chunk(2)
kl, mean_term, variance_term = diagonal_gaussian_kl(
source_mu, source_sigma, target_mu, target_sigma)
token_index = torch.arange(mu.shape[1], device=mu.device).reshape(1, -1, 1)
token_index = token_index.expand(source_state.shape[0], -1, -1)
values = dict(kl_source_target=kl, kl_mean=mean_term, kl_variance=variance_term,
source_mu=source_mu, source_sigma=source_sigma,
target_mu=target_mu, target_sigma=target_sigma, token_index=token_index)
maps = {'source_state': source_state}
for name, value in values.items():
scalar = value.ndim == 2 or name == 'token_index'
if value.ndim == 2:
value = value.unsqueeze(-1)
# Use the stateless permutation API: scalar maps have a different channel count.
grid = block.permutation.permute(value, dim=1, shape=source_state.shape, inverse=True)
grid = grid.reshape(*source_state.shape[:-1], value.shape[-1])
maps[name] = grid.squeeze(-1) if scalar else grid
return maps
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='Repeat for multiple PIE-Bench++ image IDs (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 the flow')
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')
if int(os.environ.get('WORLD_SIZE', '1')) != 1:
parser.error('Use one process/GPU')
cli.precision = 'fp32'
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:
if not row['source_prompt'] or not row['target_prompt'].replace('[', '').replace(']', ''):
raise ValueError(f'Image {row["id"]} has an empty source or target prompt')
if cli.output_dir is None:
output_dir = ROOT / 'result/token_kl' / cli.category / str(row['id'])
elif len(rows) == 1:
output_dir = cli.output_dir
else:
output_dir = cli.output_dir / str(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
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
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
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)
tensors = conditional_kl_maps(model, latent, source_condition.float(), target_condition.float())
maps = {name: value[0].cpu().numpy() for name, value in tensors.items()}
summary = {
'category': cli.category, 'image_id': row['id'],
'source_prompt': source_prompt, 'target_prompt': target_prompt,
'kl_direction': 'source || target', 'units': 'nats/token; sum over channels',
'kl_sum_at_source_prefixes': float(maps['kl_source_target'].sum()),
'kl_mean': float(maps['kl_source_target'].mean()),
'kl_max': float(maps['kl_source_target'].max()),
'mean_term_sum': float(maps['kl_mean'].sum()),
'variance_term_sum': float(maps['kl_variance'].sum()),
'token_map_shape': list(maps['kl_source_target'].shape),
'channels_per_token': int(maps['source_mu'].shape[-1]),
'block_index': len(model.blocks) - 1,
'distribution_space': 'deepest-block input after text-independent shallow flow',
'context': 'identical source-image prefixes for both prompts; teacher forcing',
'array_layout': 'spatial H,W[,C]; token_index gives zero-based autoregressive order',
'vae_latent': 'posterior mean, scaled', 'guidance': 0.0,
'nf_precision': 'fp32', 'kl_precision': 'fp64',
'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,
'sum_interpretation': 'fixed-prefix conditional KL sum, not full image-distribution KL',
}
output_dir.mkdir(parents=True, exist_ok=False)
np.savez_compressed(output_dir / 'token_kl.npz', **maps)
rgb = ((image[0].float().cpu().clamp(-1, 1) + 1) * 127.5)
rgb = rgb.round().byte().permute(1, 2, 0).numpy()
Image.fromarray(rgb).save(output_dir / 'input.png')
figure, axes = plt.subplots(1, 4, figsize=(18, 4.5), constrained_layout=True)
axes[0].imshow(rgb)
axes[0].set_title('Input image')
axes[0].axis('off')
color_max = max(summary['kl_max'], 1e-12)
for axis, name, title in zip(axes[1:],
('kl_source_target', 'kl_mean', 'kl_variance'),
('KL(source || target)', 'Mean contribution', 'Variance contribution')):
heatmap = axis.imshow(maps[name], cmap='magma', vmin=0, vmax=color_max,
interpolation='nearest')
axis.set_title(title)
axis.set_xlabel('Token column')
axis.set_ylabel('Token row')
figure.colorbar(heatmap, ax=list(axes[1:]), label='nats/token (shared scale)')
figure.suptitle(f'{cli.category}/{row["id"]}: identical source prefixes')
figure.savefig(output_dir / 'token_kl.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"]}: KL sum={summary["kl_sum_at_source_prefixes"]:.6f}, '
f'mean={summary["kl_mean"]:.6f}, max={summary["kl_max"]:.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()
|