Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files6 unmodified lines78910111213141516178 unmodified lines2627282930313233346 unmodified lines414243444546474849505142 unmodified lines94959697989910010110210310410510610710810911011111211311411 unmodified lines1261271281291301311321331341356 unmodified lines14214314414514614714814915015115215315415515615715815916016116216316416516616716816917017110 unmodified lines1821831841851861871881891901911926 unmodified lines1992002012022032042052061 unmodified line2082092102112122132142152168 unmodified lines2252262272282292302312326 unmodified linesimport numpy as npimport osimport spaces # Import spaces for ZeroGPU compatibility# Load model and processormodel_path = "deepseek-ai/Janus-1.3B"config = AutoConfig.from_pretrained(model_path)language_config = config.language_configlanguage_config._attn_implementation = 'eager'8 unmodified linesvl_chat_processor = VLChatProcessor.from_pretrained(model_path)tokenizer = vl_chat_processor.tokenizercuda_device = 'cuda' if torch.cuda.is_available() else 'cpu'# Multimodal Understanding function@torch.inference_mode()@spaces.GPU(duration=120)# Multimodal Understanding functiondef multimodal_understanding(image, question, seed, top_p, temperature):# Clear CUDA cache before generating6 unmodified linesconversation = [{"role": "User","content": f"<image_placeholder>\n{question}","images": [image],},{"role": "Assistant", "content": ""},]pil_images = [Image.fromarray(image)]42 unmodified linespkv = Nonefor i in range(image_token_num_per_image):outputs = vl_gpt.language_model.model(inputs_embeds=inputs_embeds,use_cache=True,past_key_values=pkv)pkv = outputs.past_key_valueshidden_states = outputs.last_hidden_statelogits = vl_gpt.gen_head(hidden_states[:, -1, :])logit_cond = logits[0::2, :]logit_uncond = logits[1::2, :]logits = logit_uncond + cfg_weight * (logit_cond - logit_uncond)probs = torch.softmax(logits / temperature, dim=-1)next_token = torch.multinomial(probs, num_samples=1)generated_tokens[:, i] = next_token.squeeze(dim=-1)next_token = torch.cat([next_token.unsqueeze(dim=1), next_token.unsqueeze(dim=1)], dim=1).view(-1)img_embeds = vl_gpt.prepare_gen_img_embeds(next_token)inputs_embeds = img_embeds.unsqueeze(dim=1)patches = vl_gpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int),shape=[parallel_size, 8, width // patch_size, height // patch_size])11 unmodified lines@torch.inference_mode()@spaces.GPU(duration=120) # Specify a duration to avoid timeoutdef generate_image(prompt,seed=None,guidance=5):# Clear CUDA cache and avoid tracking gradientstorch.cuda.empty_cache()# Set the seed for reproducible results6 unmodified linesparallel_size = 5with torch.no_grad():messages = [{'role': 'User', 'content': prompt},{'role': 'Assistant', 'content': ''}]text = vl_chat_processor.apply_sft_template_for_multi_turn_prompts(conversations=messages,sft_format=vl_chat_processor.sft_format,system_prompt='')text = text + vl_chat_processor.image_start_taginput_ids = torch.LongTensor(tokenizer.encode(text))output, patches = generate(input_ids,width // 16 * 16,height // 16 * 16,cfg_weight=guidance,parallel_size=parallel_size)images = unpack(patches,width // 16 * 16,height // 16 * 16)return [Image.fromarray(images[i]).resize((1024, 1024), Image.LANCZOS) for i in range(parallel_size)]# Gradio interfacewith gr.Blocks() as demo:gr.Markdown(value="# Multimodal Understanding")# with gr.Row():with gr.Row():image_input = gr.Image()with gr.Column():10 unmodified linesexamples=[["explain this meme","doge.png",],["Convert the formula into latex code.","equation.png",],],inputs=[question_input, image_input],6 unmodified lineswith gr.Row():cfg_weight_input = gr.Slider(minimum=1, maximum=10, value=5, step=0.5, label="CFG Weight")prompt_input = gr.Textbox(label="Prompt")seed_input = gr.Number(label="Seed (Optional)", precision=0, value=12345)generation_button = gr.Button("Generate Images")1 unmodified lineimage_output = gr.Gallery(label="Generated Images", columns=2, rows=2, height=300)examples_t2i = gr.Examples(label="Text to image generation examples. (Tips for designing prompts: Adding description like 'digital art' at the end of the prompt or writing the prompt in more detail can help produce better images!)",examples=["Master shifu racoon wearing drip attire as a street gangster.","A cute and adorable baby fox with big brown eyes, autumn leaves in the background enchanting,immortal,fluffy, shiny mane,Petals,fairyism,unreal engine 5 and Octane Render,highly detailed, photorealistic, cinematic, natural colors.","The image features an intricately designed eye set against a circular backdrop adorned with ornate swirl patterns that evoke both realism and surrealism. At the center of attention is a strikingly vivid blue iris surrounded by delicate veins radiating outward from the pupil to create depth and intensity. The eyelashes are long and dark, casting subtle shadows on the skin around them which appears smooth yet slightly textured as if aged or weathered over time.\n\nAbove the eye, there's a stone-like structure resembling part of classical architecture, adding layers of mystery and timeless elegance to the composition. This architectural element contrasts sharply but harmoniously with the organic curves surrounding it. Below the eye lies another decorative motif reminiscent of baroque artistry, further enhancing the overall sense of eternity encapsulated within each meticulously crafted detail. \n\nOverall, the atmosphere exudes a mysterious aura intertwined seamlessly with elements suggesting timelessness, achieved through the juxtaposition of realistic textures and surreal artistic flourishes. Each component\u2014from the intricate designs framing the eye to the ancient-looking stone piece above\u2014contributes uniquely towards creating a visually captivating tableau imbued with enigmatic allure.",],8 unmodified linesgeneration_button.click(fn=generate_image,inputs=[prompt_input, seed_input, cfg_weight_input],outputs=image_output)demo.launch(share=True)6 unmodified lines7891011121314151617188 unmodified lines2728293031323334356 unmodified lines424344454647484950515242 unmodified lines959697989910010110210310410510610710810911011111211311411511611711811912011 unmodified lines1321331341351361371381391401411426 unmodified lines14915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817910 unmodified lines1901911921931941951961971981992006 unmodified lines2072082092102112122132142151 unmodified line2172182192202212222232242252262272288 unmodified lines2372382392402412422432442456 unmodified linesimport numpy as npimport osimport time# import spaces # Import spaces for ZeroGPU compatibility# Load model and processormodel_path = "deepseek-ai/Janus-Pro-7B"config = AutoConfig.from_pretrained(model_path)language_config = config.language_configlanguage_config._attn_implementation = 'eager'8 unmodified linesvl_chat_processor = VLChatProcessor.from_pretrained(model_path)tokenizer = vl_chat_processor.tokenizercuda_device = 'cuda' if torch.cuda.is_available() else 'cpu'@torch.inference_mode()# @spaces.GPU(duration=120)# Multimodal Understanding functiondef multimodal_understanding(image, question, seed, top_p, temperature):# Clear CUDA cache before generating6 unmodified linesconversation = [{"role": "<|User|>","content": f"<image_placeholder>\n{question}","images": [image],},{"role": "<|Assistant|>", "content": ""},]pil_images = [Image.fromarray(image)]42 unmodified linespkv = Nonefor i in range(image_token_num_per_image):with torch.no_grad():outputs = vl_gpt.language_model.model(inputs_embeds=inputs_embeds,use_cache=True,past_key_values=pkv)pkv = outputs.past_key_valueshidden_states = outputs.last_hidden_statelogits = vl_gpt.gen_head(hidden_states[:, -1, :])logit_cond = logits[0::2, :]logit_uncond = logits[1::2, :]logits = logit_uncond + cfg_weight * (logit_cond - logit_uncond)probs = torch.softmax(logits / temperature, dim=-1)next_token = torch.multinomial(probs, num_samples=1)generated_tokens[:, i] = next_token.squeeze(dim=-1)next_token = torch.cat([next_token.unsqueeze(dim=1), next_token.unsqueeze(dim=1)], dim=1).view(-1)img_embeds = vl_gpt.prepare_gen_img_embeds(next_token)inputs_embeds = img_embeds.unsqueeze(dim=1)patches = vl_gpt.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int),shape=[parallel_size, 8, width // patch_size, height // patch_size])11 unmodified lines@torch.inference_mode()# @spaces.GPU(duration=120) # Specify a duration to avoid timeoutdef generate_image(prompt,seed=None,guidance=5,t2i_temperature=1.0):# Clear CUDA cache and avoid tracking gradientstorch.cuda.empty_cache()# Set the seed for reproducible results6 unmodified linesparallel_size = 5with torch.no_grad():messages = [{'role': '<|User|>', 'content': prompt},{'role': '<|Assistant|>', 'content': ''}]text = vl_chat_processor.apply_sft_template_for_multi_turn_prompts(conversations=messages,sft_format=vl_chat_processor.sft_format,system_prompt='')text = text + vl_chat_processor.image_start_taginput_ids = torch.LongTensor(tokenizer.encode(text))output, patches = generate(input_ids,width // 16 * 16,height // 16 * 16,cfg_weight=guidance,parallel_size=parallel_size,temperature=t2i_temperature)images = unpack(patches,width // 16 * 16,height // 16 * 16,parallel_size=parallel_size)return [Image.fromarray(images[i]).resize((768, 768), Image.LANCZOS) for i in range(parallel_size)]# Gradio interfacewith gr.Blocks() as demo:gr.Markdown(value="# Multimodal Understanding")with gr.Row():image_input = gr.Image()with gr.Column():10 unmodified linesexamples=[["explain this meme","images/doge.png",],["Convert the formula into latex code.","images/equation.png",],],inputs=[question_input, image_input],6 unmodified lineswith gr.Row():cfg_weight_input = gr.Slider(minimum=1, maximum=10, value=5, step=0.5, label="CFG Weight")t2i_temperature = gr.Slider(minimum=0, maximum=1, value=1.0, step=0.05, label="temperature")prompt_input = gr.Textbox(label="Prompt. (Prompt in more detail can help produce better images!)")seed_input = gr.Number(label="Seed (Optional)", precision=0, value=12345)generation_button = gr.Button("Generate Images")1 unmodified lineimage_output = gr.Gallery(label="Generated Images", columns=2, rows=2, height=300)examples_t2i = gr.Examples(label="Text to image generation examples.",examples=["Master shifu racoon wearing drip attire as a street gangster.","The face of a beautiful girl","Astronaut in a jungle, cold color palette, muted colors, detailed, 8k","A glass of red wine on a reflective surface.","A cute and adorable baby fox with big brown eyes, autumn leaves in the background enchanting,immortal,fluffy, shiny mane,Petals,fairyism,unreal engine 5 and Octane Render,highly detailed, photorealistic, cinematic, natural colors.","The image features an intricately designed eye set against a circular backdrop adorned with ornate swirl patterns that evoke both realism and surrealism. At the center of attention is a strikingly vivid blue iris surrounded by delicate veins radiating outward from the pupil to create depth and intensity. The eyelashes are long and dark, casting subtle shadows on the skin around them which appears smooth yet slightly textured as if aged or weathered over time.\n\nAbove the eye, there's a stone-like structure resembling part of classical architecture, adding layers of mystery and timeless elegance to the composition. This architectural element contrasts sharply but harmoniously with the organic curves surrounding it. Below the eye lies another decorative motif reminiscent of baroque artistry, further enhancing the overall sense of eternity encapsulated within each meticulously crafted detail. \n\nOverall, the atmosphere exudes a mysterious aura intertwined seamlessly with elements suggesting timelessness, achieved through the juxtaposition of realistic textures and surreal artistic flourishes. Each component\u2014from the intricate designs framing the eye to the ancient-looking stone piece above\u2014contributes uniquely towards creating a visually captivating tableau imbued with enigmatic allure.",],8 unmodified linesgeneration_button.click(fn=generate_image,inputs=[prompt_input, seed_input, cfg_weight_input, t2i_temperature],outputs=image_output)demo.launch(share=True)# demo.queue(concurrency_count=1, max_size=10).launch(server_name="0.0.0.0", server_port=37906, root_path="/path")
app.py+49-36