vqa_dataset_old.py 4.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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_dialog(dialog, 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(dialog)
  21. #print("text_prompt",text_prompt)
  22. batch = processor(images=images, text=text_prompt,padding = True, return_tensors="pt")
  23. labels = copy.copy(batch["input_ids"].tolist()[0])
  24. eot_indices = [i for i,n in enumerate(labels) if n == 128009]
  25. last_idx = 0
  26. # system prompt header "<|start_header_id|>system<|end_header_id|>" has been tokenized to [128006, 9125, 128007]
  27. # user prompt header "<|start_header_id|>user<|end_header_id|>" has been tokenized to [128006, 882, 128007]
  28. prompt_header_seqs = [[128006, 9125, 128007],[128006, 882, 128007]]
  29. for n, idx in enumerate(eot_indices):
  30. current_seq = labels[last_idx:idx+1]
  31. if check_header(prompt_header_seqs,current_seq):
  32. # found prompt header, indicating that this seq should be masked
  33. labels[last_idx:idx+1] = [-100] * (idx-last_idx+1)
  34. else:
  35. last_idx = idx+1
  36. # Lastly mask all the assistant header prompt <|start_header_id|>assistant<|end_header_id|>, which has been tokenized to [128006, 78191, 128007]
  37. assistant_header_seq = [128006, 78191, 128007]
  38. labels = replace_target(assistant_header_seq,labels)
  39. #print("labels",labels)
  40. # print("pixel_values .shape",batch["pixel_values"].shape)
  41. # print("batch_size, num_concurrent_media, num_tiles, num_channels, height, width = pixel_values.shape")
  42. batch["labels"] = torch.tensor(labels)
  43. #pixel_values .shape torch.Size([1, 1, 4, 3, 560, 560])
  44. batch["pixel_values"] = torch.squeeze(batch["pixel_values"], 1)
  45. # pixel_values .shape torch.Size([1, 4, 3, 560, 560])
  46. print("pixel_values .shape",batch["pixel_values"].shape)
  47. # exit()
  48. # combined_tokens = {
  49. # # "input_ids": list(itertools.chain(*(t for t in dialog_tokens))),
  50. # # "labels": list(itertools.chain(*(t for t in labels_tokens))),
  51. # "input_ids": dialog_tokens,
  52. # "labels": labels,
  53. # "attention_mask": [1]*len(dialog_tokens),
  54. # "pixel_values": batch["pixel_values"],
  55. # "aspect_ratio_ids": batch["aspect_ratio_ids"],
  56. # "aspect_ratio_mask": batch["aspect_ratio_mask"],
  57. # "cross_attention_mask": batch["cross_attention_mask"]
  58. # }
  59. # input_ids = list(itertools.chain(*(t for t in dialog_tokens))),
  60. # labels = list(itertools.chain(*(t for t in labels_tokens))),
  61. # attention_mask = [1]*len(list(itertools.chain(*(t for t in dialog_tokens)))),
  62. # pixel_values = batch["pixel_values"],
  63. # image_sizes = batch["image_sizes"]
  64. # print("combined_tokens",combined_tokens[image_sizes])
  65. return batch
  66. def image_tokenize(sample, processor):
  67. processor.tokenizer.padding_side = "right" # during training, one always uses padding on the right
  68. images,sample_text = sample["images"],sample["messages"]
  69. dialog = []
  70. for line in sample_text:
  71. content = []
  72. messages = line["content"]
  73. role = line["role"]
  74. for message in messages:
  75. if message["type"] == "image":
  76. content.append({"type": "image"})
  77. elif message["type"] == "text":
  78. content.append({"type": "text", "text": message["text"].strip()})
  79. dialog.append({"role": role,"content":content})
  80. return tokenize_dialog(dialog,images, processor)
  81. def get_custom_dataset(dataset_config, processor, split, split_ratio=0.9):
  82. # load_dataset will return DatasetDict that contains all the data in the train set
  83. dataset_dict = load_dataset("remyxai/vqasynth_spacellava")
  84. dataset = dataset_dict[split]
  85. dataset = dataset.select(range(100))
  86. tokenized_datasets = dataset.map(lambda x: image_tokenize(x, processor))
  87. tokenized_datasets = tokenized_datasets.remove_columns(dataset.column_names)
  88. return tokenized_datasets