vqa_dataset.py 3.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. batch["labels"] = copy.copy(batch["input_ids"])
  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. # Lastly 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. batch["labels"][i] = torch.tensor(labels)
  43. return batch
  44. def get_custom_dataset(dataset_config, processor, split, split_ratio=0.9):
  45. # load_dataset will return DatasetDict that contains all the data in the train set
  46. dataset_dict = load_dataset("remyxai/vqasynth_spacellava")
  47. dataset = dataset_dict[split]
  48. dataset = dataset.select(range(100))
  49. return dataset
  50. class VQADataCollator:
  51. def __init__(self, processor):
  52. self.processor = processor
  53. self.processor.tokenizer.padding_side = "right" # during training, one always uses padding on the right
  54. def __call__(self, samples):
  55. dialogs,images = [],[]
  56. for sample in samples:
  57. image,sample_text = sample["images"],sample["messages"]
  58. dialog = []
  59. for line in sample_text:
  60. content = []
  61. messages = line["content"]
  62. role = line["role"]
  63. for message in messages:
  64. if message["type"] == "image":
  65. content.append({"type": "image"})
  66. elif message["type"] == "text":
  67. content.append({"type": "text", "text": message["text"].strip()})
  68. dialog.append({"role": role,"content":content})
  69. dialogs.append(dialog)
  70. images.append(image)
  71. return tokenize_dialogs(dialogs,images, self.processor)
  72. def get_data_collator(processor):
  73. return VQADataCollator(processor)