Download eccv_2026_evalcode/upscale_pixelrush_sd.py from phuckstnk63/abcxyz: direct link, hf CLI and curl.
- Browser
- Download file 14.7 kB
-
https://huggingface.co/datasets/phuckstnk63/abcxyz/resolve/main/eccv_2026_evalcode/upscale_pixelrush_sd.py
- Command line
-
hf download hf://datasets/phuckstnk63/abcxyz/eccv_2026_evalcode/upscale_pixelrush_sd.py
-
curl -L -o upscale_pixelrush_sd.py https://huggingface.co/datasets/phuckstnk63/abcxyz/resolve/main/eccv_2026_evalcode/upscale_pixelrush_sd.py
14.7 kB
| import json | |
| import random | |
| import os | |
| import threading | |
| import yaml | |
| import torch.multiprocessing as mp | |
| from pathlib import Path | |
| from dataclasses import dataclass, asdict | |
| from typing import Optional | |
| import torch | |
| from PIL import Image | |
| import numpy as np | |
| import torchvision.transforms as transforms | |
| from torchvision.models import inception_v3 | |
| from scipy import linalg | |
| import scipy | |
| import torch.nn.functional as F | |
| import torch.nn as nn | |
| from torch.utils.data import Dataset, DataLoader | |
| import pickle | |
| from tqdm import tqdm | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| import einops | |
| from diffusers import StableDiffusionXLPipeline, FluxPipeline | |
| import sys | |
| sys.path.insert(0, "/lustre/scratch/client/movian/research/users/phuclh12/Code/minHiWave") | |
| from pipeline_swifthi import SwiftHiPipeline | |
| from pipeline_swifthi_sparse import SwiftHiPipeline as SwiftHiPipelineSparse | |
| from pipeline_sd_invsr import CustomSDPipeline | |
| from pipeline_sd_invsr_sparse import CustomSDPipeline as CustomSDPipelineSparse | |
| from pipeline_pixart_sigma import PixArtSigmaHiPipeline | |
| from utils import load_prompts | |
| class UpscaleConfig: | |
| """Configuration for upscaling pipeline.""" | |
| ddim_inv_to_step: int = 249 | |
| upscale_RGB: bool = False | |
| upscale_bridge: bool = True | |
| padding_anhtran: bool = True | |
| small_bridge: bool = False | |
| use_temporal_scaling: bool = False | |
| use_noise_injection: bool = False | |
| temperature: float = 0.7 | |
| user_define: float = 2.0 | |
| lambda_noise: float = 0.9 | |
| inv_sr_weight: Optional[float] = None | |
| renoise_inv: bool = False | |
| renoise_inv_step: int = 10 | |
| renoise_strategy: str = "aa" | |
| renoise_format: bool = False | |
| renoise_ema_beta: float = 0.7 | |
| def to_dict_sdxl(self): | |
| """ | |
| Convert to dict for SDXL pipeline (SwiftHiPipeline). | |
| Filters parameters accepted by hiwave_one_step in pipeline_swifthi.py | |
| """ | |
| sdxl_params = { | |
| "ddim_inv_to_step", | |
| "upscale_RGB", | |
| "upscale_bridge", | |
| "use_temporal_scaling", | |
| "temperature", | |
| "user_define", | |
| "use_noise_injection", | |
| "lambda_noise", | |
| "renoise_inv", | |
| "renoise_inv_step", | |
| "renoise_strategy", | |
| "renoise_format", | |
| "renoise_ema_beta", | |
| "padding_anhtran", | |
| "small_bridge", | |
| } | |
| return {k: v for k, v in asdict(self).items() if k in sdxl_params and v is not None} | |
| def to_dict_pixart_sigma(self): | |
| """ | |
| Convert to dict for PixArt Sigma pipeline (PixArtSigmaHiPipeline). | |
| Filters parameters accepted by hiwave_one_step in pipeline_swifthi.py | |
| """ | |
| pixart_sigma_params = { | |
| "ddim_inv_to_step", | |
| "upscale_RGB", | |
| "upscale_bridge", | |
| "use_temporal_scaling", | |
| "temperature", | |
| "user_define", | |
| "use_noise_injection", | |
| "lambda_noise", | |
| "renoise_inv", | |
| "renoise_inv_step", | |
| "renoise_strategy", | |
| "renoise_format", | |
| "renoise_ema_beta", | |
| "padding_anhtran", | |
| "small_bridge", | |
| } | |
| return {k: v for k, v in asdict(self).items() if k in pixart_sigma_params and v is not None} | |
| def to_dict_sd(self): | |
| """ | |
| Convert to dict for SD pipeline (CustomSDPipeline). | |
| Filters parameters accepted by hiwave_one_step in pipeline_sd_invsr.py | |
| """ | |
| sd_params = { | |
| "ddim_inv_to_step", | |
| "upscale_RGB", | |
| "upscale_bridge", | |
| "inv_sr_weight", | |
| "padding_anhtran", | |
| "small_bridge", | |
| "use_temporal_scaling", | |
| "temperature", | |
| "user_define", | |
| } | |
| return {k: v for k, v in asdict(self).items() if k in sd_params and v is not None} | |
| def to_dict(self): | |
| """Convert to dict, removing None values (generic fallback).""" | |
| return {k: v for k, v in asdict(self).items() if v is not None} | |
| def gen_1k_image( | |
| output_dir, | |
| prompt_file, | |
| use_flux_base: bool = False, | |
| ): | |
| if use_flux_base: | |
| pipe = FluxPipeline.from_pretrained( | |
| "/lustre/scratch/client/movian/research/users/phuclh12/Code/minHiWave/weight_cache/FLUX.1-Krea-dev", | |
| torch_dtype=torch.bfloat16, | |
| device="cuda", | |
| local_files_only=True, | |
| ) | |
| guidance_scale = 4.5 | |
| else: | |
| pipe = StableDiffusionXLPipeline.from_pretrained( | |
| "stabilityai/stable-diffusion-xl-base-1.0", | |
| torch_dtype=torch.float16, | |
| local_files_only=True, | |
| ) | |
| guidance_scale = 7.5 | |
| pipe.to("cuda") | |
| print(f"Reading prompts from: {prompt_file}") | |
| with open(prompt_file, 'r', encoding='utf-8') as f: | |
| prompts = [line.strip() for line in f.readlines() if line.strip()] | |
| os.makedirs(output_dir, exist_ok=True) | |
| os.makedirs(os.path.join(output_dir, f"image_1k_{use_flux_base}"), exist_ok=True) | |
| for i, prompt in enumerate(prompts): | |
| print(f"Processing prompt {i+1}/{len(prompts)}: {prompt[:50]}...") | |
| try: | |
| image_filename = f"image_{i+1:04d}.jpg" | |
| image_path = os.path.join(output_dir, f"image_1k_{use_flux_base}", image_filename) | |
| image = pipe( | |
| prompt=prompt, | |
| num_inference_steps=50, | |
| guidance_scale=guidance_scale, | |
| width=1024, | |
| height=1024, | |
| )[0] | |
| image[0].save(image_path) | |
| except Exception as e: | |
| print(f"Error generating 1k image: {str(e)}") | |
| continue | |
| def _worker( | |
| rank: int, | |
| pipeline, | |
| indices: list, | |
| prompts: list, | |
| original_image_path: str, | |
| output_dir: str, | |
| config: UpscaleConfig, | |
| cascade_upscale: bool = True, | |
| pipeline_type: str = "sdxl", | |
| ): | |
| """Single-GPU worker thread: uses a pre-initialized pipeline on GPU `rank`.""" | |
| torch.cuda.set_device(rank) | |
| image_2k_dir = os.path.join(output_dir, "image_2k") | |
| image_4k_dir = os.path.join(output_dir, "image_4k") | |
| # Use the appropriate to_dict method based on pipeline type | |
| if pipeline_type == "sdxl": | |
| kwargs = config.to_dict_sdxl() | |
| elif pipeline_type == "sd": | |
| kwargs = config.to_dict_sd() | |
| elif pipeline_type == "pixart_sigma": | |
| kwargs = config.to_dict_pixart_sigma() | |
| # Pass 1: generate all 2k images | |
| for i in tqdm(indices, desc=f"GPU {rank} [2k]", position=rank, disable=rank != 0): | |
| prompt = prompts[i] | |
| # try: | |
| image_filename = f"image_{i+1:04d}.jpg" | |
| image_1k_path = os.path.join(original_image_path, image_filename.replace("jpg", "png")) | |
| image_2k_path = os.path.join(image_2k_dir, image_filename) | |
| image_1k = Image.open(image_1k_path) | |
| image_1k = torch.from_numpy(np.array(image_1k)).float() / 255.0 | |
| image_1k = (2 * image_1k - 1.0).clamp(-1, 1) | |
| image_1k = image_1k.unsqueeze(0).permute(0, 3, 1, 2) | |
| image_2k = pipeline.hiwave_one_step(image=image_1k, prompt=prompt, upsample=2, **kwargs) | |
| pipeline._save_image(image_2k, image_2k_path) | |
| # except Exception as e: | |
| # print(f"[GPU {rank}] Error generating 2k for index {i}: {e}") | |
| # continue | |
| # Pass 2: generate all 4k images | |
| for i in tqdm(indices, desc=f"GPU {rank} [4k]", position=rank, disable=rank != 0): | |
| prompt = prompts[i] | |
| try: | |
| image_filename = f"image_{i+1:04d}.jpg" | |
| image_1k_path = os.path.join(original_image_path, image_filename.replace("jpg", "png")) | |
| image_2k_path = os.path.join(image_2k_dir, image_filename) | |
| image_4k_path = os.path.join(image_4k_dir, image_filename) | |
| if cascade_upscale: | |
| image_2k = Image.open(image_2k_path) | |
| image_2k = torch.from_numpy(np.array(image_2k)).float() / 255.0 | |
| image_2k = (2 * image_2k - 1.0).clamp(-1, 1) | |
| image_2k = image_2k.unsqueeze(0).permute(0, 3, 1, 2) | |
| image_4k = pipeline.hiwave_one_step(image=image_2k, prompt=prompt, upsample=2, **kwargs) | |
| else: | |
| image_1k = Image.open(image_1k_path) | |
| image_1k = torch.from_numpy(np.array(image_1k)).float() / 255.0 | |
| image_1k = (2 * image_1k - 1.0).clamp(-1, 1) | |
| image_1k = image_1k.unsqueeze(0).permute(0, 3, 1, 2) | |
| image_4k = pipeline.hiwave_one_step(image=image_1k, prompt=prompt, upsample=4, **kwargs) | |
| pipeline._save_image(image_4k, image_4k_path) | |
| except Exception as e: | |
| print(f"[GPU {rank}] Error generating 4k for index {i}: {e}") | |
| continue | |
| if __name__ == "__main__": | |
| import argparse | |
| parser = argparse.ArgumentParser(description="Generate upscaled images on multiple GPUs") | |
| parser.add_argument("--pipeline", type=str, choices=["sd", "sdxl", "pixart_sigma"], default="sdxl", help="Pipeline type: sd or sdxl or pixart_sigma") | |
| parser.add_argument("--sparse", action="store_true", help="Use sparse pipeline variant (sdxl→SwiftHiPipelineSparse, sd→CustomSDPipelineSparse)") | |
| parser.add_argument("--output_dir", type=str, required=True, help="Output directory for generated images") | |
| parser.add_argument("--prompt_file", type=str, default="/lustre/scratch/client/movian/research/users/phuclh12/Code/minHiWave/prompts.txt", help="Path to prompts file") | |
| parser.add_argument("--input_dir", type=str, default="/lustre/scratch/client/movian/research/users/phuclh12/Code/minHiWave/output/image_1k", help="Input 1k images directory") | |
| parser.add_argument("--num_gpus", type=int, default=4, help="Number of GPUs to use") | |
| # Config parameters | |
| parser.add_argument("--cascade_upscale", action="store_true", help="Cascade upscale: 1k->2k->4k (upsample=2 each). If False: 1k->4k directly (upsample=4). Use --cascade_upscale true/false") | |
| parser.add_argument("--ddim_inv_to_step", type=int, default=249, help="DDIM inversion steps") | |
| parser.add_argument("--upscale_RGB", action="store_true", help="Upscale in RGB space") | |
| parser.add_argument("--upscale_bridge", action="store_true", help="Use bridge upscaling") | |
| parser.add_argument("--padding_anhtran", action="store_true", help="Use Anh Tran padding") | |
| parser.add_argument("--small_bridge", action="store_true", help="Use small bridge model") | |
| parser.add_argument("--use_temporal_scaling", action="store_true", help="Use temporal scaling") | |
| parser.add_argument("--use_noise_injection", action="store_true", help="Use noise injection") | |
| parser.add_argument("--temperature", type=float, default=0.7, help="Temperature for temporal scaling") | |
| parser.add_argument("--user_define", type=float, default=2.0, help="User-defined parameter") | |
| parser.add_argument("--lambda_noise", type=float, default=0.9, help="Noise injection lambda") | |
| parser.add_argument("--inv_sr_weight", type=float, default=0.0, help="InvSR weight (SD only)") | |
| parser.add_argument("--renoise_inv", action="store_true", help="Renoise inversion") | |
| args = parser.parse_args() | |
| output_dir = args.output_dir | |
| prompt_file = args.prompt_file | |
| original_image_path = args.input_dir | |
| with open(prompt_file, "r", encoding="utf-8") as f: | |
| prompts = [line.strip() for line in f if line.strip()] | |
| print(f"Found {len(prompts)} prompts, using {args.num_gpus} GPUs with {args.pipeline.upper()} pipeline") | |
| assert os.path.exists(original_image_path), f"Image dir not found: {original_image_path}" | |
| Path(os.path.join(output_dir, "image_2k")).mkdir(parents=True, exist_ok=True) | |
| Path(os.path.join(output_dir, "image_4k")).mkdir(parents=True, exist_ok=True) | |
| num_gpus = args.num_gpus | |
| chunks = [list(range(rank, len(prompts), num_gpus)) for rank in range(num_gpus)] | |
| # Build config from arguments | |
| config = UpscaleConfig( | |
| ddim_inv_to_step=args.ddim_inv_to_step, | |
| upscale_RGB=args.upscale_RGB, | |
| upscale_bridge=args.upscale_bridge, | |
| padding_anhtran=args.padding_anhtran, | |
| small_bridge=args.small_bridge, | |
| use_temporal_scaling=args.use_temporal_scaling, | |
| use_noise_injection=args.use_noise_injection, | |
| temperature=args.temperature, | |
| user_define=args.user_define, | |
| lambda_noise=args.lambda_noise, | |
| inv_sr_weight=args.inv_sr_weight, | |
| renoise_inv=args.renoise_inv, | |
| ) | |
| print(f"Config: {config}") | |
| # Save config to output_dir as config.yaml | |
| config_dict = { | |
| "pipeline": args.pipeline, | |
| "sparse": args.sparse, | |
| "cascade_upscale": args.cascade_upscale, | |
| "prompt_file": prompt_file, | |
| "input_dir": original_image_path, | |
| "num_gpus": num_gpus, | |
| **asdict(config) | |
| } | |
| config_path = os.path.join(output_dir, "config.yaml") | |
| with open(config_path, "w") as f: | |
| yaml.dump(config_dict, f, default_flow_style=False, sort_keys=False) | |
| print(f"Config saved to: {config_path}") | |
| # Initialize pipelines based on type | |
| sparse_tag = " (sparse)" if args.sparse else "" | |
| print(f"Initializing {args.pipeline.upper()}{sparse_tag} pipelines on each GPU...") | |
| if args.pipeline == "sdxl": | |
| PipelineClass = SwiftHiPipelineSparse if args.sparse else SwiftHiPipeline | |
| pipelines = [ | |
| PipelineClass( | |
| model_id="stabilityai/stable-diffusion-xl-base-1.0", | |
| turbo_model_id="stabilityai/sdxl-turbo", | |
| device=f"cuda:{rank}", | |
| ) | |
| for rank in range(num_gpus) | |
| ] | |
| elif args.pipeline == "sd": | |
| PipelineClass = CustomSDPipelineSparse if args.sparse else CustomSDPipeline | |
| pipelines = [ | |
| PipelineClass( | |
| model_id="stabilityai/sd-turbo", | |
| device=f"cuda:{rank}", | |
| ) | |
| for rank in range(num_gpus) | |
| ] | |
| elif args.pipeline == "pixart_sigma": | |
| pipelines = [ | |
| PixArtSigmaHiPipeline( | |
| model_id="PixArt-alpha/PixArt-Sigma-XL-2-1024-MS", | |
| device=f"cuda:{rank}", | |
| ) | |
| for rank in range(num_gpus) | |
| ] | |
| print("All pipelines initialized.") | |
| # Launch worker threads | |
| threads = [ | |
| threading.Thread( | |
| target=_worker, | |
| args=(rank, pipelines[rank], chunks[rank], prompts, original_image_path, output_dir, config, args.cascade_upscale, args.pipeline), | |
| name=f"worker-gpu-{rank}", | |
| ) | |
| for rank in range(num_gpus) | |
| ] | |
| for t in threads: | |
| t.start() | |
| for t in threads: | |
| t.join() | |
| print("All done.") | |