memoryai commited on
Commit
94e279b
·
verified ·
1 Parent(s): 84d2952

Upload scripts/serving/inference_4k.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. scripts/serving/inference_4k.py +165 -0
scripts/serving/inference_4k.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ 4K Image Generation Pipeline:
3
+ 1. Generate 1024px with fine-tuned Flux Dev LoRA
4
+ 2. Upscale to 4096px with Real-ESRGAN x4
5
+
6
+ Usage:
7
+ python3 inference_4k.py --prompt "a beautiful landscape" --output output.png
8
+ python3 inference_4k.py --prompt "a cat" --lora-path /path/to/checkpoint --output cat_4k.png
9
+ """
10
+ import argparse
11
+ import time
12
+ from pathlib import Path
13
+
14
+ import torch
15
+ import numpy as np
16
+ from PIL import Image
17
+
18
+
19
+ def load_flux_pipeline(model_name, lora_path=None, device="cuda:0", dtype=torch.bfloat16):
20
+ from diffusers import FluxPipeline
21
+
22
+ print(f" Loading Flux Dev pipeline...")
23
+ pipe = FluxPipeline.from_pretrained(
24
+ model_name,
25
+ torch_dtype=dtype,
26
+ )
27
+
28
+ if lora_path:
29
+ lora_path = Path(lora_path)
30
+ if (lora_path / "adapter_model.safetensors").exists():
31
+ pipe.load_lora_weights(str(lora_path))
32
+ print(f" Loaded LoRA from {lora_path}")
33
+ else:
34
+ print(f" WARNING: No adapter_model.safetensors in {lora_path}")
35
+
36
+ pipe = pipe.to(device)
37
+ pipe.enable_model_cpu_offload()
38
+ return pipe
39
+
40
+
41
+ def load_realesrgan(device="cuda:0", scale=4):
42
+ """Load Real-ESRGAN x4 model for upscaling."""
43
+ try:
44
+ from realesrgan import RealESRGANer
45
+ from basicsr.archs.rrdbnet_arch import RRDBNet
46
+ except ImportError:
47
+ print(" Installing Real-ESRGAN...")
48
+ import subprocess
49
+ subprocess.run([
50
+ "pip3", "install", "-q",
51
+ "realesrgan", "basicsr", "facexlib", "gfpgan"
52
+ ], check=True)
53
+ from realesrgan import RealESRGANer
54
+ from basicsr.archs.rrdbnet_arch import RRDBNet
55
+
56
+ model = RRDBNet(num_in_ch=3, num_out_ch=3, num_feat=64, num_block=23, num_grow_ch=32, scale=scale)
57
+
58
+ model_path = Path("/data0/models/RealESRGAN_x4plus.pth")
59
+ if not model_path.exists():
60
+ print(" Downloading RealESRGAN_x4plus model...")
61
+ model_path.parent.mkdir(parents=True, exist_ok=True)
62
+ import urllib.request
63
+ urllib.request.urlretrieve(
64
+ "https://github.com/xinntao/Real-ESRGAN/releases/download/v0.1.0/RealESRGAN_x4plus.pth",
65
+ str(model_path),
66
+ )
67
+
68
+ upsampler = RealESRGANer(
69
+ scale=scale,
70
+ model_path=str(model_path),
71
+ model=model,
72
+ tile=512,
73
+ tile_pad=10,
74
+ pre_pad=0,
75
+ half=True,
76
+ device=device,
77
+ )
78
+ print(f" Real-ESRGAN x{scale} loaded")
79
+ return upsampler
80
+
81
+
82
+ def generate_1k(pipe, prompt, num_steps=28, guidance_scale=3.5, seed=None):
83
+ """Generate 1024x1024 image with Flux Dev."""
84
+ generator = None
85
+ if seed is not None:
86
+ generator = torch.Generator(device=pipe.device).manual_seed(seed)
87
+
88
+ image = pipe(
89
+ prompt=prompt,
90
+ num_inference_steps=num_steps,
91
+ guidance_scale=guidance_scale,
92
+ height=1024,
93
+ width=1024,
94
+ generator=generator,
95
+ ).images[0]
96
+
97
+ return image
98
+
99
+
100
+ def upscale_4k(upsampler, image):
101
+ """Upscale PIL image to 4K using Real-ESRGAN."""
102
+ import cv2
103
+
104
+ img_np = np.array(image)
105
+ img_bgr = cv2.cvtColor(img_np, cv2.COLOR_RGB2BGR)
106
+
107
+ output, _ = upsampler.enhance(img_bgr, outscale=4)
108
+
109
+ output_rgb = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)
110
+ return Image.fromarray(output_rgb)
111
+
112
+
113
+ def main():
114
+ parser = argparse.ArgumentParser(description="Generate 4K images")
115
+ parser.add_argument("--prompt", type=str, required=True)
116
+ parser.add_argument("--output", type=str, default="output_4k.png")
117
+ parser.add_argument("--model-name", default="black-forest-labs/FLUX.1-dev")
118
+ parser.add_argument("--lora-path", type=str, default=None)
119
+ parser.add_argument("--num-steps", type=int, default=28)
120
+ parser.add_argument("--guidance-scale", type=float, default=3.5)
121
+ parser.add_argument("--seed", type=int, default=None)
122
+ parser.add_argument("--device", default="cuda:0")
123
+ parser.add_argument("--skip-upscale", action="store_true")
124
+ parser.add_argument("--save-1k", action="store_true", help="Also save 1K intermediate")
125
+ args = parser.parse_args()
126
+
127
+ t0 = time.time()
128
+
129
+ # Stage 1: Generate 1024px
130
+ print("=== Stage 1: Generate 1024px ===")
131
+ pipe = load_flux_pipeline(args.model_name, args.lora_path, args.device)
132
+ image_1k = generate_1k(pipe, args.prompt, args.num_steps, args.guidance_scale, args.seed)
133
+ print(f" Generated 1024x1024 in {time.time()-t0:.1f}s")
134
+
135
+ if args.save_1k:
136
+ path_1k = Path(args.output).with_suffix("").with_name(Path(args.output).stem + "_1k.png")
137
+ image_1k.save(path_1k)
138
+ print(f" Saved 1K: {path_1k}")
139
+
140
+ # Free GPU memory
141
+ del pipe
142
+ torch.cuda.empty_cache()
143
+
144
+ if args.skip_upscale:
145
+ image_1k.save(args.output)
146
+ print(f" Saved (no upscale): {args.output}")
147
+ return
148
+
149
+ # Stage 2: Upscale to 4K
150
+ print("=== Stage 2: Upscale to 4096px ===")
151
+ t1 = time.time()
152
+ upsampler = load_realesrgan(args.device)
153
+ image_4k = upscale_4k(upsampler, image_1k)
154
+ print(f" Upscaled to {image_4k.size[0]}x{image_4k.size[1]} in {time.time()-t1:.1f}s")
155
+
156
+ # Save
157
+ output_path = Path(args.output)
158
+ output_path.parent.mkdir(parents=True, exist_ok=True)
159
+ image_4k.save(output_path, quality=95)
160
+ print(f"\n Final 4K image saved: {output_path}")
161
+ print(f" Total time: {time.time()-t0:.1f}s")
162
+
163
+
164
+ if __name__ == "__main__":
165
+ main()