File size: 4,661 Bytes
b373569 | 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 | """
Inference pipeline: Generate 4K image from text prompt.
Stage 1 (Flux) → Stage 2 (SR 1K→2K) → Stage 3 (SR 2K→4K)
"""
import argparse
import time
from pathlib import Path
import torch
from PIL import Image
from diffusers import FluxPipeline
from peft import PeftModel
from train_sr import SRUNet
def load_flux_pipeline(base_model, lora_path=None, device="cuda:0"):
print(f"Loading Flux from {base_model}...")
pipe = FluxPipeline.from_pretrained(
base_model,
torch_dtype=torch.bfloat16,
).to(device)
if lora_path:
print(f"Loading LoRA from {lora_path}...")
pipe.transformer = PeftModel.from_pretrained(pipe.transformer, lora_path)
return pipe
def load_sr_model(checkpoint_path, base_channels=64, device="cuda:1"):
print(f"Loading SR model from {checkpoint_path}...")
model = SRUNet(in_channels=3, out_channels=3, base_channels=base_channels, scale_factor=2)
state_dict = torch.load(checkpoint_path, map_location="cpu")
model.load_state_dict(state_dict)
model = model.to(device, dtype=torch.bfloat16)
model.eval()
return model
def image_to_tensor(image, device):
from torchvision import transforms
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5]),
])
return transform(image).unsqueeze(0).to(device, dtype=torch.bfloat16)
def tensor_to_image(tensor):
tensor = tensor.squeeze(0).float().cpu()
tensor = tensor * 0.5 + 0.5
tensor = tensor.clamp(0, 1)
from torchvision.transforms.functional import to_pil_image
return to_pil_image(tensor)
@torch.no_grad()
def generate_4k(prompt, flux_pipe, sr_stage2, sr_stage3, output_path, num_inference_steps=28, guidance_scale=3.5):
print(f"\nGenerating: '{prompt}'")
t0 = time.time()
# Stage 1: Generate 1024px with Flux
print(" Stage 1: Generating 1024px...")
image_1k = flux_pipe(
prompt=prompt,
num_inference_steps=num_inference_steps,
guidance_scale=guidance_scale,
width=1024,
height=1024,
).images[0]
t1 = time.time()
print(f" Done in {t1-t0:.1f}s")
# Stage 2: Upscale 1K → 2K
print(" Stage 2: Upscaling to 2K...")
device_sr = next(sr_stage2.parameters()).device
input_tensor = image_to_tensor(image_1k, device_sr)
output_2k = sr_stage2(input_tensor)
image_2k = tensor_to_image(output_2k)
t2 = time.time()
print(f" Done in {t2-t1:.1f}s ({image_2k.size[0]}x{image_2k.size[1]})")
# Stage 3: Upscale 2K → 4K
print(" Stage 3: Upscaling to 4K...")
input_tensor = image_to_tensor(image_2k, device_sr)
output_4k = sr_stage3(input_tensor)
image_4k = tensor_to_image(output_4k)
t3 = time.time()
print(f" Done in {t3-t2:.1f}s ({image_4k.size[0]}x{image_4k.size[1]})")
# Save all stages
output_path = Path(output_path)
output_path.mkdir(parents=True, exist_ok=True)
stem = prompt[:50].replace(" ", "_").replace("/", "_")
image_1k.save(output_path / f"{stem}_1k.png")
image_2k.save(output_path / f"{stem}_2k.png")
image_4k.save(output_path / f"{stem}_4k.png")
print(f"\n Total time: {t3-t0:.1f}s")
print(f" Saved to: {output_path}")
return image_4k
def main():
parser = argparse.ArgumentParser(description="Generate 4K images")
parser.add_argument("--prompt", required=True, help="Text prompt")
parser.add_argument("--flux-model", default="black-forest-labs/FLUX.1-schnell")
parser.add_argument("--lora-path", type=Path, default=None)
parser.add_argument("--sr-stage2", type=Path, default=Path("/home/adminuser/chungcat/checkpoints/sr_stage2/final/model.pt"))
parser.add_argument("--sr-stage3", type=Path, default=Path("/home/adminuser/chungcat/checkpoints/sr_stage3/final/model.pt"))
parser.add_argument("--output-dir", type=Path, default=Path("/home/adminuser/chungcat/outputs"))
parser.add_argument("--steps", type=int, default=28)
parser.add_argument("--guidance-scale", type=float, default=3.5)
parser.add_argument("--flux-device", default="cuda:0")
parser.add_argument("--sr-device", default="cuda:1")
args = parser.parse_args()
# Load models
flux_pipe = load_flux_pipeline(args.flux_model, args.lora_path, args.flux_device)
sr_stage2 = load_sr_model(args.sr_stage2, device=args.sr_device)
sr_stage3 = load_sr_model(args.sr_stage3, device=args.sr_device)
# Generate
generate_4k(
args.prompt, flux_pipe, sr_stage2, sr_stage3,
args.output_dir, args.steps, args.guidance_scale,
)
if __name__ == "__main__":
main()
|