vqa_dataset.py 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 3 Community License Agreement.
  3. import copy
  4. from datasets import load_dataset
  5. import itertools
  6. import torch
  7. # check system prompt token seq or user prompt token seq is in the current token list
  8. def check_header(targets,seq):
  9. for i in range(len(seq)-3):
  10. if seq[i:i+3] in targets:
  11. return True
  12. return False
  13. def replace_target(target,seq):
  14. for i in range(len(seq)-3):
  15. if seq[i:i+3] == target:
  16. seq[i],seq[i+1],seq[i+2] = -100,-100,-100
  17. return seq
  18. def tokenize_dialogs(dialogs, images, processor):
  19. # If vocab size is above 128000, use the chat template to generate the tokens as it is from Llama 3 family models
  20. text_prompt = processor.apply_chat_template(dialogs)
  21. #print("text_prompt",text_prompt)
  22. batch = processor(images=images, text=text_prompt,padding = True, return_tensors="pt")
  23. label_list = []
  24. for i in range(len(batch["input_ids"])):
  25. dialog_tokens = batch["input_ids"][i].tolist()
  26. labels = copy.copy(dialog_tokens)
  27. eot_indices = [i for i,n in enumerate(labels) if n == 128009]
  28. last_idx = 0
  29. # system prompt header "<|start_header_id|>system<|end_header_id|>" has been tokenized to [128006, 9125, 128007]
  30. # user prompt header "<|start_header_id|>user<|end_header_id|>" has been tokenized to [128006, 882, 128007]
  31. prompt_header_seqs = [[128006, 9125, 128007],[128006, 882, 128007]]
  32. for n, idx in enumerate(eot_indices):
  33. current_seq = labels[last_idx:idx+1]
  34. if check_header(prompt_header_seqs,current_seq):
  35. # found prompt header, indicating that this seq should be masked
  36. labels[last_idx:idx+1] = [-100] * (idx-last_idx+1)
  37. else:
  38. last_idx = idx+1
  39. # Mask all the assistant header prompt <|start_header_id|>assistant<|end_header_id|>, which has been tokenized to [128006, 78191, 128007]
  40. assistant_header_seq = [128006, 78191, 128007]
  41. labels = replace_target(assistant_header_seq,labels)
  42. # Mask the padding token and image token 128256
  43. for i in range(len(labels)):
  44. if labels[i] == processor.tokenizer.pad_token_id or labels[i] == 128256: # 128256 is image token index
  45. labels[i] = -100
  46. label_list.append(labels)
  47. batch["labels"] = torch.tensor(label_list)
  48. tokenizer_length = len(processor.tokenizer)
  49. return batch
  50. def tokenize_dialog(dialog, images, processor):
  51. # If vocab size is above 128000, use the chat template to generate the tokens as it is from Llama 3 family models
  52. text_prompt = processor.apply_chat_template(dialog)
  53. #print("text_prompt",text_prompt)
  54. batch = processor(images=images, text=text_prompt,padding = True, return_tensors="pt")
  55. labels = copy.copy(batch["input_ids"].tolist()[0])
  56. eot_indices = [i for i,n in enumerate(labels) if n == 128009]
  57. last_idx = 0
  58. # system prompt header "<|start_header_id|>system<|end_header_id|>" has been tokenized to [128006, 9125, 128007]
  59. # user prompt header "<|start_header_id|>user<|end_header_id|>" has been tokenized to [128006, 882, 128007]
  60. prompt_header_seqs = [[128006, 9125, 128007],[128006, 882, 128007]]
  61. for n, idx in enumerate(eot_indices):
  62. current_seq = labels[last_idx:idx+1]
  63. if check_header(prompt_header_seqs,current_seq):
  64. # found prompt header, indicating that this seq should be masked
  65. labels[last_idx:idx+1] = [-100] * (idx-last_idx+1)
  66. else:
  67. last_idx = idx+1
  68. # Lastly mask all the assistant header prompt <|start_header_id|>assistant<|end_header_id|>, which has been tokenized to [128006, 78191, 128007]
  69. assistant_header_seq = [128006, 78191, 128007]
  70. labels = replace_target(assistant_header_seq,labels)
  71. #print("labels",labels)
  72. # print("pixel_values .shape",batch["pixel_values"].shape)
  73. # print("batch_size, num_concurrent_media, num_tiles, num_channels, height, width = pixel_values.shape")
  74. batch["labels"] = torch.tensor(labels)
  75. # exit()
  76. # combined_tokens = {
  77. # # "input_ids": list(itertools.chain(*(t for t in dialog_tokens))),
  78. # # "labels": list(itertools.chain(*(t for t in labels_tokens))),
  79. # "input_ids": dialog_tokens,
  80. # "labels": labels,
  81. # "attention_mask": [1]*len(dialog_tokens),
  82. # "pixel_values": batch["pixel_values"],
  83. # "aspect_ratio_ids": batch["aspect_ratio_ids"],
  84. # "aspect_ratio_mask": batch["aspect_ratio_mask"],
  85. # "cross_attention_mask": batch["cross_attention_mask"]
  86. # }
  87. # input_ids = list(itertools.chain(*(t for t in dialog_tokens))),
  88. # labels = list(itertools.chain(*(t for t in labels_tokens))),
  89. # attention_mask = [1]*len(list(itertools.chain(*(t for t in dialog_tokens)))),
  90. # pixel_values = batch["pixel_values"],
  91. # image_sizes = batch["image_sizes"]
  92. # print("combined_tokens",combined_tokens[image_sizes])
  93. return batch
  94. def get_custom_dataset(dataset_config, processor, split, split_ratio=0.9):
  95. # load_dataset will return DatasetDict that contains all the data in the train set
  96. dataset_dict = load_dataset("remyxai/vqasynth_spacellava")
  97. dataset = dataset_dict[split]
  98. dataset = dataset.select(range(500))
  99. return dataset
  100. class VQADataCollator:
  101. def __init__(self, processor):
  102. self.processor = processor
  103. self.processor.tokenizer.padding_side = "right" # during training, one always uses padding on the right
  104. def __call__(self, samples):
  105. dialogs,images = [],[]
  106. for sample in samples:
  107. image,sample_text = sample["images"],sample["messages"]
  108. dialog = []
  109. for line in sample_text:
  110. content = []
  111. messages = line["content"]
  112. role = line["role"]
  113. for message in messages:
  114. if message["type"] == "image":
  115. content.append({"type": "image"})
  116. elif message["type"] == "text":
  117. content.append({"type": "text", "text": message["text"].strip()})
  118. dialog.append({"role": role,"content":content})
  119. dialogs.append(dialog)
  120. images.append(image)
  121. return tokenize_dialogs(dialogs,images, self.processor)
  122. def __callworking__(self, samples):
  123. for sample in samples:
  124. image,sample_text = sample["images"],sample["messages"]
  125. dialog = []
  126. for line in sample_text:
  127. content = []
  128. messages = line["content"]
  129. role = line["role"]
  130. for message in messages:
  131. if message["type"] == "image":
  132. content.append({"type": "image"})
  133. elif message["type"] == "text":
  134. content.append({"type": "text", "text": message["text"].strip()})
  135. dialog.append({"role": role,"content":content})
  136. return tokenize_dialog(dialog,image, self.processor)
  137. def get_data_collator(processor):
  138. return VQADataCollator(processor)