Spaces:
Runtime error
Runtime error
add app_t2i.py
Browse files- app_t2i.py +209 -0
app_t2i.py
ADDED
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from PIL import Image
|
2 |
+
import gradio as gr
|
3 |
+
from huggingface_hub import hf_hub_download, snapshot_download
|
4 |
+
import torch
|
5 |
+
torch.backends.cuda.matmul.allow_tf32 = True
|
6 |
+
torch.backends.cudnn.allow_tf32 = True
|
7 |
+
torch.set_float32_matmul_precision('high')
|
8 |
+
setattr(torch.nn.Linear, 'reset_parameters', lambda self: None)
|
9 |
+
setattr(torch.nn.LayerNorm, 'reset_parameters', lambda self: None)
|
10 |
+
import os
|
11 |
+
import time
|
12 |
+
import argparse
|
13 |
+
from tokenizer_image.vq_model import VQ_models
|
14 |
+
from models.gpt import GPT_models
|
15 |
+
from models.generate import generate
|
16 |
+
from t5 import T5Embedder
|
17 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
18 |
+
|
19 |
+
device = "cuda"
|
20 |
+
|
21 |
+
model2ckpt = {
|
22 |
+
"GPT-XL": ("vq_ds16_t2i.pt", "t2i_XL_stage2_512.pt", 512),
|
23 |
+
}
|
24 |
+
|
25 |
+
def load_model(args):
|
26 |
+
ckpt_folder = './'
|
27 |
+
t5_folder = os.path.join(ckpt_folder, "flan-t5-xl")
|
28 |
+
if not os.path.exists(t5_folder):
|
29 |
+
os.makedirs(t5_folder, exist_ok=True)
|
30 |
+
vq_ckpt, gpt_ckpt, image_size = model2ckpt[args.gpt_model]
|
31 |
+
hf_hub_download(repo_id="peizesun/llamagen_t2i", filename=vq_ckpt, local_dir=ckpt_folder)
|
32 |
+
hf_hub_download(repo_id="peizesun/llamagen_t2i", filename=gpt_ckpt, local_dir=ckpt_folder)
|
33 |
+
hf_hub_download(repo_id="google/flan-t5-xl", filename="config.json", local_dir=t5_folder)
|
34 |
+
hf_hub_download(repo_id="google/flan-t5-xl", filename="pytorch_model-00001-of-00002.bin", local_dir=t5_folder)
|
35 |
+
hf_hub_download(repo_id="google/flan-t5-xl", filename="pytorch_model-00002-of-00002.bin", local_dir=t5_folder)
|
36 |
+
hf_hub_download(repo_id="google/flan-t5-xl", filename="pytorch_model.bin.index.json", local_dir=t5_folder)
|
37 |
+
hf_hub_download(repo_id="google/flan-t5-xl", filename="special_tokens_map.json", local_dir=t5_folder)
|
38 |
+
hf_hub_download(repo_id="google/flan-t5-xl", filename="spiece.model", local_dir=t5_folder)
|
39 |
+
hf_hub_download(repo_id="google/flan-t5-xl", filename="tokenizer_config.json", local_dir=t5_folder)
|
40 |
+
# create and load model
|
41 |
+
vq_model = VQ_models[args.vq_model](
|
42 |
+
codebook_size=args.codebook_size,
|
43 |
+
codebook_embed_dim=args.codebook_embed_dim)
|
44 |
+
vq_model.to(device)
|
45 |
+
vq_model.eval()
|
46 |
+
checkpoint = torch.load(f"{ckpt_folder}{vq_ckpt}", map_location="cpu")
|
47 |
+
vq_model.load_state_dict(checkpoint["model"])
|
48 |
+
del checkpoint
|
49 |
+
print(f"image tokenizer is loaded")
|
50 |
+
|
51 |
+
# create and load gpt model
|
52 |
+
precision = {'none': torch.float32, 'bf16': torch.bfloat16, 'fp16': torch.float16}[args.precision]
|
53 |
+
latent_size = image_size // args.downsample_size
|
54 |
+
gpt_model = GPT_models[args.gpt_model](
|
55 |
+
vocab_size=args.codebook_size,
|
56 |
+
block_size=latent_size ** 2,
|
57 |
+
num_classes=args.num_classes,
|
58 |
+
cls_token_num=args.cls_token_num,
|
59 |
+
model_type=args.gpt_type,
|
60 |
+
).to(device=device, dtype=precision)
|
61 |
+
|
62 |
+
checkpoint = torch.load(f"{ckpt_folder}{gpt_ckpt}", map_location="cpu")
|
63 |
+
if args.from_fsdp: # fspd
|
64 |
+
model_weight = checkpoint
|
65 |
+
elif "model" in checkpoint: # ddp
|
66 |
+
model_weight = checkpoint["model"]
|
67 |
+
elif "module" in checkpoint: # deepspeed
|
68 |
+
model_weight = checkpoint["module"]
|
69 |
+
elif "state_dict" in checkpoint:
|
70 |
+
model_weight = checkpoint["state_dict"]
|
71 |
+
else:
|
72 |
+
raise Exception("please check model weight")
|
73 |
+
# if 'freqs_cis' in model_weight:
|
74 |
+
# model_weight.pop('freqs_cis')
|
75 |
+
gpt_model.load_state_dict(model_weight, strict=False)
|
76 |
+
gpt_model.eval()
|
77 |
+
del checkpoint
|
78 |
+
print(f"gpt model is loaded")
|
79 |
+
|
80 |
+
if args.compile:
|
81 |
+
print(f"compiling the model...")
|
82 |
+
gpt_model = torch.compile(
|
83 |
+
gpt_model,
|
84 |
+
mode="reduce-overhead",
|
85 |
+
fullgraph=True
|
86 |
+
) # requires PyTorch 2.0 (optional)
|
87 |
+
else:
|
88 |
+
print(f"no need to compile model in demo")
|
89 |
+
|
90 |
+
t5_model = T5Embedder(
|
91 |
+
device=device,
|
92 |
+
local_cache=True,
|
93 |
+
cache_dir=ckpt_folder,
|
94 |
+
dir_or_name="flan-t5-xl",
|
95 |
+
torch_dtype=precision,
|
96 |
+
model_max_length=args.t5_feature_max_len,
|
97 |
+
)
|
98 |
+
|
99 |
+
return t5_model, vq_model, gpt_model, image_size
|
100 |
+
|
101 |
+
|
102 |
+
def infer(cfg_scale, top_k, top_p, temperature, prompt, seed):
|
103 |
+
prompts = [prompt for _ in range(4)]
|
104 |
+
caption_embs, emb_masks = t5_model.get_text_embeddings(prompts)
|
105 |
+
|
106 |
+
if not args.no_left_padding:
|
107 |
+
print(f"processing left-padding...")
|
108 |
+
# a naive way to implement left-padding
|
109 |
+
new_emb_masks = torch.flip(emb_masks, dims=[-1])
|
110 |
+
new_caption_embs = []
|
111 |
+
for idx, (caption_emb, emb_mask) in enumerate(zip(caption_embs, emb_masks)):
|
112 |
+
valid_num = int(emb_mask.sum().item())
|
113 |
+
print(f' prompt {idx} token len: {valid_num}')
|
114 |
+
new_caption_emb = torch.cat([caption_emb[valid_num:], caption_emb[:valid_num]])
|
115 |
+
new_caption_embs.append(new_caption_emb)
|
116 |
+
new_caption_embs = torch.stack(new_caption_embs)
|
117 |
+
else:
|
118 |
+
new_caption_embs, new_emb_masks = caption_embs, emb_masks
|
119 |
+
c_indices = new_caption_embs * new_emb_masks[:,:, None]
|
120 |
+
c_emb_masks = new_emb_masks
|
121 |
+
qzshape = [len(c_indices), args.codebook_embed_dim, latent_size, latent_size]
|
122 |
+
|
123 |
+
t1 = time.time()
|
124 |
+
torch.manual_seed(seed)
|
125 |
+
index_sample = generate(
|
126 |
+
gpt_model, c_indices, latent_size ** 2,
|
127 |
+
c_emb_masks,
|
128 |
+
cfg_scale=cfg_scale, cfg_interval=args.cfg_interval,
|
129 |
+
temperature=temperature, top_k=top_k,
|
130 |
+
top_p=top_p, sample_logits=True,
|
131 |
+
)
|
132 |
+
sampling_time = time.time() - t1
|
133 |
+
print(f"gpt sampling takes about {sampling_time:.2f} seconds.")
|
134 |
+
|
135 |
+
t2 = time.time()
|
136 |
+
samples = vq_model.decode_code(index_sample, qzshape) # output value is between [-1, 1]
|
137 |
+
decoder_time = time.time() - t2
|
138 |
+
print(f"decoder takes about {decoder_time:.2f} seconds.")
|
139 |
+
# Convert to PIL.Image format:
|
140 |
+
samples = samples.mul(127.5).add_(128.0).clamp_(0, 255).permute(0, 2, 3, 1).to("cpu", torch.uint8).numpy()
|
141 |
+
samples = [Image.fromarray(sample) for sample in samples]
|
142 |
+
return samples
|
143 |
+
|
144 |
+
|
145 |
+
parser = argparse.ArgumentParser()
|
146 |
+
parser.add_argument("--t5-path", type=str, default='.')
|
147 |
+
parser.add_argument("--t5-feature-max-len", type=int, default=120)
|
148 |
+
parser.add_argument("--t5-feature-dim", type=int, default=2048)
|
149 |
+
parser.add_argument("--no-left-padding", action='store_true', default=False)
|
150 |
+
parser.add_argument("--gpt-model", type=str, choices=list(GPT_models.keys()), default="GPT-XL")
|
151 |
+
parser.add_argument("--gpt-type", type=str, choices=['c2i', 't2i'], default="t2i", help="class-conditional or text-conditional")
|
152 |
+
parser.add_argument("--from-fsdp", action='store_true')
|
153 |
+
parser.add_argument("--cls-token-num", type=int, default=120, help="max token number of condition input")
|
154 |
+
parser.add_argument("--precision", type=str, default='bf16', choices=["none", "fp16", "bf16"])
|
155 |
+
parser.add_argument("--compile", action='store_true', default=False)
|
156 |
+
parser.add_argument("--vq-model", type=str, choices=list(VQ_models.keys()), default="VQ-16")
|
157 |
+
parser.add_argument("--codebook-size", type=int, default=16384, help="codebook size for vector quantization")
|
158 |
+
parser.add_argument("--codebook-embed-dim", type=int, default=8, help="codebook dimension for vector quantization")
|
159 |
+
parser.add_argument("--downsample-size", type=int, choices=[8, 16], default=16)
|
160 |
+
parser.add_argument("--num-classes", type=int, default=1000)
|
161 |
+
parser.add_argument("--cfg-scale", type=float, default=7.5)
|
162 |
+
parser.add_argument("--cfg-interval", type=float, default=-1)
|
163 |
+
parser.add_argument("--seed", type=int, default=0)
|
164 |
+
parser.add_argument("--top-k", type=int, default=2000,help="top-k value to sample with")
|
165 |
+
parser.add_argument("--temperature", type=float, default=1.0, help="temperature value to sample with")
|
166 |
+
parser.add_argument("--top-p", type=float, default=1.0, help="top-p value to sample with")
|
167 |
+
args = parser.parse_args()
|
168 |
+
|
169 |
+
t5_model, vq_model, gpt_model, image_size = load_model(args)
|
170 |
+
latent_size = image_size // args.downsample_size
|
171 |
+
|
172 |
+
examples = [
|
173 |
+
"A fluffy golden retriever puppy with big, soulful eyes sits in a sunlit garden, surrounded by colorful flowers and butterflies fluttering around its wagging tail.",
|
174 |
+
"A steaming bowl of Pho, filled with translucent rice noodles and thin slices of savory beef, topped with a heaping of fresh bean sprouts, a wedge of lime on the side, and a sprinkle of chopped green onions and cilantro.",
|
175 |
+
"An ethereal black and white landscape, where a solitary, sinuous black tree stands stark against a stark white snowy backdrop. Its branches twist intricately towards the sky, casting dramatic shadows on the untouched snow below.",
|
176 |
+
]
|
177 |
+
|
178 |
+
with gr.Blocks() as demo:
|
179 |
+
gr.Markdown("<h1 style='text-align: center'>Autoregressive Model Beats Diffusion: Llama for Scalable Image Generation</h1>")
|
180 |
+
|
181 |
+
with gr.Tabs():
|
182 |
+
with gr.TabItem('Generate'):
|
183 |
+
with gr.Row():
|
184 |
+
with gr.Column():
|
185 |
+
cfg_scale = gr.Slider(minimum=1, maximum=25, step=0.1, value=7.5, label='Classifier-free Guidance Scale')
|
186 |
+
top_k = gr.Slider(minimum=1, maximum=16384, step=1, value=4000, label='Top-K')
|
187 |
+
top_p = gr.Slider(minimum=0., maximum=1.0, step=0.1, value=1.0, label="Top-P")
|
188 |
+
temperature = gr.Slider(minimum=0., maximum=1.0, step=0.1, value=1.0, label='Temperature')
|
189 |
+
seed = gr.Slider(minimum=0, maximum=1000, step=1, value=0, label='Seed')
|
190 |
+
with gr.Row():
|
191 |
+
text_prompt = gr.Textbox(
|
192 |
+
label="Enter your prompt",
|
193 |
+
show_label=False,
|
194 |
+
max_lines=1,
|
195 |
+
placeholder="Enter your prompt",
|
196 |
+
)
|
197 |
+
button = gr.Button("Generate", variant="primary")
|
198 |
+
gr.Examples(
|
199 |
+
label="Examples (select one example, and click Generate button)",
|
200 |
+
examples=examples,
|
201 |
+
inputs=text_prompt,
|
202 |
+
# outputs=[result],
|
203 |
+
# fn=generate,
|
204 |
+
)
|
205 |
+
with gr.Column():
|
206 |
+
output = gr.Gallery(label='Generated Images', height=700)
|
207 |
+
button.click(infer, inputs=[cfg_scale, top_k, top_p, temperature, text_prompt, seed], outputs=[output])
|
208 |
+
demo.queue()
|
209 |
+
demo.launch(debug=True, share=True)
|