raft_dataset.py 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  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. import datasets
  5. from datasets import Dataset, load_dataset, DatasetDict
  6. import itertools
  7. B_INST, E_INST = "[INST]", "[/INST]"
  8. # check system prompt token seq or user prompt token seq is in the current token list
  9. def check_header(targets,seq):
  10. for i in range(len(seq)-3):
  11. if seq[i:i+3] in targets:
  12. return True
  13. return False
  14. def replace_target(target,seq):
  15. for i in range(len(seq)-3):
  16. if seq[i:i+3] == target:
  17. seq[i],seq[i+1],seq[i+2] = -100,-100,-100
  18. return seq
  19. def tokenize_dialog(dialog, tokenizer):
  20. # If vocab size is above 128000, use the chat template to generate the tokens as it is from Llama 3 family models
  21. if tokenizer.vocab_size >= 128000:
  22. dialog_tokens = tokenizer.apply_chat_template(dialog)
  23. eot_indices = [i for i,n in enumerate(dialog_tokens) if n == 128009]
  24. labels = copy.copy(dialog_tokens)
  25. last_idx = 0
  26. token_length = len(dialog_tokens)
  27. last_idx = 0
  28. # system prompt header "<|start_header_id|>system<|end_header_id|>" has been tokenized to [128006, 9125, 128007]
  29. # user prompt header "<|start_header_id|>user<|end_header_id|>" has been tokenized to [128006, 882, 128007]
  30. prompt_header_seqs = [[128006, 9125, 128007],[128006, 882, 128007]]
  31. for n, idx in enumerate(eot_indices):
  32. current_seq = labels[last_idx:idx+1]
  33. if check_header(prompt_header_seqs,current_seq):
  34. # found prompt header, indicating that this seq should be masked
  35. labels[last_idx:idx+1] = [-100] * (idx-last_idx+1)
  36. else:
  37. last_idx = idx
  38. # Lastly mask all the assistant header prompt <|start_header_id|>assistant<|end_header_id|>, which has been tokenized to [128006, 78191, 128007]
  39. assistant_header_seq = [128006, 78191, 128007]
  40. labels = replace_target(assistant_header_seq,labels)
  41. dialog_tokens = [dialog_tokens]
  42. labels_tokens = [labels]
  43. else:
  44. # Otherwise, use the original tokenizer to generate the tokens as it is from Llama 2 family models
  45. prompt_tokens = [tokenizer.encode(f"{tokenizer.bos_token}{B_INST} {(prompt['content']).strip()} {E_INST}", add_special_tokens=False) for prompt in dialog[:2]]
  46. answer = dialog[-1]
  47. answer_tokens = tokenizer.encode(f"{answer['content'].strip()} {tokenizer.eos_token}", add_special_tokens=False)
  48. #Add labels, convert prompt token to -100 in order to ignore in loss function
  49. sample = {
  50. "input_ids": prompt_tokens + answer_tokens,
  51. "attention_mask" : [1] * (len(prompt_tokens) + len(answer_tokens)),
  52. "labels": [-100] * len(prompt_tokens) + answer_tokens,
  53. }
  54. return sample
  55. combined_tokens = {
  56. "input_ids": list(itertools.chain(*(t for t in dialog_tokens))),
  57. "labels": list(itertools.chain(*(t for t in labels_tokens))),
  58. }
  59. return dict(combined_tokens, attention_mask=[1]*len(combined_tokens["input_ids"]))
  60. def raft_tokenize(q_a_pair, tokenizer):
  61. # last line is the question
  62. question = q_a_pair["instruction"].split('\n')[-1]
  63. # all the lines before the last line are the context
  64. documents = q_a_pair["instruction"].split('\n')[:-1]
  65. # output is the label
  66. answer = q_a_pair["output"]
  67. system_prompt = "You are a helpful chatbot who can provide an answer to every questions from the user given a relevant context."
  68. user_prompt = """
  69. Question: {question}\nContext: {context}\n
  70. Answer this question using the information given multiple documents in the context above. Here is things to pay attention to:
  71. - First provide step-by-step reasoning on how to answer the question.
  72. - In the reasoning, if you need to copy paste some sentences from the context, include them in ##begin_quote## and ##end_quote##. This would mean that things outside of ##begin_quote## and ##end_quote## are not directly copy paste from the context.
  73. - End your response with final answer in the form <ANSWER>: $answer, the answer should be succinct.
  74. You MUST begin your final answer with the tag "<ANSWER>:".
  75. """.format(question=question, context=str(documents))
  76. chat = [
  77. {"role": "system", "content": system_prompt},
  78. {"role": "user", "content": user_prompt},
  79. {"role": "assistant", "content": answer}
  80. ]
  81. return tokenize_dialog(chat, tokenizer)
  82. def get_custom_dataset(dataset_config, tokenizer, split, split_ratio=0.8):
  83. # load_dataset will return DatasetDict that contains all the data in the train set
  84. dataset_dict = load_dataset('json', data_files=dataset_config.data_path)
  85. dataset = dataset_dict['train']
  86. dataset = dataset.train_test_split(test_size=1-split_ratio, shuffle=True, seed=42)
  87. dataset = dataset[split].map(lambda sample: {
  88. "instruction": sample["instruction"],
  89. "output": sample["cot_answer"],
  90. },
  91. batched=True,
  92. )
  93. dataset = dataset.map(lambda x: raft_tokenize(x, tokenizer))
  94. return dataset