Download scripts/nf_source_anchored_decoupled_affine_editing.py from Lingmin-Ran/SADAE: direct link, hf CLI and curl.
- Browser
- Download file 30.8 kB
-
https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/nf_source_anchored_decoupled_affine_editing.py
- Command line
-
hf download hf://Lingmin-Ran/SADAE/scripts/nf_source_anchored_decoupled_affine_editing.py
-
curl -L -o nf_source_anchored_decoupled_affine_editing.py https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/nf_source_anchored_decoupled_affine_editing.py
30.8 kB
| #!/usr/bin/env python3 | |
| """Source-Anchored Decoupled Affine Editing v2 (SADAE), without masks. | |
| Use one image with explicit prompts, or select images from PIE-Bench/PIE-Bench++. | |
| The NF network and KV caches use FP32. Training noise is optional. | |
| Gamma defaults to 1 to preserve the original SADAE update. | |
| Optional CFG uses closed-loop source encoding and FP64 affine arithmetic. | |
| PIE-Bench metrics are evaluated on saved images after generation. | |
| Under torchrun, each GPU edits a distinct subset and rank 0 merges the results. | |
| """ | |
| import argparse | |
| from io import BytesIO | |
| from itertools import chain, islice | |
| import json | |
| import math | |
| import os | |
| from pathlib import Path | |
| import sys | |
| import time | |
| import torch | |
| import torch.nn.functional as F | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| from transformer_flow import IdentityBlock, INV_SOFTPLUS_1, KVCache | |
| DEFAULT_DATASET = Path('/mnt/bn/jiangzhongtao/lingmin/dataset/PIE_Bench_pp') | |
| def cfg_candidate(block, prefix, step, cache, freqs, noise, cfg): | |
| raw, mean = block.reverse_step(prefix, step, cache, freqs_cis=freqs) | |
| raw, mean = raw.double(), mean.double() | |
| scale = F.softplus(raw + INV_SOFTPLUS_1) if block.use_softplus else raw.exp() | |
| mean, scale = block.guidance(scale, mean, cfg) | |
| slot = step if block.use_sos else step + 1 | |
| return noise[:, slot:slot + 1] * scale[:1] + mean[:1] | |
| def edit_latent(model, source_latent, source_condition, target_condition, | |
| alpha=1.0, beta=0.5, verbose=True, *, gamma=1.0, cfg=0.0, empty_condition=None): | |
| if not math.isfinite(alpha) or alpha < 0: | |
| raise ValueError('alpha must be finite and nonnegative') | |
| if not math.isfinite(beta) or not 0 <= beta <= 1: | |
| raise ValueError('beta must be finite and in [0, 1]') | |
| if not math.isfinite(gamma) or not 0 <= gamma <= 1: | |
| raise ValueError('gamma must be finite and in [0, 1]') | |
| if not math.isfinite(cfg) or cfg < 0: | |
| raise ValueError('cfg must be finite and nonnegative') | |
| if source_latent.ndim != 4 or source_latent.shape[0] != 1: | |
| raise ValueError('Edit one image at a time with latent shape [1, C, H, W]') | |
| if source_condition.ndim != 3 or source_condition.shape[0] != 1 or source_condition.shape != target_condition.shape: | |
| raise ValueError('Conditions must have matching shapes [1, text_length, text_dim]') | |
| if cfg > 0: | |
| if empty_condition is None or empty_condition.shape != source_condition.shape: | |
| raise ValueError('CFG requires an empty condition matching the source condition shape') | |
| if any(c.dtype != torch.float32 for c in (source_condition, target_condition, empty_condition)): | |
| raise ValueError('CFG conditions must use FP32') | |
| if not model.use_rope or model.temporal_causal or model.shallow_block_local or not model.cond_top_only: | |
| raise ValueError('Requires an image StarFlow with RoPE and cond_top_only=True') | |
| if model.training: | |
| raise ValueError('Call model.eval() before editing') | |
| if source_latent.dtype != torch.float32 or next(model.parameters()).dtype != torch.float32: | |
| raise ValueError('NF inputs and weights must use FP32') | |
| if any(not isinstance(block, IdentityBlock) and block.txt_dim > 0 for block in model.blocks[:-1]): | |
| raise ValueError('Shallow blocks must be unconditional') | |
| top = model.blocks[-1] | |
| if cfg > 0: | |
| from nf_roundtrip import closed_loop_forward | |
| source_pair = torch.cat([source_condition, empty_condition]) | |
| target_pair = torch.cat([target_condition, empty_condition]) | |
| if verbose: | |
| print(f' closed-loop source encoding; cfg={cfg}', flush=True) | |
| _, states, simulated_top = closed_loop_forward(model, source_latent, source_pair, cfg) | |
| else: | |
| _, _, states, _ = model(source_latent, source_condition, guidance=0) | |
| source_pair, target_pair = source_condition, target_condition | |
| source_state = states[-2] | |
| # h and z must share the deepest block's autoregressive order. | |
| original = top.permutation(source_state) | |
| noise = top.permutation(states[-1]) | |
| if not torch.isfinite(original).all() or not torch.isfinite(noise).all(): | |
| raise FloatingPointError('Non-finite source inversion') | |
| cache_state = torch.cat([source_state, source_state]) if cfg > 0 else source_state | |
| if cfg > 0: | |
| freqs = top.get_freqs_cis(cache_state, source_pair, model.feat_rope_gen) | |
| reference_prefix = top.permutation(model.patchify(simulated_top)) | |
| fixed_prefix = torch.cat([reference_prefix, reference_prefix]) | |
| reference_state = original.double() | |
| fixed_text_delta = torch.zeros_like(noise) | |
| source_cache, target_cache = KVCache(), KVCache() | |
| try: | |
| top.initialize_kv_cache(source_cache, cache_state, freqs) | |
| top.initialize_kv_cache(target_cache, cache_state, freqs) | |
| top.reverse_step_condition(source_pair, source_cache, freqs_cis=freqs) | |
| top.reverse_step_condition(target_pair, target_cache, freqs_cis=freqs) | |
| steps = noise.shape[1] if top.use_sos else noise.shape[1] - 1 | |
| if verbose: | |
| print(f' fixed CFG reference: {steps} steps', flush=True) | |
| for step in range(steps): | |
| source_candidate = cfg_candidate(top, fixed_prefix, step, source_cache, freqs, noise, cfg) | |
| target_candidate = cfg_candidate(top, fixed_prefix, step, target_cache, freqs, noise, cfg) | |
| slot = step if top.use_sos else step + 1 | |
| reference_state[:, slot:slot + 1] = source_candidate | |
| fixed_text_delta[:, slot:slot + 1] = target_candidate - source_candidate | |
| finally: | |
| source_cache.delete() | |
| target_cache.delete() | |
| if not torch.isfinite(reference_state).all(): | |
| raise FloatingPointError('Non-finite closed-loop reference') | |
| else: | |
| projections = [] | |
| hook = top.proj_out.register_forward_hook( | |
| lambda module, inputs, output: projections.append(output.detach())) | |
| try: | |
| top(source_state, target_condition, model.feat_rope_gen, guidance=0) | |
| finally: | |
| hook.remove() | |
| raw = projections[0].float() | |
| if top.soft_clip > 0: | |
| raw = top.soft_clip * torch.tanh(raw / top.soft_clip) | |
| if not top.use_sos: | |
| raw = torch.cat([torch.zeros_like(raw[:, :1]), raw[:, :-1]], dim=1) | |
| raw_scale, mean = raw.chunk(2, dim=-1) | |
| scale = F.softplus(raw_scale + INV_SOFTPLUS_1) if top.use_softplus else raw_scale.exp() | |
| fixed_text_delta = mean + scale * noise - original | |
| reference_state = original | |
| if not torch.isfinite(fixed_text_delta).all(): | |
| raise FloatingPointError('Non-finite fixed source-prefix text delta') | |
| generated = reference_state.clone() | |
| text_delta = torch.zeros_like(generated) | |
| prefix_delta = torch.zeros_like(generated) | |
| interaction_delta = torch.zeros_like(generated) | |
| if cfg > 0: | |
| network_prefix = torch.zeros_like(fixed_prefix) | |
| if not top.use_sos: | |
| network_prefix[:, :1] = fixed_prefix[:, :1] | |
| else: | |
| freqs = top.get_freqs_cis(source_state, source_condition, model.feat_rope_gen) | |
| source_cache, target_cache = KVCache(), KVCache() | |
| try: | |
| top.initialize_kv_cache(source_cache, cache_state, freqs) | |
| top.initialize_kv_cache(target_cache, cache_state, freqs) | |
| top.reverse_step_condition(source_pair, source_cache, freqs_cis=freqs) | |
| top.reverse_step_condition(target_pair, target_cache, freqs_cis=freqs) | |
| # Without SOS, the first token has the identity affine under both conditions. | |
| steps = noise.shape[1] if top.use_sos else noise.shape[1] - 1 | |
| if verbose: | |
| print(f' deepest block: {noise.shape[1]} tokens; alpha={alpha}, beta={beta}, gamma={gamma}', flush=True) | |
| for step in range(steps): | |
| slot = step if top.use_sos else step + 1 | |
| if cfg > 0: | |
| source_candidate = cfg_candidate(top, network_prefix, step, source_cache, freqs, noise, cfg) | |
| target_candidate = cfg_candidate(top, network_prefix, step, target_cache, freqs, noise, cfg) | |
| else: | |
| source_raw, source_mean = top.reverse_step( | |
| generated, step, source_cache, y=source_condition, freqs_cis=freqs) | |
| target_raw, target_mean = top.reverse_step( | |
| generated, step, target_cache, y=target_condition, freqs_cis=freqs) | |
| if top.use_softplus: | |
| source_scale = F.softplus(source_raw.float() + INV_SOFTPLUS_1) | |
| target_scale = F.softplus(target_raw.float() + INV_SOFTPLUS_1) | |
| else: | |
| source_scale, target_scale = source_raw.float().exp(), target_raw.float().exp() | |
| source_candidate = source_mean.float() + source_scale * noise[:, slot:slot + 1] | |
| target_candidate = target_mean.float() + target_scale * noise[:, slot:slot + 1] | |
| reference = reference_state[:, slot:slot + 1] | |
| d = target_candidate - source_candidate | |
| b = source_candidate - reference | |
| d0 = fixed_text_delta[:, slot:slot + 1] | |
| q = d - d0 | |
| text_delta[:, slot:slot + 1] = d | |
| prefix_delta[:, slot:slot + 1] = b | |
| interaction_delta[:, slot:slot + 1] = q | |
| # Both independent caches consume this final edited token on the next step. | |
| if cfg > 0 and alpha == beta == gamma == 1.0: | |
| # Match closed_loop_reverse without cancellation in the unit-weight limit. | |
| generated[:, slot:slot + 1] = target_candidate | |
| elif gamma == 1.0: | |
| # Preserve the original floating-point operation order. | |
| generated[:, slot:slot + 1] = reference + alpha * d + beta * b | |
| else: | |
| generated[:, slot:slot + 1] = reference + alpha * d0 + beta * b + alpha * gamma * q | |
| if cfg > 0: | |
| token = generated[:, slot:slot + 1].float() | |
| network_prefix[:, slot:slot + 1] = torch.cat([token, token]) | |
| if verbose and (step + 1) % 128 == 0: | |
| print(f' generated {step + 1}/{steps}', flush=True) | |
| finally: | |
| source_cache.delete() | |
| target_cache.delete() | |
| if not torch.isfinite(generated).all(): | |
| raise FloatingPointError('Non-finite deepest edited state; reduce alpha') | |
| current = top.permutation(generated, inverse=True).float() | |
| for index in reversed(range(len(model.blocks) - 1)): | |
| if verbose: | |
| print(f' shallow inverse block={index + 1}/{len(model.blocks) - 1}', flush=True) | |
| cache = KVCache() | |
| try: | |
| current = model.blocks[index].reverse( | |
| current, y=None, guidance=0, rope=model.feat_rope, kv_cache=cache) | |
| finally: | |
| cache.delete() | |
| if not torch.isfinite(current).all(): | |
| raise FloatingPointError(f'Non-finite shallow inverse at block {index}') | |
| edited = model.unpatchify(current) | |
| artifacts = {'u_source': source_latent, 'u_edit': edited, 'h_source': original, | |
| 'z_source': noise, 'h_edit': generated, 'd': text_delta, 'b': prefix_delta, | |
| 'd0': fixed_text_delta, 'q': interaction_delta} | |
| report = { | |
| 'alpha': alpha, 'beta': beta, 'gamma': gamma, 'cfg': cfg, 'num_blocks': len(model.blocks), | |
| 'source_encoder': 'closed-loop' if cfg > 0 else 'parallel', | |
| 'affine_precision': 'fp64' if cfg > 0 else 'fp32', 'z_dtype': str(noise.dtype), | |
| 'top_state_spatial_shape': list(source_state.shape), | |
| 'token_shape': list(original.shape), 'token_order': 'deepest block autoregressive order', | |
| 'seq_order': model.seq_order, | |
| 'text_delta_rms': text_delta.double().square().mean().sqrt().item(), | |
| 'prefix_delta_rms': prefix_delta.double().square().mean().sqrt().item(), | |
| 'fixed_text_delta_rms': fixed_text_delta.double().square().mean().sqrt().item(), | |
| 'interaction_delta_rms': interaction_delta.double().square().mean().sqrt().item(), | |
| 'top_displacement_rms': (generated - original).double().square().mean().sqrt().item(), | |
| 'latent_displacement_rms': (edited - source_latent).double().square().mean().sqrt().item(), | |
| 'latent_displacement_max_abs': (edited - source_latent).abs().max().item(), | |
| } | |
| if cfg > 0: | |
| artifacts['h_reference'] = reference_state | |
| report['reference_reconstruction_max_abs'] = (reference_state - original.double()).abs().max().item() | |
| report['reference_feedback_max_abs'] = (reference_state.float() - reference_prefix).abs().max().item() | |
| return edited, artifacts, report | |
| def parse_args(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--image-path', type=Path, help='Omit to use PIE-Bench/PIE-Bench++') | |
| parser.add_argument('--source-prompt') | |
| parser.add_argument('--target-prompt') | |
| parser.add_argument('--dataset', type=Path, default=DEFAULT_DATASET, | |
| help='PIE-Bench root with mapping_file.json and annotation_images/, or PIE-Bench++ Parquet root') | |
| parser.add_argument('--category', action='append', help='Category directory name; repeatable') | |
| parser.add_argument('--image-id', type=int, action='append') | |
| parser.add_argument('--start-index', type=int, default=0) | |
| parser.add_argument('--max-samples', type=int, default=4, help='PIE only; 0: all selected images') | |
| parser.add_argument('--comparison-samples', type=int, default=4, | |
| help='Number of first source/editing pairs in comparison.png') | |
| parser.add_argument('--alpha', type=float, default=1.0, help='Text change weight, >= 0') | |
| parser.add_argument('--beta', type=float, default=0.5, help='Prefix change weight, in [0, 1]') | |
| parser.add_argument('--gamma', type=float, default=1.0, | |
| help='Interaction retention, in [0, 1]; 1 preserves original SADAE') | |
| parser.add_argument('--cfg', type=float, default=0.0, | |
| help='CFG strength, >= 0; positive values use closed-loop encoding and FP64 affines') | |
| parser.add_argument('--training-noise', action='store_true', | |
| help='Add checkpoint training noise before NF editing and self-denoise once before decode') | |
| parser.add_argument('--skip-metrics', action='store_true', | |
| help='Skip automatic PIE-Bench evaluation after image generation') | |
| parser.add_argument('--metrics-device', choices=('cpu', 'cuda'), default='cuda', | |
| help='Device for PIE-Bench evaluation (default: cuda)') | |
| parser.add_argument('--output-dir', type=Path, default=ROOT / 'result/nf_source_anchored_decoupled_affine', | |
| help='Must not already exist') | |
| parser.add_argument('--model-config-path', type=Path, default=ROOT / 'configs/starflow_3B_t2i_256x256.yaml') | |
| parser.add_argument('--checkpoint-path', type=Path, default=ROOT / 'ckpts/starflow_3B_t2i_256x256.pth') | |
| parser.add_argument('--seed', type=int, default=999) | |
| cli = parser.parse_args() | |
| cli.precision = 'fp32' | |
| if not math.isfinite(cli.alpha) or cli.alpha < 0: | |
| parser.error('alpha must be finite and nonnegative') | |
| if not math.isfinite(cli.beta) or not 0 <= cli.beta <= 1: | |
| parser.error('beta must be finite and in [0, 1]') | |
| if not math.isfinite(cli.gamma) or not 0 <= cli.gamma <= 1: | |
| parser.error('gamma must be finite and in [0, 1]') | |
| if not math.isfinite(cli.cfg) or cli.cfg < 0: | |
| parser.error('cfg must be finite and nonnegative') | |
| if min(cli.start_index, cli.max_samples) < 0 or (cli.image_id and min(cli.image_id) < 0): | |
| parser.error('Indices and sample counts must be nonnegative') | |
| if cli.comparison_samples < 1: | |
| parser.error('comparison-samples must be positive') | |
| if cli.image_path is not None: | |
| if not cli.image_path.is_file(): | |
| parser.error('--image-path must be an existing file') | |
| if not cli.source_prompt or not cli.source_prompt.strip() or not cli.target_prompt or not cli.target_prompt.strip(): | |
| parser.error('Single-image mode requires nonempty source and target prompts') | |
| if cli.category or cli.image_id or cli.start_index or cli.max_samples != 4: | |
| parser.error('PIE selection options cannot be combined with --image-path') | |
| elif cli.source_prompt is not None or cli.target_prompt is not None: | |
| parser.error('Prompt overrides require --image-path') | |
| for name in ('image_path', 'dataset', 'output_dir', 'model_config_path', 'checkpoint_path'): | |
| value = getattr(cli, name) | |
| if value is not None: | |
| setattr(cli, name, value.resolve()) | |
| return cli | |
| def iter_inputs(cli): | |
| if cli.image_path is not None: | |
| yield {'category': 'single', 'id': cli.image_path.stem, | |
| 'image_bytes': cli.image_path.read_bytes(), | |
| 'source_prompt': cli.source_prompt.strip(), 'target_prompt': cli.target_prompt.strip()} | |
| return | |
| mapping_path = cli.dataset / 'mapping_file.json' | |
| original_pie = mapping_path.is_file() | |
| if original_pie: | |
| mapping = json.loads(mapping_path.read_text()) | |
| categories = {Path(row['image_path']).parts[0] for row in mapping.values()} | |
| rows = ((Path(row['image_path']).parts[0], { | |
| 'id': image_id, 'image_path': row['image_path'], | |
| 'source_prompt': row['original_prompt'], 'target_prompt': row['editing_prompt'], | |
| 'mask': row['mask'], | |
| }) for image_id, row in mapping.items()) | |
| else: | |
| import pyarrow.parquet as pq | |
| paths = sorted(cli.dataset.glob('*/*.parquet')) | |
| if not paths: | |
| raise FileNotFoundError(f'No PIE-Bench mapping_file.json or PIE-Bench++ Parquet files under {cli.dataset}') | |
| categories = {path.parent.name for path in paths} | |
| columns = ['image', 'id', 'source_prompt', 'target_prompt'] | |
| if not cli.skip_metrics: | |
| columns.append('mask') | |
| rows = ((path.parent.name, row) for path in paths | |
| if not cli.category or path.parent.name in cli.category | |
| for batch in pq.ParquetFile(path).iter_batches(batch_size=64, columns=columns) | |
| for row in batch.to_pylist()) | |
| if cli.category and (unknown := set(cli.category) - categories): | |
| raise ValueError(f'Unknown PIE categories: {sorted(unknown)}') | |
| index = 0 | |
| requested, found = set(cli.image_id or []), set() | |
| for category, row in rows: | |
| if cli.category and category not in cli.category: | |
| continue | |
| index += 1 | |
| if index <= cli.start_index or (requested and int(row['id']) not in requested): | |
| continue | |
| found.add(int(row['id'])) | |
| image_bytes = ((cli.dataset / 'annotation_images' / row['image_path']).read_bytes() | |
| if original_pie else row['image']['bytes']) | |
| yield {'category': category, 'id': str(row['id']), 'image_bytes': image_bytes, | |
| 'source_prompt': row['source_prompt'].replace('[', '').replace(']', '').strip(), | |
| 'target_prompt': row['target_prompt'].replace('[', '').replace(']', '').strip(), | |
| 'pie_mask': row.get('mask')} | |
| if requested - found: | |
| raise ValueError(f'IDs missing after filters: {sorted(requested - found)}') | |
| def preprocess_image(image_bytes, image_size): | |
| from PIL import Image, ImageOps | |
| import torchvision.transforms as transforms | |
| with Image.open(BytesIO(image_bytes)) 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).unsqueeze(0) | |
| def save_image(tensor, path): | |
| from PIL import Image | |
| if not torch.isfinite(tensor).all(): | |
| raise FloatingPointError(f'Non-finite decoded image: {path}') | |
| path.parent.mkdir(parents=True, exist_ok=True) | |
| pixels = (tensor[0].detach().float().cpu().clamp(-1, 1) + 1) * 127.5 | |
| Image.fromarray(pixels.round().byte().permute(1, 2, 0).numpy()).save(path) | |
| def main(): | |
| cli = parse_args() | |
| rank = int(os.environ.get('RANK', '0')) | |
| world_size = int(os.environ.get('WORLD_SIZE', '1')) | |
| if cli.output_dir.exists(): | |
| raise FileExistsError(f'Choose a new --output-dir: {cli.output_dir}') | |
| inputs = iter_inputs(cli) | |
| if cli.image_id: | |
| inputs = iter(list(inputs)) | |
| if cli.image_path is None and cli.max_samples: | |
| inputs = islice(inputs, cli.max_samples) | |
| first = next(inputs, None) | |
| if first is None: | |
| raise ValueError('No images selected') | |
| if not torch.cuda.is_available(): | |
| raise RuntimeError('StarFlow 3B editing requires a CUDA GPU') | |
| from pie_bench_nf_components import load_components | |
| from utils import encode_text | |
| os.chdir(ROOT) | |
| args, model, vae, tokenizer, text_encoder, dist, device = load_components(cli) | |
| if cli.training_noise: | |
| from pie_bench_nf_components import add_training_noise | |
| from utils import self_denoise | |
| input_noise_std = args.noise_std if cli.training_noise else 0.0 | |
| for component in (model, vae, text_encoder): | |
| component.eval().requires_grad_(False) | |
| if rank == 0: | |
| cli.output_dir.mkdir(parents=True, exist_ok=False) | |
| if dist.distributed: | |
| dist.barrier() | |
| run_config = {key: str(value) if isinstance(value, Path) else value for key, value in vars(cli).items()} | |
| reference_name = 'h_reference' if cli.cfg > 0 else 'h_source' | |
| run_config.update(method='SADAE', method_version=2, cfg=cli.cfg, spatial_mask=False, training_noise=cli.training_noise, | |
| self_denoising_steps=int(cli.training_noise), vae_latent='posterior mode', nf_precision='fp32', | |
| source_encoder='closed-loop' if cli.cfg > 0 else 'parallel', | |
| affine_precision='fp64' if cli.cfg > 0 else 'fp32', | |
| z_dtype='torch.float64' if cli.cfg > 0 else 'torch.float32', | |
| torch_version=torch.__version__, gpu=torch.cuda.get_device_name(device), | |
| update=f'h_edit = {reference_name} + alpha * d0 + beta * (S - {reference_name}) + alpha * gamma * ((T - S) - d0)') | |
| if cli.training_noise: | |
| run_config['input_noise_std'] = input_noise_std | |
| if rank == 0: | |
| run_config['world_size'] = world_size | |
| (cli.output_dir / 'run_config.json').write_text(json.dumps(run_config, indent=2, ensure_ascii=False) + '\n') | |
| previous_tf32 = torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| torch.backends.cudnn.allow_tf32 = False | |
| reports = [] | |
| indexed_reports = [] | |
| evaluate_metrics = cli.image_path is None and not cli.skip_metrics | |
| evaluation_masks = [] | |
| if rank == 0 and cli.image_path is not None and not cli.skip_metrics: | |
| print('PIE-Bench metrics skipped: single-image mode has no annotated editing mask', flush=True) | |
| try: | |
| for index, item in enumerate(chain([first], inputs)): | |
| if index % world_size != rank: | |
| continue | |
| started = time.perf_counter() | |
| category, image_id = item['category'], item['id'] | |
| if not item['source_prompt'] or not item['target_prompt']: | |
| raise ValueError(f'Missing prompt: {category}/{image_id}') | |
| print(f'Processing {category}/{image_id}', flush=True) | |
| image = preprocess_image(item['image_bytes'], args.img_size * vae.downsample_factor).to(device) | |
| if evaluate_metrics: | |
| from pie_bench_metrics import preprocess_pie_mask | |
| evaluation_masks.append(preprocess_pie_mask( | |
| item['pie_mask'], item['image_bytes'], image.shape[-1])) | |
| with torch.autocast('cuda', dtype=torch.bfloat16): | |
| posterior = vae.vae.encode(image).latent_dist | |
| vae_latent = (posterior.mode() * vae.scaling_factor).detach() | |
| source_latent = vae_latent.float() | |
| prompts = [item['source_prompt'], item['target_prompt']] | |
| if cli.cfg > 0: | |
| prompts.append('') | |
| conditions = encode_text(text_encoder, tokenizer, prompts, args.txt_size, device, | |
| noise_std=input_noise_std if args.cond_noise_level else None).float() | |
| vae_only = vae.decode(vae_latent if cli.cfg > 0 else source_latent) | |
| nf_input = source_latent | |
| if cli.training_noise: | |
| item_seed = cli.seed + sum(ord(c) for c in category) + ( | |
| int(image_id) if image_id.isdigit() else sum(ord(c) for c in image_id)) | |
| noise_seed = item_seed + 1_000_003 | |
| nf_input = add_training_noise(source_latent, args, noise_seed) | |
| with torch.autocast('cuda', enabled=False): | |
| edited_latent, artifacts, report = edit_latent( | |
| model, nf_input, conditions[:1], conditions[1:2], cli.alpha, cli.beta, | |
| gamma=cli.gamma, cfg=cli.cfg, empty_condition=conditions[2:3] if cli.cfg > 0 else None) | |
| decode_latent = edited_latent | |
| if cli.training_noise: | |
| try: | |
| decode_latent = self_denoise( | |
| model, edited_latent.detach(), conditions[1:2], | |
| noise_std=input_noise_std, lr=1, steps=1) | |
| finally: | |
| model.eval() | |
| artifacts.update(u_source_clean=source_latent, u_edit_denoised=decode_latent) | |
| report.update(training_noise=True, input_noise_std=input_noise_std, | |
| noise_seed=noise_seed, self_denoising_steps=1) | |
| with torch.autocast('cuda', dtype=torch.bfloat16): | |
| edited = vae.decode(decode_latent.to(vae_latent.dtype) if cli.cfg > 0 else decode_latent) | |
| stem = Path(category) / image_id | |
| for kind, pixels in (('source', image), ('vae_only', vae_only), ('editing', edited)): | |
| save_image(pixels, cli.output_dir / kind / stem.with_name(stem.name + '.png')) | |
| for folder in ('states', 'metadata'): | |
| (cli.output_dir / folder / stem.parent).mkdir(parents=True, exist_ok=True) | |
| torch.save({name: value.detach().cpu() for name, value in artifacts.items()}, | |
| cli.output_dir / 'states' / stem.with_name(stem.name + '.pt')) | |
| report.update(category=category, id=image_id, source_prompt=item['source_prompt'], | |
| target_prompt=item['target_prompt'], | |
| vae_decode_dtype=str(vae_latent.dtype if cli.cfg > 0 else source_latent.dtype), | |
| decoded_vs_vae_rms=(edited - vae_only).double().square().mean().sqrt().item(), | |
| elapsed_seconds=time.perf_counter() - started) | |
| (cli.output_dir / 'metadata' / stem.with_name(stem.name + '.json')).write_text( | |
| json.dumps(report, indent=2, ensure_ascii=False, allow_nan=False) + '\n') | |
| reports.append(report) | |
| indexed_reports.append((index, report)) | |
| print(f" latent displacement={report['latent_displacement_rms']:.6g}; " | |
| f"elapsed={report['elapsed_seconds']:.1f}s", flush=True) | |
| if dist.distributed: | |
| gathered = [None] * world_size if rank == 0 else None | |
| torch.distributed.gather_object((indexed_reports, evaluation_masks), gathered, dst=0) | |
| # Torchmetrics must not synchronize with workers that have finished editing. | |
| torch.distributed.destroy_process_group() | |
| dist.distributed = False | |
| if rank != 0: | |
| return | |
| ordered = sorted( | |
| (index, report, masks[local_index] if evaluate_metrics else None) | |
| for rank_reports, masks in gathered | |
| for local_index, (index, report) in enumerate(rank_reports)) | |
| reports = [report for _, report, _ in ordered] | |
| evaluation_masks = [mask for _, _, mask in ordered] if evaluate_metrics else [] | |
| summary = {'count': len(reports), 'images': reports} | |
| summary_path = cli.output_dir / 'summary.json' | |
| summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False, allow_nan=False) + '\n') | |
| from PIL import Image, ImageDraw | |
| selected = reports[:cli.comparison_samples] | |
| image_size = args.img_size * vae.downsample_factor | |
| header_height = 32 | |
| comparison = Image.new('RGB', (2 * image_size, header_height + len(selected) * image_size), 'white') | |
| draw = ImageDraw.Draw(comparison) | |
| draw.text((8, 8), 'Source', fill='black') | |
| label = f'Editing (alpha={cli.alpha:g}, beta={cli.beta:g}, gamma={cli.gamma:g})' | |
| if cli.cfg > 0: | |
| label = f'Editing (a={cli.alpha:g}, b={cli.beta:g}, g={cli.gamma:g}, cfg={cli.cfg:g})' | |
| draw.text((image_size + 8, 8), label, fill='black') | |
| for row, report in enumerate(selected): | |
| stem = Path(report['category']) / report['id'] | |
| for column, kind in enumerate(('source', 'editing')): | |
| with Image.open(cli.output_dir / kind / stem.with_name(stem.name + '.png')) as pixels: | |
| comparison.paste(pixels, (column * image_size, header_height + row * image_size)) | |
| comparison.save(cli.output_dir / 'comparison.png') | |
| if evaluate_metrics: | |
| from pie_bench_metrics import evaluate_saved_images | |
| del model, vae, text_encoder, component, posterior | |
| torch.cuda.empty_cache() | |
| summary['pie_bench_metrics'] = evaluate_saved_images( | |
| cli.output_dir, reports, evaluation_masks, cli.metrics_device) | |
| summary_path.write_text(json.dumps(summary, indent=2, ensure_ascii=False, allow_nan=False) + '\n') | |
| finally: | |
| torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = previous_tf32 | |
| if dist.distributed: | |
| torch.distributed.destroy_process_group() | |
| dist.distributed = False | |
| print(f'Finished {len(reports)} images; output={cli.output_dir}', flush=True) | |
| if __name__ == '__main__': | |
| main() | |