v33ts commited on
Commit
82d3034
·
verified ·
1 Parent(s): 4a2c676

Upload models/Joy_caption_two/app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. models/Joy_caption_two/app.py +336 -0
models/Joy_caption_two/app.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ from huggingface_hub import InferenceClient
4
+ from torch import nn
5
+ from transformers import AutoModel, AutoProcessor, AutoTokenizer, PreTrainedTokenizer, PreTrainedTokenizerFast, AutoModelForCausalLM
6
+ from pathlib import Path
7
+ import torch
8
+ import torch.amp.autocast_mode
9
+ from PIL import Image
10
+ import os
11
+ import torchvision.transforms.functional as TVF
12
+
13
+
14
+ CLIP_PATH = "google/siglip-so400m-patch14-384"
15
+ CHECKPOINT_PATH = Path("cgrkzexw-599808")
16
+ TITLE = "<h1><center>JoyCaption Alpha Two (2024-09-26a)</center></h1>"
17
+ CAPTION_TYPE_MAP = {
18
+ "Descriptive": [
19
+ "Write a descriptive caption for this image in a formal tone.",
20
+ "Write a descriptive caption for this image in a formal tone within {word_count} words.",
21
+ "Write a {length} descriptive caption for this image in a formal tone.",
22
+ ],
23
+ "Descriptive (Informal)": [
24
+ "Write a descriptive caption for this image in a casual tone.",
25
+ "Write a descriptive caption for this image in a casual tone within {word_count} words.",
26
+ "Write a {length} descriptive caption for this image in a casual tone.",
27
+ ],
28
+ "Training Prompt": [
29
+ "Write a stable diffusion prompt for this image.",
30
+ "Write a stable diffusion prompt for this image within {word_count} words.",
31
+ "Write a {length} stable diffusion prompt for this image.",
32
+ ],
33
+ "MidJourney": [
34
+ "Write a MidJourney prompt for this image.",
35
+ "Write a MidJourney prompt for this image within {word_count} words.",
36
+ "Write a {length} MidJourney prompt for this image.",
37
+ ],
38
+ "Booru tag list": [
39
+ "Write a list of Booru tags for this image.",
40
+ "Write a list of Booru tags for this image within {word_count} words.",
41
+ "Write a {length} list of Booru tags for this image.",
42
+ ],
43
+ "Booru-like tag list": [
44
+ "Write a list of Booru-like tags for this image.",
45
+ "Write a list of Booru-like tags for this image within {word_count} words.",
46
+ "Write a {length} list of Booru-like tags for this image.",
47
+ ],
48
+ "Art Critic": [
49
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc.",
50
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it within {word_count} words.",
51
+ "Analyze this image like an art critic would with information about its composition, style, symbolism, the use of color, light, any artistic movement it might belong to, etc. Keep it {length}.",
52
+ ],
53
+ "Product Listing": [
54
+ "Write a caption for this image as though it were a product listing.",
55
+ "Write a caption for this image as though it were a product listing. Keep it under {word_count} words.",
56
+ "Write a {length} caption for this image as though it were a product listing.",
57
+ ],
58
+ "Social Media Post": [
59
+ "Write a caption for this image as if it were being used for a social media post.",
60
+ "Write a caption for this image as if it were being used for a social media post. Limit the caption to {word_count} words.",
61
+ "Write a {length} caption for this image as if it were being used for a social media post.",
62
+ ],
63
+ }
64
+
65
+ HF_TOKEN = os.environ.get("HF_TOKEN", None)
66
+
67
+
68
+ class ImageAdapter(nn.Module):
69
+ def __init__(self, input_features: int, output_features: int, ln1: bool, pos_emb: bool, num_image_tokens: int, deep_extract: bool):
70
+ super().__init__()
71
+ self.deep_extract = deep_extract
72
+
73
+ if self.deep_extract:
74
+ input_features = input_features * 5
75
+
76
+ self.linear1 = nn.Linear(input_features, output_features)
77
+ self.activation = nn.GELU()
78
+ self.linear2 = nn.Linear(output_features, output_features)
79
+ self.ln1 = nn.Identity() if not ln1 else nn.LayerNorm(input_features)
80
+ self.pos_emb = None if not pos_emb else nn.Parameter(torch.zeros(num_image_tokens, input_features))
81
+
82
+ # Other tokens (<|image_start|>, <|image_end|>, <|eot_id|>)
83
+ self.other_tokens = nn.Embedding(3, output_features)
84
+ self.other_tokens.weight.data.normal_(mean=0.0, std=0.02) # Matches HF's implementation of llama3
85
+
86
+ def forward(self, vision_outputs: torch.Tensor):
87
+ if self.deep_extract:
88
+ x = torch.concat((
89
+ vision_outputs[-2],
90
+ vision_outputs[3],
91
+ vision_outputs[7],
92
+ vision_outputs[13],
93
+ vision_outputs[20],
94
+ ), dim=-1)
95
+ assert len(x.shape) == 3, f"Expected 3, got {len(x.shape)}" # batch, tokens, features
96
+ assert x.shape[-1] == vision_outputs[-2].shape[-1] * 5, f"Expected {vision_outputs[-2].shape[-1] * 5}, got {x.shape[-1]}"
97
+ else:
98
+ x = vision_outputs[-2]
99
+
100
+ x = self.ln1(x)
101
+
102
+ if self.pos_emb is not None:
103
+ assert x.shape[-2:] == self.pos_emb.shape, f"Expected {self.pos_emb.shape}, got {x.shape[-2:]}"
104
+ x = x + self.pos_emb
105
+
106
+ x = self.linear1(x)
107
+ x = self.activation(x)
108
+ x = self.linear2(x)
109
+
110
+ # <|image_start|>, IMAGE, <|image_end|>
111
+ other_tokens = self.other_tokens(torch.tensor([0, 1], device=self.other_tokens.weight.device).expand(x.shape[0], -1))
112
+ assert other_tokens.shape == (x.shape[0], 2, x.shape[2]), f"Expected {(x.shape[0], 2, x.shape[2])}, got {other_tokens.shape}"
113
+ x = torch.cat((other_tokens[:, 0:1], x, other_tokens[:, 1:2]), dim=1)
114
+
115
+ return x
116
+
117
+ def get_eot_embedding(self):
118
+ return self.other_tokens(torch.tensor([2], device=self.other_tokens.weight.device)).squeeze(0)
119
+
120
+
121
+
122
+ # Load CLIP
123
+ print("Loading CLIP")
124
+ clip_processor = AutoProcessor.from_pretrained(CLIP_PATH)
125
+ clip_model = AutoModel.from_pretrained(CLIP_PATH)
126
+ clip_model = clip_model.vision_model
127
+
128
+ assert (CHECKPOINT_PATH / "clip_model.pt").exists()
129
+ print("Loading VLM's custom vision model")
130
+ checkpoint = torch.load(CHECKPOINT_PATH / "clip_model.pt", map_location='cpu')
131
+ checkpoint = {k.replace("_orig_mod.module.", ""): v for k, v in checkpoint.items()}
132
+ clip_model.load_state_dict(checkpoint)
133
+ del checkpoint
134
+
135
+ clip_model.eval()
136
+ clip_model.requires_grad_(False)
137
+ clip_model.to("cuda")
138
+
139
+
140
+ # Tokenizer
141
+ print("Loading tokenizer")
142
+ tokenizer = AutoTokenizer.from_pretrained(CHECKPOINT_PATH / "text_model", use_fast=True)
143
+ assert isinstance(tokenizer, PreTrainedTokenizer) or isinstance(tokenizer, PreTrainedTokenizerFast), f"Tokenizer is of type {type(tokenizer)}"
144
+
145
+ # LLM
146
+ print("Loading LLM")
147
+ print("Loading VLM's custom text model")
148
+ text_model = AutoModelForCausalLM.from_pretrained(CHECKPOINT_PATH / "text_model", device_map=0, torch_dtype=torch.bfloat16)
149
+ text_model.eval()
150
+
151
+ # Image Adapter
152
+ print("Loading image adapter")
153
+ image_adapter = ImageAdapter(clip_model.config.hidden_size, text_model.config.hidden_size, False, False, 38, False)
154
+ image_adapter.load_state_dict(torch.load(CHECKPOINT_PATH / "image_adapter.pt", map_location="cpu"))
155
+ image_adapter.eval()
156
+ image_adapter.to("cuda")
157
+
158
+
159
+ @spaces.GPU()
160
+ @torch.no_grad()
161
+ def stream_chat(input_image: Image.Image, caption_type: str, caption_length: str | int, extra_options: list[str], name_input: str, custom_prompt: str) -> tuple[str, str]:
162
+ torch.cuda.empty_cache()
163
+
164
+ # 'any' means no length specified
165
+ length = None if caption_length == "any" else caption_length
166
+
167
+ if isinstance(length, str):
168
+ try:
169
+ length = int(length)
170
+ except ValueError:
171
+ pass
172
+
173
+ # Build prompt
174
+ if length is None:
175
+ map_idx = 0
176
+ elif isinstance(length, int):
177
+ map_idx = 1
178
+ elif isinstance(length, str):
179
+ map_idx = 2
180
+ else:
181
+ raise ValueError(f"Invalid caption length: {length}")
182
+
183
+ prompt_str = CAPTION_TYPE_MAP[caption_type][map_idx]
184
+
185
+ # Add extra options
186
+ if len(extra_options) > 0:
187
+ prompt_str += " " + " ".join(extra_options)
188
+
189
+ # Add name, length, word_count
190
+ prompt_str = prompt_str.format(name=name_input, length=caption_length, word_count=caption_length)
191
+
192
+ if custom_prompt.strip() != "":
193
+ prompt_str = custom_prompt.strip()
194
+
195
+ # For debugging
196
+ print(f"Prompt: {prompt_str}")
197
+
198
+ # Preprocess image
199
+ # NOTE: I found the default processor for so400M to have worse results than just using PIL directly
200
+ #image = clip_processor(images=input_image, return_tensors='pt').pixel_values
201
+ image = input_image.resize((384, 384), Image.LANCZOS)
202
+ pixel_values = TVF.pil_to_tensor(image).unsqueeze(0) / 255.0
203
+ pixel_values = TVF.normalize(pixel_values, [0.5], [0.5])
204
+ pixel_values = pixel_values.to('cuda')
205
+
206
+ # Embed image
207
+ # This results in Batch x Image Tokens x Features
208
+ with torch.amp.autocast_mode.autocast('cuda', enabled=True):
209
+ vision_outputs = clip_model(pixel_values=pixel_values, output_hidden_states=True)
210
+ embedded_images = image_adapter(vision_outputs.hidden_states)
211
+ embedded_images = embedded_images.to('cuda')
212
+
213
+ # Build the conversation
214
+ convo = [
215
+ {
216
+ "role": "system",
217
+ "content": "You are a helpful image captioner.",
218
+ },
219
+ {
220
+ "role": "user",
221
+ "content": prompt_str,
222
+ },
223
+ ]
224
+
225
+ # Format the conversation
226
+ convo_string = tokenizer.apply_chat_template(convo, tokenize = False, add_generation_prompt = True)
227
+ assert isinstance(convo_string, str)
228
+
229
+ # Tokenize the conversation
230
+ # prompt_str is tokenized separately so we can do the calculations below
231
+ convo_tokens = tokenizer.encode(convo_string, return_tensors="pt", add_special_tokens=False, truncation=False)
232
+ prompt_tokens = tokenizer.encode(prompt_str, return_tensors="pt", add_special_tokens=False, truncation=False)
233
+ assert isinstance(convo_tokens, torch.Tensor) and isinstance(prompt_tokens, torch.Tensor)
234
+ convo_tokens = convo_tokens.squeeze(0) # Squeeze just to make the following easier
235
+ prompt_tokens = prompt_tokens.squeeze(0)
236
+
237
+ # Calculate where to inject the image
238
+ eot_id_indices = (convo_tokens == tokenizer.convert_tokens_to_ids("<|eot_id|>")).nonzero(as_tuple=True)[0].tolist()
239
+ assert len(eot_id_indices) == 2, f"Expected 2 <|eot_id|> tokens, got {len(eot_id_indices)}"
240
+
241
+ preamble_len = eot_id_indices[1] - prompt_tokens.shape[0] # Number of tokens before the prompt
242
+
243
+ # Embed the tokens
244
+ convo_embeds = text_model.model.embed_tokens(convo_tokens.unsqueeze(0).to('cuda'))
245
+
246
+ # Construct the input
247
+ input_embeds = torch.cat([
248
+ convo_embeds[:, :preamble_len], # Part before the prompt
249
+ embedded_images.to(dtype=convo_embeds.dtype), # Image
250
+ convo_embeds[:, preamble_len:], # The prompt and anything after it
251
+ ], dim=1).to('cuda')
252
+
253
+ input_ids = torch.cat([
254
+ convo_tokens[:preamble_len].unsqueeze(0),
255
+ torch.zeros((1, embedded_images.shape[1]), dtype=torch.long), # Dummy tokens for the image (TODO: Should probably use a special token here so as not to confuse any generation algorithms that might be inspecting the input)
256
+ convo_tokens[preamble_len:].unsqueeze(0),
257
+ ], dim=1).to('cuda')
258
+ attention_mask = torch.ones_like(input_ids)
259
+
260
+ # Debugging
261
+ print(f"Input to model: {repr(tokenizer.decode(input_ids[0]))}")
262
+
263
+ #generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=False, suppress_tokens=None)
264
+ #generate_ids = text_model.generate(input_ids, inputs_embeds=inputs_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, top_k=10, temperature=0.5, suppress_tokens=None)
265
+ generate_ids = text_model.generate(input_ids, inputs_embeds=input_embeds, attention_mask=attention_mask, max_new_tokens=300, do_sample=True, suppress_tokens=None) # Uses the default which is temp=0.6, top_p=0.9
266
+
267
+ # Trim off the prompt
268
+ generate_ids = generate_ids[:, input_ids.shape[1]:]
269
+ if generate_ids[0][-1] == tokenizer.eos_token_id or generate_ids[0][-1] == tokenizer.convert_tokens_to_ids("<|eot_id|>"):
270
+ generate_ids = generate_ids[:, :-1]
271
+
272
+ caption = tokenizer.batch_decode(generate_ids, skip_special_tokens=False, clean_up_tokenization_spaces=False)[0]
273
+
274
+ return prompt_str, caption.strip()
275
+
276
+
277
+ with gr.Blocks() as demo:
278
+ gr.HTML(TITLE)
279
+
280
+ with gr.Row():
281
+ with gr.Column():
282
+ input_image = gr.Image(type="pil", label="Input Image")
283
+
284
+ caption_type = gr.Dropdown(
285
+ choices=["Descriptive", "Descriptive (Informal)", "Training Prompt", "MidJourney", "Booru tag list", "Booru-like tag list", "Art Critic", "Product Listing", "Social Media Post"],
286
+ label="Caption Type",
287
+ value="Descriptive",
288
+ )
289
+
290
+ caption_length = gr.Dropdown(
291
+ choices=["any", "very short", "short", "medium-length", "long", "very long"] +
292
+ [str(i) for i in range(20, 261, 10)],
293
+ label="Caption Length",
294
+ value="long",
295
+ )
296
+
297
+ extra_options = gr.CheckboxGroup(
298
+ choices=[
299
+ "If there is a person/character in the image you must refer to them as {name}.",
300
+ "Do NOT include information about people/characters that cannot be changed (like ethnicity, gender, etc), but do still include changeable attributes (like hair style).",
301
+ "Include information about lighting.",
302
+ "Include information about camera angle.",
303
+ "Include information about whether there is a watermark or not.",
304
+ "Include information about whether there are JPEG artifacts or not.",
305
+ "If it is a photo you MUST include information about what camera was likely used and details such as aperture, shutter speed, ISO, etc.",
306
+ "Do NOT include anything sexual; keep it PG.",
307
+ "Do NOT mention the image's resolution.",
308
+ "You MUST include information about the subjective aesthetic quality of the image from low to very high.",
309
+ "Include information on the image's composition style, such as leading lines, rule of thirds, or symmetry.",
310
+ "Do NOT mention any text that is in the image.",
311
+ "Specify the depth of field and whether the background is in focus or blurred.",
312
+ "If applicable, mention the likely use of artificial or natural lighting sources.",
313
+ "Do NOT use any ambiguous language.",
314
+ "Include whether the image is sfw, suggestive, or nsfw.",
315
+ "ONLY describe the most important elements of the image."
316
+ ],
317
+ label="Extra Options"
318
+ )
319
+
320
+ name_input = gr.Textbox(label="Person/Character Name (if applicable)")
321
+ gr.Markdown("**Note:** Name input is only used if an Extra Option is selected that requires it.")
322
+
323
+ custom_prompt = gr.Textbox(label="Custom Prompt (optional, will override all other settings)")
324
+ gr.Markdown("**Note:** Alpha Two is not a general instruction follower and will not follow prompts outside its training data well. Use this feature with caution.")
325
+
326
+ run_button = gr.Button("Caption")
327
+
328
+ with gr.Column():
329
+ output_prompt = gr.Textbox(label="Prompt that was used")
330
+ output_caption = gr.Textbox(label="Caption")
331
+
332
+ run_button.click(fn=stream_chat, inputs=[input_image, caption_type, caption_length, extra_options, name_input, custom_prompt], outputs=[output_prompt, output_caption])
333
+
334
+
335
+ if __name__ == "__main__":
336
+ demo.launch()