File size: 13,737 Bytes
735672d
 
8bad2c2
735672d
 
b97419e
 
 
 
735672d
 
 
 
b97419e
 
 
735672d
b97419e
5c46882
b97419e
735672d
8407e3d
970225d
 
8407e3d
c5803b8
 
735672d
 
 
 
 
 
 
f8bcdb6
735672d
 
 
 
 
f8bcdb6
 
 
735672d
 
b97419e
735672d
 
f8bcdb6
735672d
b97419e
735672d
f8bcdb6
735672d
b97419e
 
f8bcdb6
b97419e
735672d
 
 
 
 
 
f8bcdb6
b97419e
 
 
 
 
f8bcdb6
735672d
f8bcdb6
8bad2c2
735672d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85e413
735672d
 
e85e413
f8bcdb6
735672d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8bad2c2
735672d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b97419e
735672d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f2d0235
735672d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e85e413
 
 
735672d
 
 
 
e85e413
 
 
 
 
 
 
 
6baebec
735672d
 
 
 
4931465
735672d
 
 
 
 
 
 
 
b2ec3e2
735672d
 
 
4931465
735672d
 
 
 
9ecb1d6
74ff14c
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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
import time
import torch
import spaces
from PIL import Image
from tqdm import tqdm
from threading import Thread
from torchvision import transforms
from huggingface_hub import hf_hub_download
from transformers import AutoTokenizer, AutoModelForCausalLM, TextIteratorStreamer

from model import *
from unitok.config import Args
from unitok.model import UniTok
from conversation import conv_templates
from mm_utils import tokenizer_image_token
from helpers import sample, expand2square

import os
os.system("wget -q https://huggingface.co/FoundationVision/unitok_tokenizer/resolve/main/unitok_tokenizer.pth")
PILtransform = transforms.ToPILImage()

os.system("pip uninstall -y gradio") 
os.system("pip install gradio==4.44.1")
os.system("pip install gradio_client==1.3.0")

import gradio as gr


IMAGE_TOKEN_INDEX=-200
PLACEHOLDER = """
<div style="padding: 30px; text-align: center; display: flex; flex-direction: column; align-items: center;">
   <img src='file/Liquid_icon.png' style="width: 80%; max-width: 600px; height: auto; opacity: 0.5;"> 
   <h1 style="font-size: 20px; margin-bottom: 1px; opacity: 0.55;">UniTok-MLLM-7B</h1>
</div>
"""

CSS ="""
.contain { display: flex; flex-direction: column; }
#component-0 { height: 100%; }
#chatbot { flex-grow: 1; }
"""


title_html = """
<div style="display: flex; flex-direction: column; align-items: center; gap: 10px;">
<h1 style="margin: 0; line-height: 1; text-align: center;">UniTok: A Unified Tokenizer for Visual Generation and Understanding</h1>
</div>
"""

links_html = f"""
<center><font size=3><a href='https://foundationvision.github.io/Liquid/'>UniTok</a> has been open-sourced on <a href='https://huggingface.co/FoundationVision/unitok_mllm'>😊 Huggingface</a> and <a href='https://github.com/FoundationVision/UniTok'>🌟 GitHub</a>. If you find Liquid useful, a like❤️ or a star🌟 would be appreciated.</font></center>
"""

introduction = f"""
This is a native MLLM built with UniTok, a unified visual tokenizer well-suited for both generation and understanding tasks.
More details can be found on the project <a href='https://foundationvision.github.io/UniTok/'> homepage</a> and in the <a href='https://arxiv.org/abs/2502.20321'> paper</a>. """

ckpt = torch.load('unitok_tokenizer.pth', map_location='cpu')
vae_cfg = Args()
vae_cfg.load_state_dict(ckpt['args'])
vq_model = UniTok(vae_cfg)
vq_model.load_state_dict(ckpt['trainer']['unitok'])
vq_model.to('cuda')
vq_model.eval()

mllm_ckpt = 'FoundationVision/unitok_mllm'
tokenizer = AutoTokenizer.from_pretrained(mllm_ckpt, padding_side='left')
vqllm = MiniGeminiLlamaForCausalLM.from_pretrained(mllm_ckpt).cuda()
vqllm = vqllm.to(dtype=torch.bfloat16)
vqllm = vqllm.eval()

num_codebooks = vae_cfg.num_codebooks

@spaces.GPU
def bot_streaming_I2T(message, history):
    print(message)
    global stop_flag
    stop_flag = True
    time.sleep(0.2)
    stop_flag = False
    torch.cuda.empty_cache()
    if message["files"]:
        # message["files"][-1] is a Dict or just a string
        if type(message["files"][-1]) == dict:
            image = message["files"][-1]["path"]
        else:
            image = message["files"][-1]
    else:
        # if there's no image uploaded for this turn, look for images in the past turns
        # kept inside tuples, take the last one
        for hist in history:
            if type(hist[0]) == tuple:
                image = hist[0][0]
    try:
        if image is None:
            # Handle the case where image is None
            gr.Error("You need to upload an image for UniTok to work.")
    except NameError:
        # Handle the case where 'image' is not defined at all
        gr.Error("You need to upload an image for UniTok to work.")

    qs = message['text']
    qs = '\x00<image>\x01' + '\n' + qs
    conv = conv_templates['llava_v1'].copy()
    conv.append_message(conv.roles[0], qs)
    conv.append_message(conv.roles[1], None)
    prompt = conv.get_prompt()
    
    crop_size = 256
    transform = transforms.Compose([
        transforms.Resize((crop_size, crop_size)),
        transforms.ToTensor(),
        transforms.Normalize(mean=[0.5, 0.5, 0.5], std=[0.5, 0.5, 0.5], inplace=True)
    ])
    
    print(prompt)
    image = Image.open(image).convert('RGB')
    pad_image = expand2square(image, (122, 116, 104) )
    # import pdb;pdb.set_trace()
    img = transform(pad_image).unsqueeze(0)
    img = img.to('cuda')
    # import pdb;pdb.set_trace()
    with torch.no_grad():
        vq_code = vq_model.img_to_idx(img)
        image_codes = vq_code.unsqueeze(0)
        input_ids = tokenizer_image_token(prompt, tokenizer, IMAGE_TOKEN_INDEX, return_tensors='pt')
        inputs =  {
            "inputs":input_ids.unsqueeze(0).to("cuda:0"),
            "images":image_codes.to("cuda:0"),
            "max_new_tokens":1024,
            "bos_token_id":tokenizer.bos_token_id,  # Begin of sequence token
            "eos_token_id":tokenizer.eos_token_id,  # End of sequence token
            "pad_token_id":tokenizer.pad_token_id,  # Pad token
            }
        streamer = TextIteratorStreamer(tokenizer, **{"skip_special_tokens": True, "skip_prompt": True})

        # Run the generation in a separate thread, so that we can fetch the generated text in a non-blocking way.
        generation_kwargs = dict(inputs, streamer=streamer, max_new_tokens=1024)
        thread = Thread(target=vqllm.generate_mllm, kwargs=generation_kwargs)
        thread.start()
        generated_text = ""
        for new_text in streamer:
            generated_text += new_text
            time.sleep(0.06)
            yield generated_text
        

def show_gallery(images):
    gallery = gr.Gallery(images, label="Gallery", columns=4, height="auto",preview=True,scale=0.05)  # 设置两行两列的布局
    return gallery

@spaces.GPU
def bot_streaming_T2I(message, history,guidance_scale, temperature, top_K, top_P):
    global stop_flag
    stop_flag = True
    time.sleep(0.2)
    stop_flag = False
    
    text_inputs = [message]*4  # generate 4 samples once
    uncondition_text_inputs = ['<unconditional>\x00']*len(text_inputs)
    for i in range(len(text_inputs)):
        text_inputs[i] = text_inputs[i]+' Generate an image based on this description.\x00'

    ori_batchsize = len(text_inputs)

    
    with torch.no_grad():
        if guidance_scale > 1:
            model_inputs = tokenizer(text_inputs + uncondition_text_inputs, return_tensors="pt", padding=True).to('cuda')
        else:
            model_inputs = tokenizer(text_inputs, return_tensors="pt", padding=True).to('cuda')
        model_kwargs = {'attention_mask':model_inputs.pop('attention_mask'), 'use_cache': True}
        input_ids = model_inputs.pop('input_ids')
        batch_size, cur_len = input_ids.shape
        if "inputs_embeds" in model_kwargs:
            cur_len = model_kwargs["inputs_embeds"].shape[1]
        model_kwargs["cache_position"] = torch.arange(cur_len, device=input_ids.device)
        
        with torch.no_grad():
            sampling_kwargs={'temperature': temperature, 'top_k': top_K, 'top_p': top_P, 'sample_logits': True}
            pred_tokens = []
            input_multi_ids = None
            for i in tqdm(range(256)):
                model_inputs = vqllm.prepare_inputs_for_generation(input_ids, **model_kwargs)   
                outputs = vqllm.T2I_forward_withcache(
                    **model_inputs,
                    input_multi_ids=input_multi_ids,
                    return_dict=True,
                    output_attentions=False,
                    output_hidden_states=False,
                )
                next_embed = outputs['last_hidden_state'][:, -1:, :]
                indices_arhead = []

                for i_head in range(num_codebooks):
                    ar_next_embed = vqllm.ar_head(
                        inputs_embeds=next_embed,
                        use_cache=False,
                        output_attentions=False,
                        output_hidden_states=False,
                        return_dict=False,
                        )
                    next_token_logits = vqllm.ar_head.linear_head(ar_next_embed[0])
                    if guidance_scale > 1:
                        cond_logits, uncond_logits = torch.split(next_token_logits, len(next_token_logits) // 2, dim=0)
                        cfg_logits = uncond_logits + (cond_logits - uncond_logits) * guidance_scale
                        half_next_token, _ = sample(cfg_logits, **sampling_kwargs)
                        # pred_tokens.append(half_next_token)
                        next_token = torch.cat([half_next_token, half_next_token])  # [bz,1]
                    else:
                        next_token, next_prob = sample(next_token_logits, **sampling_kwargs)
                        # pred_tokens.append(next_token)
                    indices_arhead.append(next_token)
                    if i_head < num_codebooks - 1:
                        predicted_embed = vqllm.ar_head.codebooks[i_head](next_token)
                        next_embed = torch.cat([next_embed, predicted_embed], dim=1)

                pred_tokens.append(torch.cat(indices_arhead, dim=1))  # [numcodebook,bz*2]
                input_multi_ids = torch.stack(pred_tokens, dim=-1)
                fake_id = torch.zeros_like(input_ids[:,:1])
                input_ids = torch.cat([input_ids, fake_id], dim=-1) # add fake id for cache
                
                model_kwargs = vqllm._update_model_kwargs_for_generation(
                    outputs,
                    model_kwargs,
                    is_encoder_decoder=vqllm.config.is_encoder_decoder,
                )
            del sampling_kwargs
            del model_inputs
            del outputs
            del model_kwargs
            # image_vq_id = input_ids[:,prompt_length:prompt_length+256]-ori_vocabe_size
            image_vq_id = torch.stack(pred_tokens, dim=-1)[:ori_batchsize]
        
        generated_image_list = []
        rec_images = vq_model.idx_to_img(image_vq_id)
        for index, rec_image in enumerate(rec_images):
            rec_img = PILtransform(rec_image.squeeze(0).add(1).mul_(0.5).clamp_(0, 1))
            generated_image_list.append(rec_img)

        torch.cuda.empty_cache()
        yield show_gallery(generated_image_list)
 

chatbot_T2I=gr.Chatbot(height=600)
chat_input_T2I = gr.Textbox(placeholder="Enter text prompts...", show_label=False)

chatbot_I2T=gr.Chatbot(placeholder=PLACEHOLDER, scale=1)
chat_input_I2T = gr.MultimodalTextbox(interactive=True, file_types=["image"], placeholder="Enter message or upload file...", show_label=False)


with gr.Blocks(fill_height=True) as demo:

    gr.Markdown(title_html)
    gr.Markdown(links_html)  
    gr.Markdown(introduction)

    with gr.Tab("Text To Image"):

        description="Enter a text prompt or simply try one of the examples below to generate 4 images at once. Click to display the full image. You can configure hyperparameters for image generation in the Advanced Settings. "
        gr.Markdown(description)  
        with gr.Accordion("⚙️ Advanced Settings", open=False):
            with gr.Row():
                guidance_scale = gr.Slider(1.0, 20.0, value=7.0, label="Guidance Scale")
                temperature = gr.Slider(0.0, 1.0, value=1.0, label="temperature")
                top_K = gr.Slider(1, 4096, value=2048, label="Top K")
                top_P = gr.Slider(0.0, 1.0, value=1.0, label="Top P")
 
        aaa = gr.ChatInterface(
        fn=bot_streaming_T2I,
        examples=[
            ["cherry tree on the surface of the moon", 5.0, 1.0, 2048, 1.0],
            ["New York City at night with starry night vincent van gogh style", 5.0, 1.0, 2048, 1.0],
            ["cavalier king charles spaniel being cute and ultra realistic with cute sunglasses", 5.0, 1.0, 2048, 1.0],
            ["anthophomorphic Shaman owl portrait, light rays, facepaint, detailed, digital photography", 5.0, 1.0, 2048, 1.0],
            ["denzel washington as lor krishna front facing looking straight into the eye in the battlefield of kurukshetra", 5.0, 1.0, 2048, 1.0],
            ["realxing mountain scene, warm colors, sunset, river in front of mountain, pine trees, oil painting, photo realistic, blue ambiant lighting", 5.0, 1.0, 2048, 1.0],
            ["the ship of the dead by aaron hawthorne, in the style of en plein air beach scenes, ian miller, jasper francis cropsey, joram roukes, emotional and dramatic scenes, rusty debris, danish golden age, sunset", 5.0, 1.0, 2048, 1.0],
            ["japanese sakura bonsai, best quality, ultra high res, scene featuring volumetric lighting, Urban alleyway, warm color temperature, Straight On, variable depth of field, dynamic composition", 5.0, 1.0, 2048, 1.0],
        ],
        stop_btn="Stop Generation",
        additional_inputs = [guidance_scale, temperature, top_K, top_P],
        additional_inputs_accordion="⚙️ Advanced Settings",
        multimodal=False,
        cache_examples=False,
        textbox=chat_input_T2I,
        chatbot=chatbot_T2I,
        fill_height=True,
        )
 
    with gr.Tab("Image To Text"):
        bbb = gr.ChatInterface(
            fn=bot_streaming_I2T,
            examples=[{"text": "How to make this pastry?", "files": ["./baklava.png"]}],
            description="Upload an image and start chatting about it, or simply try one of the examples below. If you don't upload an image, you will receive an error.",
            stop_btn="Stop Generation",
            multimodal=True,
            cache_examples=False,
            textbox=chat_input_I2T,
            chatbot=chatbot_I2T,
            )

# demo.queue(api_open=False)
demo.launch(allowed_paths=["./"], share=True )