raft_dataset.py 4.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. # check system prompt token seq or user prompt token seq is in the current token list
  7. def check_header(targets,seq):
  8. for i in range(len(seq)-3):
  9. if seq[i:i+3] in targets:
  10. return True
  11. return False
  12. def replace_target(target,seq):
  13. for i in range(len(seq)-3):
  14. if seq[i:i+3] == target:
  15. seq[i],seq[i+1],seq[i+2] = -100,-100,-100
  16. return seq
  17. def tokenize_dialog(dialog, tokenizer):
  18. # If vocab size is above 128000, use the chat template to generate the tokens as it is from Llama 3 family models
  19. if tokenizer.vocab_size >= 128000:
  20. dialog_tokens = tokenizer.apply_chat_template(dialog)
  21. eot_indices = [i for i,n in enumerate(dialog_tokens) if n == 128009]
  22. labels = copy.copy(dialog_tokens)
  23. last_idx = 0
  24. # system prompt header "<|start_header_id|>system<|end_header_id|>" has been tokenized to [128006, 9125, 128007]
  25. # user prompt header "<|start_header_id|>user<|end_header_id|>" has been tokenized to [128006, 882, 128007]
  26. prompt_header_seqs = [[128006, 9125, 128007],[128006, 882, 128007]]
  27. for n, idx in enumerate(eot_indices):
  28. current_seq = labels[last_idx:idx+1]
  29. if check_header(prompt_header_seqs,current_seq):
  30. # found prompt header, indicating that this seq should be masked
  31. labels[last_idx:idx+1] = [-100] * (idx-last_idx+1)
  32. else:
  33. last_idx = idx
  34. # Lastly mask all the assistant header prompt <|start_header_id|>assistant<|end_header_id|>, which has been tokenized to [128006, 78191, 128007]
  35. assistant_header_seq = [128006, 78191, 128007]
  36. labels = replace_target(assistant_header_seq,labels)
  37. dialog_tokens = [dialog_tokens]
  38. labels_tokens = [labels]
  39. else:
  40. raise Exception("This raft_dataset only supports Llama 3 family models, please make sure the tokenizer is from Llama 3 family models.")
  41. combined_tokens = {
  42. "input_ids": list(itertools.chain(*(t for t in dialog_tokens))),
  43. "labels": list(itertools.chain(*(t for t in labels_tokens))),
  44. }
  45. return dict(combined_tokens, attention_mask=[1]*len(combined_tokens["input_ids"]))
  46. def raft_tokenize(q_a_pair, tokenizer):
  47. end_tag = "</DOCUMENT>"
  48. # find the last end_tag in the instruction, the rest is the question
  49. try:
  50. index =q_a_pair["instruction"].rindex(end_tag)+len(end_tag)
  51. except ValueError:
  52. print(q_a_pair["instruction"])
  53. raise Exception("The instruction does not contain the end tag <\/DOCUMENT>")
  54. # all the lines after end_tag are the question
  55. question = q_a_pair["instruction"][index:].strip()
  56. # all the lines before end_tag are the context
  57. documents = q_a_pair["instruction"][:index].strip()
  58. # output is the label
  59. answer = q_a_pair["output"]
  60. system_prompt = "You are a helpful chatbot who can provide an answer to every questions from the user given a relevant context."
  61. user_prompt = """
  62. Question: {question}\nContext: {context}\n
  63. Answer this question using the information given by multiple documents in the context above. Here are the things to pay attention to:
  64. - The context contains many documents, each document starts with <DOCUMENT> and ends </DOCUMENT>.
  65. - First provide step-by-step reasoning on how to answer the question.
  66. - 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.
  67. - End your response with final answer in the form <ANSWER>: $answer, the answer should less than 60 words.
  68. You MUST begin your final answer with the tag "<ANSWER>:".
  69. """.format(question=question, context=documents)
  70. chat = [
  71. {"role": "system", "content": system_prompt},
  72. {"role": "user", "content": user_prompt},
  73. {"role": "assistant", "content": answer}
  74. ]
  75. return tokenize_dialog(chat, tokenizer)
  76. def get_custom_dataset(dataset_config, tokenizer, split, split_ratio=0.9):
  77. # load_dataset will return DatasetDict that contains all the data in the train set
  78. dataset_dict = load_dataset('json', data_files=dataset_config.data_path)
  79. dataset = dataset_dict['train']
  80. dataset = dataset.train_test_split(test_size=1-split_ratio, shuffle=True, seed=42)
  81. dataset = dataset[split].map(lambda sample: {
  82. "instruction": sample["instruction"],
  83. "output": sample["cot_answer"],
  84. },
  85. batched=True,
  86. )
  87. dataset = dataset.map(lambda x: raft_tokenize(x, tokenizer))
  88. return dataset