Andyson commited on
Commit
161a2b4
β€’
1 Parent(s): 33e54e3
app.py CHANGED
@@ -37,6 +37,7 @@ IMG_TOKEN = '<img_{:05d}>'
37
  IMG_FLAG = '<image>'
38
  num_img_in_tokens = 64
39
  num_img_out_tokens = 64
 
40
 
41
  resolution_grids = ['1x1', '1x2', '1x3', '1x4', '1x5', '1x6', '1x10', '2x1', '3x1', '4x1', '5x1', '6x1', '10x1', '2x2',
42
  '2x3', '3x2', '2x4', '4x2']
@@ -119,6 +120,7 @@ class LLMService:
119
  self.agent = hydra.utils.instantiate(agent_cfg, llm=llm)
120
 
121
  self.agent.eval().to(self.llm_device, dtype=self.dtype)
 
122
  print('Init agent mdoel Done')
123
 
124
  noise_scheduler = EulerDiscreteScheduler.from_pretrained(args.diffusion_path, subfolder="scheduler")
@@ -166,10 +168,13 @@ service = LLMService(args)
166
 
167
 
168
  @spaces.GPU
169
- def generate(text_list, image_list, max_new_tokens):
170
  with torch.no_grad():
 
171
  text_list = text_list.split(IMG_FLAG)
 
172
  top_p = 0.5
 
173
  assert len(text_list) == len(image_list) + 1
174
 
175
  image_tokens = BOI_TOKEN + ''.join(
@@ -181,31 +186,12 @@ def generate(text_list, image_list, max_new_tokens):
181
  embeds_cmp_mask = []
182
  embeds_gen_mask = []
183
 
184
- if service.multi_resolution:
185
- patch_pos = []
186
- image_patch_length = []
187
- image_size_list = []
188
-
189
  for idx, image_item in enumerate(image_list):
190
  if isinstance(image_item, str):
191
  image = decode_image(image_item)
192
  print('after decode image size:', image.size)
193
  input_images.append(image)
194
 
195
- # if service.multi_resolution:
196
- # image_size_list.append(image.size)
197
- # print('image size:', image.size)
198
- # image_tensor, patch_pos_tensor = process_anyres_image(image, service.image_transform,
199
- # service.grid_pinpoints,
200
- # service.base_resolution)
201
- # image_tensor_list.append(image_tensor)
202
- # patch_pos.append(patch_pos_tensor)
203
- # image_patch_length.append(image_tensor.shape[0])
204
- # print('image_patch_length', image_patch_length)
205
- # embeds_cmp_mask.extend([True] * image_tensor.shape[0])
206
- # embeds_gen_mask.extend([False] * image_tensor.shape[0])
207
- #
208
- # else:
209
  image_tensor = service.image_transform(image)
210
  image_tensor_list.append(image_tensor)
211
  embeds_cmp_mask.append(True)
@@ -213,23 +199,13 @@ def generate(text_list, image_list, max_new_tokens):
213
  else:
214
  raise ValueError
215
 
216
- if service.multi_resolution:
217
- pixel_values = torch.cat(image_tensor_list).to(service.vit_sd_device, dtype=service.dtype)
218
- patch_position = torch.cat(patch_pos, dim=0)
219
-
220
- image_tokens_list = []
221
- for patch_length in image_patch_length:
222
- image_tokens = ''
223
- for _ in range(patch_length - 1):
224
- image_tokens += BOP_TOKEN + ''.join(
225
- IMG_TOKEN.format(int(item)) for item in range(num_img_in_tokens)) + EOP_TOKEN
226
- image_tokens += BOI_TOKEN + ''.join(
227
- IMG_TOKEN.format(int(item)) for item in range(num_img_in_tokens)) + EOI_TOKEN
228
- image_tokens_list.append(image_tokens)
229
- else:
230
- pixel_values = torch.stack(image_tensor_list).to(service.vit_sd_device, dtype=service.dtype)
231
-
232
- image_embeds = service.visual_encoder(pixel_values)
233
  image_embeds = image_embeds.to(service.llm_device)
234
 
235
  embeds_cmp_mask = torch.tensor(embeds_cmp_mask, dtype=torch.bool).to(service.llm_device)
@@ -241,10 +217,21 @@ def generate(text_list, image_list, max_new_tokens):
241
  embeds_cmp_mask = None
242
  embeds_gen_mask = None
243
 
 
244
  input_text = image_tokens.join(text_list)
245
 
246
- print('input_text:', input_text)
247
  input_ids = service.tokenizer.encode(input_text, add_special_tokens=False)
 
 
 
 
 
 
 
 
 
 
248
  input_ids = [service.tokenizer.bos_token_id] + input_ids
249
 
250
  input_ids = torch.tensor(input_ids).to(service.llm_device, dtype=torch.long)
@@ -262,7 +249,10 @@ def generate(text_list, image_list, max_new_tokens):
262
  ids_gen_mask = ids_gen_mask.unsqueeze(0)
263
 
264
  error_msg = []
265
-
 
 
 
266
  output = service.agent.generate(
267
  tokenizer=service.tokenizer,
268
  input_ids=input_ids,
@@ -278,7 +268,6 @@ def generate(text_list, image_list, max_new_tokens):
278
 
279
  gen_imgs_base64_list = []
280
  generated_text = output['text']
281
- generated_text = generated_text.replace(EOI_TOKEN, IMG_FLAG).replace(service.tokenizer.eos_token, '')
282
 
283
  torch.cuda.empty_cache()
284
 
@@ -294,6 +283,7 @@ def generate(text_list, image_list, max_new_tokens):
294
  for img_idx in range(output['num_gen_imgs']):
295
  img_feat = img_gen_feat[img_idx:img_idx + 1]
296
  generated_image = service.sd_adapter.generate(image_embeds=img_feat, num_inference_steps=50)[0]
 
297
 
298
  # a = time.time()
299
  # service.sd_adapter = service.sd_adapter.cpu()
@@ -301,19 +291,19 @@ def generate(text_list, image_list, max_new_tokens):
301
  # service.agent = service.agent.to(service.vit_sd_device, dtype=service.dtype)
302
  # print("Loading finished: ", time.time() - a)
303
 
304
- print(input_text + generated_text)
305
- return {'text': generated_text, 'images': gen_imgs_base64_list, 'error_msg': error_msg}
306
 
307
 
308
- def http_bot(dialog_state, input_state, max_new_tokens, max_turns,
309
  request: gr.Request):
310
  print('input_state:', input_state)
311
-
312
- if len(dialog_state.messages) == 0 or dialog_state.messages[-1]['role'] != dialog_state.roles[0] or len(
313
  dialog_state.messages[-1]['message']['text'].strip(' ?.;!/')) == 0:
314
  return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
315
 
316
- if len(dialog_state.messages) > max_turns * 2:
317
  output_state = init_input_state()
318
  output_state['text'] = 'Error: History exceeds maximum rounds, please clear history and restart.'
319
  dialog_state.messages.append({'role': dialog_state.roles[1], 'message': output_state})
@@ -322,22 +312,40 @@ def http_bot(dialog_state, input_state, max_new_tokens, max_turns,
322
 
323
  prompt = dialog_state.get_prompt()
324
  text = prompt['text']
 
325
  max_new_tokens = int(max_new_tokens)
326
  images = prompt['images']
 
 
 
 
 
 
 
 
 
 
 
 
327
 
328
- results = generate(text, images, max_new_tokens)
329
  print('response: ', {'text': results['text'], 'error_msg': results['error_msg']})
330
 
331
  output_state = init_input_state()
332
  image_dir = get_conv_image_dir()
333
  output_state['text'] = results['text']
 
334
 
335
  for image_base64 in results['images']:
336
  if image_base64 == '':
337
  image_path = ''
338
  else:
339
- image = decode_image(image_base64)
340
- image = image.convert('RGB')
 
 
 
 
 
341
  image_path = get_image_name(image=image, image_dir=image_dir)
342
  if not os.path.exists(image_path):
343
  image.save(image_path)
@@ -354,8 +362,8 @@ def http_bot(dialog_state, input_state, max_new_tokens, max_turns,
354
  IMG_FLAG = '<image>'
355
  LOGDIR = 'log'
356
 
357
- logger = build_logger("gradio_seed_x", LOGDIR)
358
- headers = {"User-Agent": "SEED-X Client"}
359
 
360
  no_change_btn = gr.Button()
361
  enable_btn = gr.Button(interactive=True)
@@ -436,10 +444,16 @@ def center_crop_image(image, max_aspect_ratio=1.5):
436
 
437
  def vote_last_response(state, vote_type, request: gr.Request):
438
  with open(get_conv_log_filename(), "a") as fout:
 
 
 
 
 
 
439
  data = {
440
  "tstamp": round(time.time(), 4),
441
  "type": vote_type,
442
- "state": state.dict(),
443
  "ip": request.client.host,
444
  }
445
  fout.write(json.dumps(data) + "\n")
@@ -475,7 +489,7 @@ def clear_history(request: gr.Request):
475
 
476
 
477
  def init_input_state():
478
- return {'images': [], 'text': ''}
479
 
480
 
481
  def add_text(dialog_state, input_state, text, request: gr.Request):
@@ -509,13 +523,17 @@ def add_image(dialog_state, input_state, image, request: gr.Request):
509
 
510
  print('image size:', image.size)
511
 
512
- image = center_crop_image(image, max_aspect_ratio=10)
513
 
514
  image_dir = get_conv_image_dir()
515
  image_path = get_image_name(image=image, image_dir=image_dir)
516
  if not os.path.exists(image_path):
517
  image.save(image_path)
518
  input_state['images'].append(image_path)
 
 
 
 
519
  input_state['text'] += IMG_FLAG
520
 
521
  if len(dialog_state.messages) > 0 and dialog_state.messages[-1]['role'] == dialog_state.roles[0]:
@@ -548,14 +566,13 @@ title = ("""
548
  # SEED-Story
549
  [[Paper]](https://arxiv.org/abs/2407.08683) [[Code]](https://github.com/TencentARC/SEED-Story)
550
 
551
- Demo of a multimodal story generation model SEED-Story-George. It is trained on StoryStream-Curious George subset.
552
  SEED-Story is a MLLM capable of generating multimodal long stories consisting of rich and coherent narrative texts, along with images that are consistent in characters and style.
553
 
554
  ## Tips:
555
  * Check out the conversation examples (at the bottom) for inspiration.
556
- * You can adjust "Max History Rounds" to try a conversation with up to **three rounds due to insufficient GPU memory**. For more turns, you can download our checkpoints from GitHub and deploy them locally for inference.
557
- * Our demo supports a mix of images and texts as input. You can freely upload an image or enter text, and then click on "Add Image/Text". You can repeat the former step multiple times, and click on "Submit" for model inference at last.
558
-
559
  * SEED-Story was trained with English-only data. It may process with other languages due to the inherent capabilities from LLaMA, but might not stable.
560
  """)
561
 
@@ -577,7 +594,7 @@ img:before {
577
  position: absolute;
578
  top: -10px;
579
  left: 0;
580
- height: calc(100% + 10px);
581
  width: 100%;
582
  background-color: rgb(230, 230, 230);
583
  border: 2px dotted rgb(200, 200, 200);
@@ -601,29 +618,10 @@ img:after {
601
 
602
  if __name__ == '__main__':
603
  examples_mix = [
604
- ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/bank.png?raw=true',
605
- 'Can I conntect with an advisor on Sunday?'],
606
- ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/ground.png?raw=true',
607
- 'Is there anything in the image that can protect me from catching the flu virus when I go out? Show me the location.'],
608
- ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/arrow.jpg?raw=true',
609
- 'What is the object pointed by the red arrow?'],
610
- ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/shanghai.png?raw=true',
611
- 'Where was this image taken? Explain your answer.'],
612
- ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/GPT4.png?raw=true',
613
- 'How long does it take to make GPT-4 safer?'],
614
- ['https://github.com/AILab-CVC/SEED-X/blob/main/demos/twitter.png?raw=true',
615
- 'Please provide a comprehensive description of this image.'],
616
- ]
617
- examples_text = [
618
- ['I want to build a two story cabin in the woods, with many commanding windows. Can you show me a picture?'],
619
- ['Use your imagination to design a concept image for Artificial General Intelligence (AGI). Show me an image.'],
620
- [
621
- 'Can you design an illustration for β€œThe Three-Body Problem” to depict a scene from the novel? Show me a picture.'],
622
- [
623
- 'My four year old son loves toy trains. Can you design a fancy birthday cake for him? Please generate a picture.'],
624
- [
625
- 'Generate an image of a portrait of young nordic girl, age 25, freckled skin, neck tatoo, blue eyes 35mm lens, photography, ultra details.'],
626
- ['Generate an impressionist painting of an astronaut in a jungle.']
627
  ]
628
  with gr.Blocks(css=css) as demo:
629
  gr.Markdown(title)
@@ -640,10 +638,10 @@ if __name__ == '__main__':
640
  elem_id='textbox',
641
  placeholder="Enter text and image, and press submit,", container=False)
642
  with gr.Row():
643
- add_image_btn = gr.Button("Add Image")
644
- add_text_btn = gr.Button("Add Text")
645
-
646
  submit_btn = gr.Button("Submit")
 
647
 
648
  with gr.Row():
649
  max_new_tokens = gr.Slider(minimum=64,
@@ -652,14 +650,11 @@ if __name__ == '__main__':
652
  step=64,
653
  interactive=True,
654
  label="Max Output Tokens")
655
- max_turns = gr.Slider(minimum=1, maximum=3, value=3, step=1, interactive=True,
656
- label="Max History Rounds")
657
- force_img_gen = gr.Radio(choices=[True, False], value=False, label='Force Image Generation')
658
- force_bbox = gr.Radio(choices=[True, False], value=False, label='Force Bounding Box')
659
- force_polish = gr.Radio(choices=[True, False], value=True, label='Force Polishing Generated Image')
660
 
661
  with gr.Column(scale=7):
662
- chatbot = gr.Chatbot(elem_id='chatbot', label="SEED-X-I", height=700)
663
  with gr.Row():
664
  upvote_btn = gr.Button(value="πŸ‘ Upvote", interactive=False)
665
  downvote_btn = gr.Button(value="πŸ‘Ž Downvote", interactive=False)
@@ -667,10 +662,8 @@ if __name__ == '__main__':
667
  clear_btn = gr.Button(value="πŸ—‘οΈ Clear history", interactive=False)
668
 
669
  with gr.Row():
670
- with gr.Column(scale=0.7):
671
  gr.Examples(examples=examples_mix, label='Input examples', inputs=[image, text], cache_examples=False)
672
- with gr.Column(scale=0.3):
673
- gr.Examples(examples=examples_text, label='Input examples', inputs=[text], cache_examples=False)
674
 
675
  # Register listeners
676
  btn_list = [upvote_btn, downvote_btn, regenerate_btn, clear_btn]
@@ -678,20 +671,25 @@ if __name__ == '__main__':
678
  downvote_btn.click(downvote_last_response, [dialog_state], [upvote_btn, downvote_btn])
679
 
680
  regenerate_btn.click(regenerate, [dialog_state], [dialog_state, chatbot] + btn_list).then(
681
- http_bot, [dialog_state, input_state, max_new_tokens, max_turns, force_img_gen, force_bbox, force_polish],
682
  [dialog_state, input_state, chatbot] + btn_list)
683
- add_image_btn.click(add_image, [dialog_state, input_state, image],
684
- [dialog_state, input_state, image, chatbot] + btn_list)
685
-
686
- add_text_btn.click(add_text, [dialog_state, input_state, text],
687
- [dialog_state, input_state, text, chatbot] + btn_list)
688
 
689
  submit_btn.click(
690
- add_image, [dialog_state, input_state, image], [dialog_state, input_state, image, chatbot] + btn_list).then(
691
  add_text, [dialog_state, input_state, text],
692
  [dialog_state, input_state, text, chatbot, upvote_btn, downvote_btn, regenerate_btn, clear_btn]).then(
 
 
 
 
 
 
693
  http_bot,
694
- [dialog_state, input_state, max_new_tokens, max_turns, force_img_gen, force_bbox, force_polish],
695
  [dialog_state, input_state, chatbot] + btn_list)
696
  clear_btn.click(clear_history, None, [dialog_state, input_state, chatbot] + btn_list)
697
 
 
37
  IMG_FLAG = '<image>'
38
  num_img_in_tokens = 64
39
  num_img_out_tokens = 64
40
+ instruction_prompt = '{instruction}'
41
 
42
  resolution_grids = ['1x1', '1x2', '1x3', '1x4', '1x5', '1x6', '1x10', '2x1', '3x1', '4x1', '5x1', '6x1', '10x1', '2x2',
43
  '2x3', '3x2', '2x4', '4x2']
 
120
  self.agent = hydra.utils.instantiate(agent_cfg, llm=llm)
121
 
122
  self.agent.eval().to(self.llm_device, dtype=self.dtype)
123
+ self.agent.llm.base_model.model.use_kv_cache_head = False
124
  print('Init agent mdoel Done')
125
 
126
  noise_scheduler = EulerDiscreteScheduler.from_pretrained(args.diffusion_path, subfolder="scheduler")
 
168
 
169
 
170
  @spaces.GPU
171
+ def generate(text_list, image_list, image_embed_list, max_new_tokens):
172
  with torch.no_grad():
173
+ print('text_list: {}'.format(text_list))
174
  text_list = text_list.split(IMG_FLAG)
175
+ text_list = [text_list[0]] + ["[INST]"+item for item in text_list[1:-1]] + [text_list[-1]]
176
  top_p = 0.5
177
+ window_size = 8
178
  assert len(text_list) == len(image_list) + 1
179
 
180
  image_tokens = BOI_TOKEN + ''.join(
 
186
  embeds_cmp_mask = []
187
  embeds_gen_mask = []
188
 
 
 
 
 
 
189
  for idx, image_item in enumerate(image_list):
190
  if isinstance(image_item, str):
191
  image = decode_image(image_item)
192
  print('after decode image size:', image.size)
193
  input_images.append(image)
194
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
195
  image_tensor = service.image_transform(image)
196
  image_tensor_list.append(image_tensor)
197
  embeds_cmp_mask.append(True)
 
199
  else:
200
  raise ValueError
201
 
202
+ # pixel_values = torch.stack(image_tensor_list).to(service.vit_sd_device, dtype=service.dtype)
203
+ #
204
+ # image_embeds = service.visual_encoder(pixel_values)
205
+ # image_embeds = image_embeds.to(service.llm_device)
206
+ print(image_embed_list)
207
+ image_embed_list = [t.squeeze(0) for t in image_embed_list]
208
+ image_embeds = torch.stack(image_embed_list, dim=0)
 
 
 
 
 
 
 
 
 
 
209
  image_embeds = image_embeds.to(service.llm_device)
210
 
211
  embeds_cmp_mask = torch.tensor(embeds_cmp_mask, dtype=torch.bool).to(service.llm_device)
 
217
  embeds_cmp_mask = None
218
  embeds_gen_mask = None
219
 
220
+
221
  input_text = image_tokens.join(text_list)
222
 
223
+ print('input_text fed to LLM:', input_text)
224
  input_ids = service.tokenizer.encode(input_text, add_special_tokens=False)
225
+
226
+ while image_embeds.shape[0] > window_size:
227
+ eoi_prompt_idx = input_text.index(EOI_TOKEN)
228
+ input_text = input_text[eoi_prompt_idx + len(EOI_TOKEN) + len('[INST]'):]
229
+ image_embeds = image_embeds[1:]
230
+ input_ids = service.tokenizer.encode(input_text, add_special_tokens=False)
231
+
232
+ if image_embeds is not None:
233
+ embeds_cmp_mask = torch.tensor([True] * image_embeds.shape[0]).to(service.llm_device, dtype=torch.bool)
234
+
235
  input_ids = [service.tokenizer.bos_token_id] + input_ids
236
 
237
  input_ids = torch.tensor(input_ids).to(service.llm_device, dtype=torch.long)
 
249
  ids_gen_mask = ids_gen_mask.unsqueeze(0)
250
 
251
  error_msg = []
252
+ print('image_embeds_shape: ' + str(image_embeds.shape))
253
+ print('image_embeds: {}'.format(image_embeds))
254
+ print('input_ids: ' + str(input_ids))
255
+ print('ids_cmp_mask: ' + str(ids_cmp_mask))
256
  output = service.agent.generate(
257
  tokenizer=service.tokenizer,
258
  input_ids=input_ids,
 
268
 
269
  gen_imgs_base64_list = []
270
  generated_text = output['text']
 
271
 
272
  torch.cuda.empty_cache()
273
 
 
283
  for img_idx in range(output['num_gen_imgs']):
284
  img_feat = img_gen_feat[img_idx:img_idx + 1]
285
  generated_image = service.sd_adapter.generate(image_embeds=img_feat, num_inference_steps=50)[0]
286
+ gen_imgs_base64_list.append(generated_image)
287
 
288
  # a = time.time()
289
  # service.sd_adapter = service.sd_adapter.cpu()
 
291
  # service.agent = service.agent.to(service.vit_sd_device, dtype=service.dtype)
292
  # print("Loading finished: ", time.time() - a)
293
 
294
+ print('[func generate inout+output]: {}'.format(input_text + generated_text))
295
+ return {'text': generated_text, 'images': gen_imgs_base64_list, 'image_embeds': img_feat.detach().clone(), 'error_msg': error_msg}
296
 
297
 
298
+ def http_bot(dialog_state, input_state, max_new_tokens, max_length,
299
  request: gr.Request):
300
  print('input_state:', input_state)
301
+ print(dialog_state.messages)
302
+ if len(dialog_state.messages) == 0 or len(
303
  dialog_state.messages[-1]['message']['text'].strip(' ?.;!/')) == 0:
304
  return (dialog_state, input_state, dialog_state.to_gradio_chatbot()) + (no_change_btn,) * 4
305
 
306
+ if len(dialog_state.messages) >= max_length:
307
  output_state = init_input_state()
308
  output_state['text'] = 'Error: History exceeds maximum rounds, please clear history and restart.'
309
  dialog_state.messages.append({'role': dialog_state.roles[1], 'message': output_state})
 
312
 
313
  prompt = dialog_state.get_prompt()
314
  text = prompt['text']
315
+ print('text from http_bot: {}'.format(text))
316
  max_new_tokens = int(max_new_tokens)
317
  images = prompt['images']
318
+ image_embeds = prompt['image_embeds']
319
+
320
+ results = generate(text, images, image_embeds, max_new_tokens)
321
+ generated_text = results['text']
322
+ pattern = r' <img_000\d{2}>'
323
+ # Replace all occurrences of the pattern with the replacement text
324
+ generated_text = re.sub(pattern, '', generated_text)
325
+
326
+ generated_text = generated_text.replace(' '+service.tokenizer.eos_token, '')\
327
+ .replace('[INST]', '').replace(' '+BOI_TOKEN, '').replace(' '+EOI_TOKEN, IMG_FLAG)
328
+
329
+ results['text'] = generated_text
330
 
 
331
  print('response: ', {'text': results['text'], 'error_msg': results['error_msg']})
332
 
333
  output_state = init_input_state()
334
  image_dir = get_conv_image_dir()
335
  output_state['text'] = results['text']
336
+ output_state['image_embeds'].append(results['image_embeds'])
337
 
338
  for image_base64 in results['images']:
339
  if image_base64 == '':
340
  image_path = ''
341
  else:
342
+ if isinstance(image_base64, Image.Image):
343
+ print('generated image is in Image.Image')
344
+ image = image_base64
345
+ else:
346
+ print('generated image is in Image_base64')
347
+ image = decode_image(image_base64)
348
+ image = image.convert('RGB')
349
  image_path = get_image_name(image=image, image_dir=image_dir)
350
  if not os.path.exists(image_path):
351
  image.save(image_path)
 
362
  IMG_FLAG = '<image>'
363
  LOGDIR = 'log'
364
 
365
+ logger = build_logger("gradio_seed_story", LOGDIR)
366
+ headers = {"User-Agent": "SEED-Story Client"}
367
 
368
  no_change_btn = gr.Button()
369
  enable_btn = gr.Button(interactive=True)
 
444
 
445
  def vote_last_response(state, vote_type, request: gr.Request):
446
  with open(get_conv_log_filename(), "a") as fout:
447
+ print(state)
448
+ print(state.dict())
449
+ dic = state.dict()
450
+ for i in range(len(dic['messages'])):
451
+ dic['messages'][i]['message'].pop('image_embeds')
452
+ print(dic)
453
  data = {
454
  "tstamp": round(time.time(), 4),
455
  "type": vote_type,
456
+ "state": dic,
457
  "ip": request.client.host,
458
  }
459
  fout.write(json.dumps(data) + "\n")
 
489
 
490
 
491
  def init_input_state():
492
+ return {'images': [], 'text': '', 'image_embeds': []}
493
 
494
 
495
  def add_text(dialog_state, input_state, text, request: gr.Request):
 
523
 
524
  print('image size:', image.size)
525
 
526
+ # image = center_crop_image(image, max_aspect_ratio=10)
527
 
528
  image_dir = get_conv_image_dir()
529
  image_path = get_image_name(image=image, image_dir=image_dir)
530
  if not os.path.exists(image_path):
531
  image.save(image_path)
532
  input_state['images'].append(image_path)
533
+ image_tensor = service.image_transform(image).unsqueeze(0).to(service.llm_device, dtype=service.dtype)
534
+ image_embeds = service.visual_encoder(image_tensor).detach().clone()
535
+ image_embeds = image_embeds.to(service.llm_device)
536
+ input_state['image_embeds'].append(image_embeds)
537
  input_state['text'] += IMG_FLAG
538
 
539
  if len(dialog_state.messages) > 0 and dialog_state.messages[-1]['role'] == dialog_state.roles[0]:
 
566
  # SEED-Story
567
  [[Paper]](https://arxiv.org/abs/2407.08683) [[Code]](https://github.com/TencentARC/SEED-Story)
568
 
569
+ Demo of the multimodal story generation model SEED-Story-George. It is trained on StoryStream-Curious George subset.
570
  SEED-Story is a MLLM capable of generating multimodal long stories consisting of rich and coherent narrative texts, along with images that are consistent in characters and style.
571
 
572
  ## Tips:
573
  * Check out the conversation examples (at the bottom) for inspiration.
574
+ * Our demo requires a mix of an image and a starting sentence as input. You can freely upload an image or enter text, and then click on "Submit". Then, The model generates the next story image and text.
575
+ * You can click on "Continue Generation" to make the model generate a next story image and text based on all previous story boards.
 
576
  * SEED-Story was trained with English-only data. It may process with other languages due to the inherent capabilities from LLaMA, but might not stable.
577
  """)
578
 
 
594
  position: absolute;
595
  top: -10px;
596
  left: 0;
597
+ height: auto;
598
  width: 100%;
599
  background-color: rgb(230, 230, 230);
600
  border: 2px dotted rgb(200, 200, 200);
 
618
 
619
  if __name__ == '__main__':
620
  examples_mix = [
621
+ ['https://github.com/TencentARC/SEED-Story/blob/master/assets/demo_examples/2.jpg?raw=true',
622
+ 'One day, George, the curious brown monkey, decided to explore a new room. He peeked out from behind a dresser, looking both curious and cautious. The dresser had three drawers, each with a round handle. An electrical outlet was visible on the wall.'],
623
+ ['https://github.com/TencentARC/SEED-Story/blob/master/assets/demo_examples/4.jpg?raw=true',
624
+ 'In the bustling city, a beautiful blue and yellow bird took flight, soaring high above the buildings. Among the clouds, a heart-shaped formation appeared, as if nature was sending a love note to the world below. Other birds joined, their silhouettes dancing in the distance.'],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
625
  ]
626
  with gr.Blocks(css=css) as demo:
627
  gr.Markdown(title)
 
638
  elem_id='textbox',
639
  placeholder="Enter text and image, and press submit,", container=False)
640
  with gr.Row():
641
+ # add_image_btn = gr.Button("Add Image")
642
+ # add_text_btn = gr.Button("Add Text")
 
643
  submit_btn = gr.Button("Submit")
644
+ continue_btn = gr.Button("Continue Generation")
645
 
646
  with gr.Row():
647
  max_new_tokens = gr.Slider(minimum=64,
 
650
  step=64,
651
  interactive=True,
652
  label="Max Output Tokens")
653
+ max_length = gr.Slider(minimum=1, maximum=30, value=10, step=1, interactive=True,
654
+ label="Max Story Length")
 
 
 
655
 
656
  with gr.Column(scale=7):
657
+ chatbot = gr.Chatbot(elem_id='chatbot', label="SEED-Story", height=700)
658
  with gr.Row():
659
  upvote_btn = gr.Button(value="πŸ‘ Upvote", interactive=False)
660
  downvote_btn = gr.Button(value="πŸ‘Ž Downvote", interactive=False)
 
662
  clear_btn = gr.Button(value="πŸ—‘οΈ Clear history", interactive=False)
663
 
664
  with gr.Row():
665
+ with gr.Column(scale=1.0):
666
  gr.Examples(examples=examples_mix, label='Input examples', inputs=[image, text], cache_examples=False)
 
 
667
 
668
  # Register listeners
669
  btn_list = [upvote_btn, downvote_btn, regenerate_btn, clear_btn]
 
671
  downvote_btn.click(downvote_last_response, [dialog_state], [upvote_btn, downvote_btn])
672
 
673
  regenerate_btn.click(regenerate, [dialog_state], [dialog_state, chatbot] + btn_list).then(
674
+ http_bot, [dialog_state, input_state, max_new_tokens, max_length],
675
  [dialog_state, input_state, chatbot] + btn_list)
676
+ # add_image_btn.click(add_image, [dialog_state, input_state, image],
677
+ # [dialog_state, input_state, image, chatbot] + btn_list)
678
+ #
679
+ # add_text_btn.click(add_text, [dialog_state, input_state, text],
680
+ # [dialog_state, input_state, text, chatbot] + btn_list)
681
 
682
  submit_btn.click(
 
683
  add_text, [dialog_state, input_state, text],
684
  [dialog_state, input_state, text, chatbot, upvote_btn, downvote_btn, regenerate_btn, clear_btn]).then(
685
+ add_image, [dialog_state, input_state, image],
686
+ [dialog_state, input_state, image, chatbot] + btn_list).then(
687
+ http_bot,
688
+ [dialog_state, input_state, max_new_tokens, max_length],
689
+ [dialog_state, input_state, chatbot] + btn_list)
690
+ continue_btn.click(
691
  http_bot,
692
+ [dialog_state, input_state, max_new_tokens, max_length],
693
  [dialog_state, input_state, chatbot] + btn_list)
694
  clear_btn.click(clear_history, None, [dialog_state, input_state, chatbot] + btn_list)
695
 
configs/visual_tokenizer/qwen_vitg_448.yaml CHANGED
@@ -7,4 +7,4 @@ mlp_ratio: 4.9231
7
  output_dim: 4096
8
  patch_size: 14
9
  width: 1664
10
- pretrained_model_path: /dataset/syang/pretrained/qwen_vit_G.pt
 
7
  output_dim: 4096
8
  patch_size: 14
9
  width: 1664
10
+ pretrained_model_path: pretrained/qwen_vit_G.pt
conversation.py CHANGED
@@ -49,7 +49,8 @@ class Conversation:
49
  skip_next: bool = False
50
 
51
  def get_prompt(self):
52
- messages = copy.deepcopy(self.messages)
 
53
  if self.sep_style == SeparatorStyle.SINGLE:
54
  if self.system is None or self.system == '':
55
  text = ''
@@ -65,28 +66,28 @@ class Conversation:
65
 
66
  text += self.roles[1] + ":"
67
  elif self.sep_style == SeparatorStyle.LLAMA_2:
68
- b_token = "[INST] "
69
- e_token = " [/INST]"
70
  if self.system is None or self.system == '':
71
  text = ''
72
  else:
73
  text = f"<<SYS>>\n{self.system}\n<</SYS>>\n\n"
74
  images = []
 
75
  for idx, message in enumerate(messages):
76
- # text += message['role'] + ": " + message['message']['text'] + self.sep
77
- if idx % 2 == 0:
78
- text += b_token + message['message']['text'] + e_token + self.sep
79
- else:
80
- text += message['message']['text'] + self.sep
81
 
82
  for image_path in message['message']['images']:
83
- image = Image.open(image_path)
84
  image_base64 = encode_image(image)
85
  images.append(image_base64)
 
 
 
86
  else:
87
  raise NotImplementedError
88
 
89
- return {'text': text, 'images': images}
90
 
91
  # def update_image_ids(self, images_ids):
92
  # image_count = 0
@@ -106,6 +107,7 @@ class Conversation:
106
  for i, single_turn in enumerate(self.messages[self.offset:]):
107
  single_turn = single_turn['message']
108
  text_list = single_turn['text'].split(IMG_FLAG)
 
109
  assert len(text_list) == len(single_turn['images']) + 1, print(text_list, len(single_turn['images']))
110
  message = ''
111
  for image_idx in range(len(single_turn['images'])):
 
49
  skip_next: bool = False
50
 
51
  def get_prompt(self):
52
+ messages = self.messages
53
+ # messages = copy.deepcopy(self.messages)
54
  if self.sep_style == SeparatorStyle.SINGLE:
55
  if self.system is None or self.system == '':
56
  text = ''
 
66
 
67
  text += self.roles[1] + ":"
68
  elif self.sep_style == SeparatorStyle.LLAMA_2:
69
+ # b_token = "[INST] "
70
+ # e_token = " [/INST]"
71
  if self.system is None or self.system == '':
72
  text = ''
73
  else:
74
  text = f"<<SYS>>\n{self.system}\n<</SYS>>\n\n"
75
  images = []
76
+ image_embeds = []
77
  for idx, message in enumerate(messages):
78
+ text += message['message']['text']
 
 
 
 
79
 
80
  for image_path in message['message']['images']:
81
+ image = Image.open(image_path).convert('RGB')
82
  image_base64 = encode_image(image)
83
  images.append(image_base64)
84
+ image_embeds.extend(message['message']['image_embeds'])
85
+
86
+
87
  else:
88
  raise NotImplementedError
89
 
90
+ return {'text': text, 'images': images, 'image_embeds': image_embeds}
91
 
92
  # def update_image_ids(self, images_ids):
93
  # image_count = 0
 
107
  for i, single_turn in enumerate(self.messages[self.offset:]):
108
  single_turn = single_turn['message']
109
  text_list = single_turn['text'].split(IMG_FLAG)
110
+ print(text_list, len(single_turn['images']))
111
  assert len(text_list) == len(single_turn['images']) + 1, print(text_list, len(single_turn['images']))
112
  message = ''
113
  for image_idx in range(len(single_turn['images'])):
pretrained/seed_story/george_sft/pytorch_model.bin CHANGED
@@ -1,3 +1,3 @@
1
  version https://git-lfs.github.com/spec/v1
2
- oid sha256:46db6f1beb672085204ca9f7d542f6b62063cbe9970933ca702bccc72f00a4f6
3
  size 14709979626
 
1
  version https://git-lfs.github.com/spec/v1
2
+ oid sha256:c7e46794a2aab38f3f59484a4f4bb4c839217ef17c4329977b0a11839f462b94
3
  size 14709979626