custom_dataset.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. # Copyright (c) Meta Platforms, Inc. and affiliates.
  2. # This software may be used and distributed according to the terms of the Llama 2 Community License Agreement.
  3. # For dataset details visit: https://huggingface.co/datasets/samsum
  4. import copy
  5. import datasets
  6. import itertools
  7. B_INST, E_INST = "[INST]", "[/INST]"
  8. def tokenize_dialog(dialog, tokenizer):
  9. if tokenizer.vocab_size >= 128000:
  10. dialog_tokens = tokenizer.apply_chat_template(dialog)
  11. dialog_tokens = dialog_tokens[:-4] # Remove generation prompt <|start_header_id|>assistant<|end_header_id|>\n\n
  12. eot_indices = [i for i,n in enumerate(dialog_tokens) if n == 128009]
  13. labels = copy.copy(dialog_tokens)
  14. last_idx = 0
  15. for n, idx in enumerate(eot_indices):
  16. if n % 2 == 1:
  17. last_idx = idx
  18. else:
  19. labels[last_idx:idx+1] = [-100] * (idx-last_idx+1)
  20. dialog_tokens = [dialog_tokens]
  21. labels_tokens = [labels]
  22. else:
  23. prompt_tokens = [tokenizer.encode(f"{tokenizer.bos_token}{B_INST} {(prompt['content']).strip()} {E_INST}", add_special_tokens=False) for prompt in dialog[::2]]
  24. answer_tokens = [tokenizer.encode(f"{answer['content'].strip()} {tokenizer.eos_token}", add_special_tokens=False) for answer in dialog[1::2]]
  25. dialog_tokens = list(itertools.chain.from_iterable(zip(prompt_tokens, answer_tokens)))
  26. #Add labels, convert prompt token to -100 in order to ignore in loss function
  27. labels_tokens = [len(c)*[-100,] if i % 2 == 0 else c for i,c in enumerate(dialog_tokens)]
  28. combined_tokens = {
  29. "input_ids": list(itertools.chain(*(t for t in dialog_tokens))),
  30. "labels": list(itertools.chain(*(t for t in labels_tokens))),
  31. }
  32. return dict(combined_tokens, attention_mask=[1]*len(combined_tokens["input_ids"]))
  33. def get_custom_dataset(dataset_config, tokenizer, split):
  34. dataset = datasets.load_dataset("OpenAssistant/oasst1", split=split)
  35. dataset = dataset.map(lambda sample: {
  36. "message_id": sample["message_id"],
  37. "parent_id": sample["parent_id"],
  38. "text": sample["text"],
  39. },
  40. batched=True,
  41. remove_columns=list(dataset.features),)
  42. nodes = {}
  43. messages = {}
  44. root_ids = []
  45. for data in dataset:
  46. if data["parent_id"]:
  47. nodes[data["parent_id"]] = nodes.get(data["parent_id"], []) + [data["message_id"]]
  48. else:
  49. root_ids.append(data["message_id"])
  50. messages[data["message_id"]]=data["text"]
  51. def follow(thread, current_id):
  52. thread = copy.copy(thread) + [messages[current_id]]
  53. if current_id in nodes:
  54. new_threads = []
  55. for next_id in nodes[current_id]:
  56. new_threads += follow(thread, next_id)
  57. return new_threads
  58. else:
  59. return [thread]
  60. def get_threads_from_root(root_id):
  61. all_threads = []
  62. thread = [messages[root_id]]
  63. for cid in nodes[root_id]:
  64. all_threads += follow(thread, cid)
  65. return all_threads
  66. dataset = dataset.filter(lambda x: x["message_id"] in root_ids)
  67. dataset = dataset.map(lambda x: {"thread": get_threads_from_root(x["message_id"])}, remove_columns=list(dataset.features))
  68. dataset = dataset.map(lambda x: {"thread": [i for row in x["thread"] for i in row]}, batched=True)
  69. def to_dialog(thread):
  70. dialog = []
  71. for i, content in enumerate(thread):
  72. dialog.append({
  73. "role": "user" if i % 2 == 0 else "assistant",
  74. "content": content,
  75. })
  76. return {"dialog": dialog}
  77. dataset = dataset.map(lambda x: to_dialog(x["thread"]), remove_columns=list(dataset.features))
  78. dataset = dataset.map(lambda x: tokenize_dialog(x["dialog"], tokenizer), remove_columns=list(dataset.features))
  79. return dataset