Download scripts/nf_likelihood_ratio_editing.py from Lingmin-Ran/SADAE: direct link, hf CLI and curl.
- Browser
- Download file 27.4 kB
-
https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/nf_likelihood_ratio_editing.py
- Command line
-
hf download hf://Lingmin-Ran/SADAE/scripts/nf_likelihood_ratio_editing.py
-
curl -L -o nf_likelihood_ratio_editing.py https://huggingface.co/Lingmin-Ran/SADAE/resolve/main/scripts/nf_likelihood_ratio_editing.py
27.4 kB
| #!/usr/bin/env python3 | |
| """Source-anchored editing with the exact conditional NF likelihood ratio. | |
| Optimizes the scaled VAE latent using summed densities, gradient descent, | |
| and Armijo backtracking. No NF inverse, CFG, masks, or parameter training. | |
| """ | |
| import argparse | |
| from dataclasses import asdict, dataclass | |
| 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 | |
| from torch.utils.checkpoint import checkpoint | |
| ROOT = Path(__file__).resolve().parents[1] | |
| sys.path.insert(0, str(ROOT)) | |
| DEFAULT_DATASET = Path('/mnt/bn/jiangzhongtao/lingmin/dataset/PIE_Bench_pp') | |
| class SolverConfig: | |
| kappa: float = 100.0 | |
| penalty_weight: float = 1.0 | |
| target_gain: float | None = None | |
| target_penalty_weight: float = 1.0 | |
| target_tol: float = 1e-4 | |
| max_step_rms: float = 0.0 | |
| max_steps: int = 50 | |
| step_size: float = 1e-3 | |
| backtrack_factor: float = 0.5 | |
| armijo: float = 1e-4 | |
| max_backtracks: int = 20 | |
| min_step_size: float = 1e-12 | |
| loss_tol: float = 1e-6 | |
| grad_tol: float = 1e-5 | |
| ratio_tol: float = 1e-4 | |
| gradient_checkpointing: bool = True | |
| def conditional_density(model, latent, condition, gradient_checkpointing=False): | |
| def forward_density(u, c): | |
| z, _, _, logdets = model(u, c) | |
| flat_z = z.flatten(1).double() | |
| prior_nll = 0.5 * flat_z.square().sum(1) | |
| prior_nll = prior_nll + 0.5 * flat_z.shape[1] * math.log(2 * math.pi) | |
| log_abs_det = torch.zeros_like(prior_nll) | |
| for logdet in logdets: | |
| log_abs_det = log_abs_det + logdet.flatten(1).double().sum(1) | |
| return torch.stack((log_abs_det - prior_nll, prior_nll, log_abs_det), dim=1) | |
| if gradient_checkpointing and torch.is_grad_enabled() and latent.requires_grad: | |
| # Checkpoint the density call while retaining eval mode and input gradients. | |
| return checkpoint(forward_density, latent, condition, use_reentrant=False) | |
| return forward_density(latent, condition) | |
| def density_gradients(model, latent, source_condition, target_condition, gradient_checkpointing): | |
| gradients = [] | |
| # Release each condition's graph before building the next one. | |
| for condition in (source_condition, target_condition): | |
| u = latent.detach().requires_grad_(True) | |
| density = conditional_density(model, u, condition, gradient_checkpointing) | |
| condition_gradient, = torch.autograd.grad(density[:, 0].sum(), u) | |
| gradients.append(condition_gradient.detach()) | |
| return gradients | |
| def optimize_latent(model, source_latent, source_condition, target_condition, config, | |
| same_condition=False, verbose=True): | |
| if source_latent.shape[0] != 1: | |
| raise ValueError('Optimize one image at a time so line search and selection are per image') | |
| source = source_latent.detach().float().clone() | |
| current = source.clone() | |
| nf_forward_calls = 0 | |
| target_enabled = config.target_gain is not None | |
| initial_target = initial_source = None | |
| rejections = {'armijo': 0, 'target_floor': 0, 'step_limit': 0} | |
| def evaluate(u, initial_ratio, threshold, step): | |
| nonlocal nf_forward_calls | |
| if not torch.isfinite(u).all(): | |
| return None | |
| source_scores = conditional_density(model, u, source_condition)[0] | |
| target_scores = conditional_density(model, u, target_condition)[0] | |
| nf_forward_calls += 2 | |
| cost = 0.5 * (u.double() - source.double()).square().sum().item() | |
| values = torch.cat((source_scores, target_scores)) | |
| if not torch.isfinite(values).all() or not math.isfinite(cost): | |
| return None | |
| ell_s, prior_s, logdet_s, ell_t, prior_t, logdet_t = values.tolist() | |
| ratio = ell_t - ell_s | |
| gap = max(0.0, threshold - ratio) if threshold is not None else config.kappa | |
| target_delta = ell_t - initial_target if initial_target is not None else 0.0 | |
| target_gap = max(0.0, config.target_gain - target_delta) if target_enabled else 0.0 | |
| loss = cost + 0.5 * config.penalty_weight * gap ** 2 | |
| loss += 0.5 * config.target_penalty_weight * target_gap ** 2 | |
| if not math.isfinite(loss): | |
| return None | |
| return { | |
| 'step': step, 'source_log_density': ell_s, 'target_log_density': ell_t, | |
| 'source_prior_nll': prior_s, 'target_prior_nll': prior_t, | |
| 'source_log_abs_det': logdet_s, 'target_log_abs_det': logdet_t, | |
| 'ratio': ratio, 'delta_ratio': ratio - initial_ratio if initial_ratio is not None else 0.0, | |
| 'cost': cost, 'violation': gap, 'loss': loss, | |
| 'ratio_violation': gap, 'target_violation': target_gap, | |
| 'delta_source_log_density': ell_s - initial_source if initial_source is not None else 0.0, | |
| 'delta_target_log_density': target_delta, | |
| 'ratio_feasible': gap <= config.ratio_tol, | |
| 'target_feasible': target_gap <= config.target_tol, | |
| 'target_floor_satisfied': not target_enabled or target_delta >= -config.target_tol, | |
| 'feasible': gap <= config.ratio_tol and target_gap <= config.target_tol, | |
| } | |
| initial = evaluate(current, None, None, 0) | |
| if initial is None: | |
| raise FloatingPointError('Non-finite source density: no valid initial candidate') | |
| initial_ratio = initial['ratio'] | |
| initial_target = initial['target_log_density'] | |
| initial_source = initial['source_log_density'] | |
| threshold = initial_ratio + config.kappa | |
| state = initial.copy() | |
| trajectory = [state] | |
| best_loss = (current.clone(), state.copy()) | |
| best_feasible = (current.clone(), state.copy()) if state['feasible'] else None | |
| stop_reason = 'max_steps' | |
| if same_condition: | |
| stop_reason = 'same_condition_infeasible' if config.kappa > 0 else 'same_condition_no_edit' | |
| elif config.kappa == 0 and (not target_enabled or config.target_gain == 0): | |
| stop_reason = 'zero_kappa' | |
| else: | |
| for _ in range(config.max_steps): | |
| gs, gt = density_gradients(model, current, source_condition, target_condition, | |
| config.gradient_checkpointing) | |
| nf_forward_calls += 2 | |
| # All terms use sums and the original source anchor throughout. | |
| gradient = (current - source) - config.penalty_weight * state['violation'] * (gt - gs) | |
| if target_enabled: | |
| gradient -= config.target_penalty_weight * state['target_violation'] * gt | |
| if not torch.isfinite(gradient).all(): | |
| stop_reason = 'nonfinite_gradient' | |
| break | |
| norm_sq = gradient.double().square().sum().item() | |
| state['gradient_norm'] = math.sqrt(norm_sq) | |
| state['target_directional_derivative'] = -(gradient.double() * gt.double()).sum().item() | |
| state['ratio_directional_derivative'] = -(gradient.double() * (gt - gs).double()).sum().item() | |
| if state['gradient_norm'] <= config.grad_tol: | |
| stop_reason = 'gradient_tolerance' | |
| break | |
| eta = config.step_size | |
| if config.max_step_rms: | |
| eta = min(eta, config.max_step_rms * math.sqrt(source.numel() / norm_sq)) | |
| step_limited = eta < config.step_size | |
| accepted = False | |
| step_rejections = {'armijo': 0, 'target_floor': 0, 'step_limit': 0} | |
| trials = 0 | |
| for backtracks in range(config.max_backtracks + 1): | |
| if eta < config.min_step_size: | |
| break | |
| trial = current - eta * gradient | |
| step_rms = (trial.double() - current.double()).square().mean().sqrt().item() | |
| if config.max_step_rms and step_rms > config.max_step_rms * (1 + 1e-6): | |
| rejections['step_limit'] += 1 | |
| step_rejections['step_limit'] += 1 | |
| eta *= config.backtrack_factor | |
| continue | |
| candidate = evaluate(trial, initial_ratio, threshold, state['step'] + 1) | |
| trials += 1 | |
| if candidate is None: | |
| stop_reason = 'nonfinite_trial' | |
| break | |
| armijo_ok = (candidate['loss'] < state['loss'] and | |
| candidate['loss'] <= state['loss'] - config.armijo * eta * norm_sq) | |
| floor_ok = candidate['target_floor_satisfied'] | |
| if armijo_ok and floor_ok: | |
| accepted = True | |
| break | |
| if not armijo_ok: | |
| rejections['armijo'] += 1 | |
| step_rejections['armijo'] += 1 | |
| if not floor_ok: | |
| rejections['target_floor'] += 1 | |
| step_rejections['target_floor'] += 1 | |
| eta *= config.backtrack_factor | |
| if not accepted: | |
| if stop_reason != 'nonfinite_trial': | |
| stop_reason = ('target_floor_blocked' if trials and step_rejections['target_floor'] == trials | |
| else 'line_search_failed') | |
| break | |
| loss_change = state['loss'] - candidate['loss'] | |
| current = trial.detach() | |
| state = candidate | |
| state.update(step_size=eta, backtracks=backtracks, loss_decrease=loss_change, | |
| step_rms=step_rms, step_limited=step_limited, line_search_rejections=step_rejections) | |
| trajectory.append(state) | |
| if state['loss'] < best_loss[1]['loss']: | |
| best_loss = (current.clone(), state.copy()) | |
| if state['feasible'] and (best_feasible is None or state['cost'] < best_feasible[1]['cost']): | |
| best_feasible = (current.clone(), state.copy()) | |
| if verbose: | |
| print(f" step={state['step']} L={state['loss']:.6g} " | |
| f"delta_R={state['delta_ratio']:.6g} C={state['cost']:.6g} " | |
| f"gap={state['violation']:.6g} eta={eta:.3g} " | |
| f"target_gain={state['delta_target_log_density']:.6g} " | |
| f"target_gap={state['target_violation']:.6g} " | |
| f"step_rms={step_rms:.3g} backtracks={backtracks}", flush=True) | |
| if loss_change <= config.loss_tol: | |
| stop_reason = 'loss_tolerance' | |
| break | |
| selected_latent, final = best_feasible if best_feasible is not None else best_loss | |
| final = final.copy() | |
| final['delta_source_log_density'] = final['source_log_density'] - initial['source_log_density'] | |
| final['delta_target_log_density'] = final['target_log_density'] - initial['target_log_density'] | |
| result = { | |
| 'initial': initial, 'final': final, 'threshold': threshold, | |
| 'target_constraint_enabled': target_enabled, | |
| 'target_threshold': initial_target + config.target_gain if target_enabled else None, | |
| 'latent_dim': source.numel(), 'stop_reason': stop_reason, | |
| 'selection': 'nearest_feasible' if best_feasible is not None else 'lowest_loss_infeasible', | |
| 'constraint_satisfied': final['feasible'], | |
| 'ratio_constraint_satisfied': final['ratio_feasible'], | |
| 'target_constraint_satisfied': final['target_feasible'] if target_enabled else None, | |
| 'strict_constraint_satisfied': (final['ratio'] >= threshold and | |
| (not target_enabled or final['delta_target_log_density'] >= config.target_gain)), | |
| 'selected_step': final['step'], 'accepted_steps': trajectory[-1]['step'], | |
| 'nf_forward_calls': nf_forward_calls, | |
| 'line_search_rejections': rejections, | |
| 'forward_calls_exclude_checkpoint_recomputation': True, | |
| } | |
| return selected_latent.detach(), result, trajectory | |
| def parse_args(): | |
| parser = argparse.ArgumentParser(description=__doc__) | |
| parser.add_argument('--image-path', type=Path, help='Single image; omit to use PIE-Bench++') | |
| parser.add_argument('--source-prompt') | |
| parser.add_argument('--target-prompt') | |
| parser.add_argument('--dataset', type=Path, default=DEFAULT_DATASET) | |
| parser.add_argument('--category', action='append', help='Repeatable PIE category filter') | |
| parser.add_argument('--image-id', type=int, action='append', help='Repeatable PIE image ID filter') | |
| parser.add_argument('--start-index', type=int, default=0) | |
| parser.add_argument('--max-samples', '--max-sample', type=int, default=0, help='0: all selected images') | |
| parser.add_argument('--output-dir', type=Path, default=ROOT / 'result/nf_likelihood_ratio', | |
| help='Must not already exist') | |
| 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('--vae-latent', choices=('mean', 'sample'), default='mean') | |
| parser.add_argument('--input-noise-std', type=float, default=0.0) | |
| parser.add_argument('--kappa', type=float, default=SolverConfig.kappa, help='Evidence growth in summed nats') | |
| parser.add_argument('--penalty-weight', type=float, default=SolverConfig.penalty_weight, help='lambda') | |
| parser.add_argument('--target-gain', type=float, default=None, | |
| help='Minimum target log-density gain in summed nats; omit to disable, 0 enables a floor') | |
| parser.add_argument('--target-penalty-weight', type=float, default=SolverConfig.target_penalty_weight) | |
| parser.add_argument('--target-tol', type=float, default=SolverConfig.target_tol, | |
| help='Target feasibility and initialization density-floor tolerance, in nats') | |
| parser.add_argument('--max-step-rms', type=float, default=SolverConfig.max_step_rms, | |
| help='Maximum RMS latent displacement per update; 0 disables the limit') | |
| parser.add_argument('--max-steps', type=int, default=SolverConfig.max_steps) | |
| parser.add_argument('--step-size', type=float, default=SolverConfig.step_size) | |
| parser.add_argument('--backtrack-factor', type=float, default=SolverConfig.backtrack_factor) | |
| parser.add_argument('--armijo', type=float, default=SolverConfig.armijo) | |
| parser.add_argument('--max-backtracks', type=int, default=SolverConfig.max_backtracks, | |
| help='Maximum shrink operations per update (trials = this + 1)') | |
| parser.add_argument('--min-step-size', type=float, default=SolverConfig.min_step_size) | |
| parser.add_argument('--loss-tol', type=float, default=SolverConfig.loss_tol, help='Absolute loss change') | |
| parser.add_argument('--grad-tol', type=float, default=SolverConfig.grad_tol) | |
| parser.add_argument('--ratio-tol', type=float, default=SolverConfig.ratio_tol, help='Feasibility tolerance in nats') | |
| parser.add_argument('--no-gradient-checkpointing', dest='gradient_checkpointing', action='store_false') | |
| cli = parser.parse_args() | |
| cli.precision = 'fp32' | |
| 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-prompt and --target-prompt') | |
| if cli.category or cli.image_id or cli.start_index or cli.max_samples: | |
| parser.error('PIE selection options cannot be used with --image-path') | |
| elif cli.source_prompt is not None or cli.target_prompt is not None: | |
| parser.error('Prompt overrides require --image-path; PIE mode uses dataset prompts') | |
| positive = ('penalty_weight', 'target_penalty_weight', 'step_size', 'min_step_size') | |
| nonnegative = ('kappa', 'input_noise_std', 'loss_tol', 'grad_tol', 'ratio_tol', 'target_tol', 'max_step_rms') | |
| for name in positive + nonnegative + ('backtrack_factor', 'armijo'): | |
| if not math.isfinite(getattr(cli, name)): | |
| parser.error(f'--{name.replace("_", "-")} must be finite') | |
| if any(getattr(cli, name) <= 0 for name in positive): | |
| parser.error('Penalty weights, step-size and min-step-size must be positive') | |
| if any(getattr(cli, name) < 0 for name in nonnegative): | |
| parser.error('kappa, input-noise-std, max-step-rms and tolerances must be nonnegative') | |
| if cli.target_gain is not None and (not math.isfinite(cli.target_gain) or cli.target_gain < 0): | |
| parser.error('target-gain must be finite and nonnegative') | |
| if not 0 < cli.backtrack_factor < 1 or not 0 < cli.armijo < 1: | |
| parser.error('backtrack-factor and armijo must be strictly between 0 and 1') | |
| if cli.min_step_size > cli.step_size: | |
| parser.error('min-step-size must not exceed step-size') | |
| if min(cli.max_steps, cli.max_backtracks, cli.start_index, cli.max_samples) < 0: | |
| parser.error('Step/sample counts and start-index must be nonnegative') | |
| if cli.image_id and min(cli.image_id) < 0: | |
| parser.error('image-id must be nonnegative') | |
| if int(os.environ.get('WORLD_SIZE', '1')) != 1: | |
| parser.error('Use one process/GPU') | |
| 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, Path(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 | |
| import pyarrow.parquet as pq | |
| paths = sorted(cli.dataset.glob('*/*.parquet')) | |
| categories = {path.parent.name for path in paths} | |
| if cli.category: | |
| unknown = set(cli.category) - categories | |
| if unknown: | |
| raise ValueError(f'Unknown categories: {sorted(unknown)}; available: {sorted(categories)}') | |
| paths = [path for path in paths if path.parent.name in cli.category] | |
| if not paths: | |
| raise FileNotFoundError(f'No PIE-Bench++ Parquet files under {cli.dataset}') | |
| index = 0 | |
| requested = set(cli.image_id or []) | |
| found = set() | |
| for path in paths: | |
| parquet = pq.ParquetFile(path) | |
| for batch in parquet.iter_batches(batch_size=64, columns=['image', 'id', 'source_prompt', 'target_prompt']): | |
| for row in batch.to_pylist(): | |
| index += 1 | |
| if index <= cli.start_index or (requested and int(row['id']) not in requested): | |
| continue | |
| found.add(int(row['id'])) | |
| yield {'category': path.parent.name, 'id': str(row['id']), | |
| 'image_bytes': row['image']['bytes'], | |
| 'source_prompt': row['source_prompt'].strip(), | |
| 'target_prompt': row['target_prompt'].replace('[', '').replace(']', '').strip()} | |
| if requested - found: | |
| raise ValueError(f'IDs missing after category/start-index 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() | |
| 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.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) | |
| for component in (model, vae, text_encoder): | |
| component.eval().requires_grad_(False) | |
| config = SolverConfig(**{key: getattr(cli, key) for key in SolverConfig.__dataclass_fields__}) | |
| 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(solver=asdict(config), nf_precision='fp32', density_reduction='sum', | |
| density_accumulation='fp64', guidance=0, torch_version=torch.__version__, | |
| gpu=torch.cuda.get_device_name(device), | |
| density_space='scaled VAE latent before decoding', | |
| preprocessing='resize shortest side then center crop to model image 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 = [] | |
| try: | |
| for item in chain([first], inputs): | |
| 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_size = args.img_size * vae.downsample_factor | |
| image = preprocess_image(item['image_bytes'], image_size).to(device) | |
| 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)) | |
| generator = torch.Generator(device=device).manual_seed(item_seed) | |
| with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16): | |
| posterior = vae.vae.encode(image).latent_dist | |
| encoded = posterior.sample(generator=generator) if cli.vae_latent == 'sample' else posterior.mode() | |
| encoded = encoded * vae.scaling_factor | |
| conditions = encode_text(text_encoder, tokenizer, | |
| [item['source_prompt'], item['target_prompt']], args.txt_size, device).float() | |
| vae_only = vae.decode(encoded) | |
| source_latent = encoded.detach().float() | |
| if cli.input_noise_std: | |
| source_latent = source_latent + cli.input_noise_std * torch.randn( | |
| source_latent.shape, generator=generator, device=device, dtype=torch.float32) | |
| same_condition = (item['source_prompt'] == item['target_prompt'] or | |
| torch.equal(conditions[:1], conditions[1:])) | |
| with torch.autocast('cuda', enabled=False): | |
| edited_latent, result, trajectory = optimize_latent( | |
| model, source_latent, conditions[:1], conditions[1:], config, same_condition) | |
| with torch.no_grad(), torch.autocast('cuda', dtype=torch.bfloat16): | |
| edited = image if same_condition else vae.decode(edited_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 ('metadata', 'trajectory', 'latents'): | |
| (cli.output_dir / folder / stem.parent).mkdir(parents=True, exist_ok=True) | |
| result.update(category=category, id=image_id, source_prompt=item['source_prompt'], | |
| target_prompt=item['target_prompt'], item_seed=item_seed, | |
| identity_bypass=same_condition, elapsed_seconds=time.perf_counter() - started) | |
| (cli.output_dir / 'metadata' / stem.with_name(stem.name + '.json')).write_text( | |
| json.dumps(result, indent=2, ensure_ascii=False, allow_nan=False) + '\n') | |
| with (cli.output_dir / 'trajectory' / stem.with_name(stem.name + '.jsonl')).open('x') as handle: | |
| for state in trajectory: | |
| handle.write(json.dumps(state, allow_nan=False) + '\n') | |
| torch.save({'source_latent': source_latent.cpu(), 'edited_latent': edited_latent.cpu()}, | |
| cli.output_dir / 'latents' / stem.with_name(stem.name + '.pt')) | |
| reports.append({'category': category, 'id': image_id, **result['final'], | |
| 'stop_reason': result['stop_reason']}) | |
| print(f" selected step={result['selected_step']} feasible={result['constraint_satisfied']} " | |
| f"stop={result['stop_reason']}", flush=True) | |
| finally: | |
| torch.backends.cuda.matmul.allow_tf32, torch.backends.cudnn.allow_tf32 = previous_tf32 | |
| if dist.distributed: | |
| torch.distributed.destroy_process_group() | |
| summary = {'count': len(reports), 'feasible_count': sum(report['feasible'] for report in reports), | |
| 'target_constraint_enabled': config.target_gain is not None, | |
| 'ratio_feasible_count': sum(report['ratio_feasible'] for report in reports), | |
| 'target_feasible_count': (sum(report['target_feasible'] for report in reports) | |
| if config.target_gain is not None else None), | |
| 'mean_delta_ratio': sum(report['delta_ratio'] for report in reports) / len(reports), | |
| 'mean_violation': sum(report['violation'] for report in reports) / len(reports), | |
| 'mean_target_violation': sum(report['target_violation'] for report in reports) / len(reports), | |
| 'mean_delta_target_log_density': sum(report['delta_target_log_density'] for report in reports) / len(reports), | |
| 'mean_delta_source_log_density': sum(report['delta_source_log_density'] for report in reports) / len(reports), | |
| 'mean_cost': sum(report['cost'] for report in reports) / len(reports), 'images': reports} | |
| (cli.output_dir / 'summary.json').write_text(json.dumps(summary, indent=2, ensure_ascii=False, allow_nan=False) + '\n') | |
| print(f"Finished {len(reports)} images; feasible={summary['feasible_count']}/{len(reports)}; " | |
| f"output={cli.output_dir}", flush=True) | |
| if __name__ == '__main__': | |
| main() | |