twodgirl commited on
Commit
e5fe5b6
1 Parent(s): c1587c5

Create demo.

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from janus.models import MultiModalityCausalLM, VLChatProcessor
3
+ from janus.utils.io import load_pil_images
4
+ import numpy as np
5
+ from PIL import Image
6
+ from transformers import AutoModelForCausalLM
7
+ import torch
8
+
9
+ ##
10
+ # Code from deepseek-ai/Janus
11
+ # Space from huggingface/twodgirl.
12
+
13
+ def generate(input_ids,
14
+ width,
15
+ height,
16
+ temperature: float = 1,
17
+ parallel_size: int = 1,
18
+ cfg_weight: float = 5,
19
+ image_token_num_per_image: int = 576,
20
+ patch_size: int = 16):
21
+ tokens = torch.zeros((parallel_size * 2, len(input_ids)), dtype=torch.int) #.cuda()
22
+ for i in range(parallel_size * 2):
23
+ tokens[i, :] = input_ids
24
+ if i % 2 != 0:
25
+ tokens[i, 1:-1] = processor.pad_id
26
+ inputs_embeds = model.language_model.get_input_embeddings()(tokens)
27
+ generated_tokens = torch.zeros((parallel_size, image_token_num_per_image), dtype=torch.int) #.cuda()
28
+
29
+ pkv = None
30
+ for i in range(image_token_num_per_image):
31
+ outputs = model.language_model.model(inputs_embeds=inputs_embeds,
32
+ use_cache=True,
33
+ past_key_values=pkv)
34
+ pkv = outputs.past_key_values
35
+ hidden_states = outputs.last_hidden_state
36
+ logits = model.gen_head(hidden_states[:, -1, :])
37
+ logit_cond = logits[0::2, :]
38
+ logit_uncond = logits[1::2, :]
39
+ logits = logit_uncond + cfg_weight * (logit_cond - logit_uncond)
40
+ probs = torch.softmax(logits / temperature, dim=-1)
41
+ next_token = torch.multinomial(probs, num_samples=1)
42
+ generated_tokens[:, i] = next_token.squeeze(dim=-1)
43
+ next_token = torch.cat([next_token.unsqueeze(dim=1), next_token.unsqueeze(dim=1)], dim=1).view(-1)
44
+ img_embeds = model.prepare_gen_img_embeds(next_token)
45
+ inputs_embeds = img_embeds.unsqueeze(dim=1)
46
+ patches = model.gen_vision_model.decode_code(generated_tokens.to(dtype=torch.int),
47
+ shape=[parallel_size, 8, width // patch_size, height // patch_size])
48
+
49
+ return generated_tokens.to(dtype=torch.int), patches
50
+
51
+ def unpack(dec, width, height, parallel_size=1):
52
+ dec = dec.to(torch.float32).cpu().numpy().transpose(0, 2, 3, 1)
53
+ dec = np.clip((dec + 1) / 2 * 255, 0, 255)
54
+
55
+ visual_img = np.zeros((parallel_size, width, height, 3), dtype=np.uint8)
56
+ visual_img[:, :, :] = dec
57
+
58
+ return visual_img
59
+
60
+ @torch.inference_mode()
61
+ def generate_image(prompt,
62
+ width,
63
+ height,
64
+ # num_steps,
65
+ guidance,
66
+ seed):
67
+ if seed > -1:
68
+ generator = torch.Generator('cpu').manual_seed(seed)
69
+ else:
70
+ generator = None
71
+ messages = [{'role': 'User', 'content': prompt},
72
+ {'role': 'Assistant', 'content': ''}]
73
+ text = processor.apply_sft_template_for_multi_turn_prompts(conversations=messages,
74
+ sft_format=processor.sft_format,
75
+ system_prompt='')
76
+ text = text + processor.image_start_tag
77
+ input_ids = torch.LongTensor(processor.tokenizer.encode(prompt))
78
+ output, patches = generate(input_ids,
79
+ width // 16 * 16,
80
+ height // 16 * 16,
81
+ cfg_weight=guidance)
82
+ images = unpack(patches,
83
+ width // 16 * 16,
84
+ height // 16 * 16)
85
+
86
+ return Image.fromarray(images[0]), seed, ''
87
+
88
+ with gr.Blocks() as demo:
89
+ with gr.Row():
90
+ with gr.Column():
91
+ prompt = gr.Textbox(label='Prompt', value='portrait, color, cinematic')
92
+ width = gr.Slider(256, 1536, 896, step=16, label='Width')
93
+ height = gr.Slider(256, 1536, 1152, step=16, label='Height')
94
+ guidance = gr.Slider(1.0, 10.0, 5, step=0.1, label='Guidance')
95
+ seed = gr.Number(-1, precision=0, label='Seed (-1 for random)')
96
+
97
+ generate_btn = gr.Button('Generate')
98
+
99
+ with gr.Column():
100
+ output_image = gr.Image(label='Generated Image')
101
+ seed_output = gr.Textbox(label='Used Seed')
102
+ intermediate_output = gr.Gallery(label='Output', elem_id='gallery', visible=False)
103
+
104
+ prompt.submit(
105
+ fn=generate_image,
106
+ inputs=[width, height, guidance, seed, prompt],
107
+ outputs=[output_image, seed_output, intermediate_output],
108
+ )
109
+ generate_btn.click(
110
+ fn=generate_image,
111
+ inputs=[width, height, guidance, seed, prompt],
112
+ outputs=[output_image, seed_output, intermediate_output],
113
+ )
114
+
115
+ if __name__ == '__main__':
116
+ model_path = 'deepseek-ai/Janus-1.3B'
117
+ processor: VLChatProcessor = VLChatProcessor.from_pretrained(model_path)
118
+ tokenizer = processor.tokenizer
119
+ model: MultiModalityCausalLM = AutoModelForCausalLM.from_pretrained(model_path, trust_remote_code=True)
120
+ model = model.to(torch.bfloat16) #.cuda()
121
+ demo.launch()