XCLiu commited on
Commit
5ea557e
1 Parent(s): 22f6cf2

Update app.py

Browse files

replace with the new lora version huggingface demo

Files changed (1) hide show
  1. app.py +130 -7
app.py CHANGED
@@ -1,9 +1,132 @@
1
- import shlex
2
- import subprocess
3
 
4
- from huggingface_hub import HfApi
5
 
6
- api = HfApi()
7
- api.snapshot_download(repo_id="XCLiu/InstaFlow_hidden", repo_type="space", local_dir=".")
8
- subprocess.run(shlex.split("pip install -r requirements.txt"))
9
- subprocess.run(shlex.split("python app.py"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
 
2
 
3
+ from pipeline_rf import RectifiedFlowPipeline
4
 
5
+ import torch
6
+ from torchvision.transforms import Compose, Resize, CenterCrop, ToTensor, Normalize
7
+ import torch.nn.functional as F
8
+
9
+ from diffusers import StableDiffusionXLImg2ImgPipeline
10
+ import time
11
+ import copy
12
+ import numpy as np
13
+
14
+ def merge_dW_to_unet(pipe, dW_dict, alpha=1.0):
15
+ _tmp_sd = pipe.unet.state_dict()
16
+ for key in dW_dict.keys():
17
+ _tmp_sd[key] += dW_dict[key] * alpha
18
+ pipe.unet.load_state_dict(_tmp_sd, strict=False)
19
+ return pipe
20
+
21
+ def get_dW_and_merge(pipe_rf, lora_path='Lykon/dreamshaper-7', save_dW = False, base_sd='runwayml/stable-diffusion-v1-5', alpha=1.0):
22
+ # get weights of base sd models
23
+ from diffusers import DiffusionPipeline
24
+ _pipe = DiffusionPipeline.from_pretrained(
25
+ base_sd,
26
+ torch_dtype=torch.float16,
27
+ safety_checker = None,
28
+ )
29
+ sd_state_dict = _pipe.unet.state_dict()
30
+
31
+ # get weights of the customized sd models, e.g., the aniverse downloaded from civitai.com
32
+ _pipe = DiffusionPipeline.from_pretrained(
33
+ lora_path,
34
+ torch_dtype=torch.float16,
35
+ safety_checker = None,
36
+ )
37
+ lora_unet_checkpoint = _pipe.unet.state_dict()
38
+
39
+ # get the dW
40
+ dW_dict = {}
41
+ for key in lora_unet_checkpoint.keys():
42
+ dW_dict[key] = lora_unet_checkpoint[key] - sd_state_dict[key]
43
+
44
+ # return and save dW dict
45
+ if save_dW:
46
+ save_name = lora_path.split('/')[-1] + '_dW.pt'
47
+ torch.save(dW_dict, save_name)
48
+
49
+ pipe_rf = merge_dW_to_unet(pipe_rf, dW_dict=dW_dict, alpha=alpha)
50
+ pipe_rf.vae = _pipe.vae
51
+ pipe_rf.text_encoder = _pipe.text_encoder
52
+
53
+ return dW_dict
54
+
55
+
56
+
57
+ pipe = StableDiffusionXLImg2ImgPipeline.from_pretrained(
58
+ "stabilityai/stable-diffusion-xl-refiner-1.0", torch_dtype=torch.float16, variant="fp16", use_safetensors=True
59
+ )
60
+ pipe = pipe.to("cuda")
61
+
62
+ insta_pipe = RectifiedFlowPipeline.from_pretrained("XCLiu/instaflow_0_9B_from_sd_1_5", torch_dtype=torch.float16)
63
+ dW_dict = get_dW_and_merge(insta_pipe, lora_path="Lykon/dreamshaper-7", save_dW=False, alpha=1.0)
64
+ insta_pipe.to("cuda")
65
+
66
+ global img
67
+
68
+ @torch.no_grad()
69
+ def set_new_latent_and_generate_new_image(seed, prompt, randomize_seed, num_inference_steps=1, guidance_scale=0.0):
70
+ print('Generate with input seed')
71
+ global img
72
+ negative_prompt=""
73
+ if randomize_seed:
74
+ seed = np.random.randint(0, 2**32)
75
+ seed = int(seed)
76
+ num_inference_steps = int(num_inference_steps)
77
+ guidance_scale = float(guidance_scale)
78
+ print(seed, num_inference_steps, guidance_scale)
79
+
80
+ t_s = time.time()
81
+ generator = torch.manual_seed(seed)
82
+ images = insta_pipe(prompt=prompt, num_inference_steps=1, guidance_scale=0.0, generator=generator).images
83
+ inf_time = time.time() - t_s
84
+
85
+ img = copy.copy(np.array(images[0]))
86
+
87
+ return images[0], inf_time, seed
88
+
89
+ @torch.no_grad()
90
+ def refine_image_512(prompt):
91
+ print('Refine with SDXL-Refiner (512)')
92
+ global img
93
+
94
+ t_s = time.time()
95
+ img = torch.tensor(img).unsqueeze(0).permute(0, 3, 1, 2) / 255.0
96
+ img = img.permute(0, 2, 3, 1).squeeze(0).cpu().numpy()
97
+ new_image = pipe(prompt, image=img).images[0]
98
+ print('time consumption:', time.time() - t_s)
99
+ new_image = np.array(new_image) * 1.0 / 255.
100
+
101
+ img = copy.copy(new_image)
102
+
103
+ return new_image
104
+
105
+
106
+ with gr.Blocks() as gradio_gui:
107
+ gr.Markdown(
108
+ """
109
+ # InstaFlow! One-Step Stable Diffusion with Rectified Flow [[paper]](https://arxiv.org/abs/2309.06380)
110
+ ## This is a demo of one-step InstaFlow-0.9B with [dreamshaper-7](https://huggingface.co/Lykon/dreamshaper-7) (a LoRA that improves image quality) and measures the inference time.
111
+ """)
112
+
113
+ with gr.Row():
114
+ with gr.Column(scale=0.4):
115
+ with gr.Group():
116
+ gr.Markdown("Generation from InstaFlow-0.9B")
117
+ im = gr.Image()
118
+
119
+ with gr.Column(scale=0.4):
120
+ inference_time_output = gr.Textbox(value='0.0', label='Inference Time with One-Step InstaFlow (Second)')
121
+ seed_input = gr.Textbox(value='101098274', label="Random Seed")
122
+ randomize_seed = gr.Checkbox(label="Randomly Sample a Random Seed", value=True)
123
+ prompt_input = gr.Textbox(value='A high-resolution photograph of a waterfall in autumn; muted tone', label="Prompt")
124
+
125
+ new_image_button = gr.Button(value="One-Step Generation with InstaFlow and the Random Seed")
126
+ new_image_button.click(set_new_latent_and_generate_new_image, inputs=[seed_input, prompt_input, randomize_seed], outputs=[im, inference_time_output, seed_input])
127
+
128
+ refine_button_512 = gr.Button(value="Refine One-Step Generation with SDXL Refiner (Resolution: 512)")
129
+ refine_button_512.click(refine_image_512, inputs=[prompt_input], outputs=[im])
130
+
131
+
132
+ gradio_gui.launch()