custom_dataset.py 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. EOT_ID = 128009 #<|eot_id|>
  9. def tokenize_dialog(dialog, tokenizer):
  10. if tokenizer.vocab_size >= 128000:
  11. dialog_tokens = tokenizer.apply_chat_template(dialog)
  12. eot_indices = [i for i,n in enumerate(dialog_tokens) if n == EOT_ID]
  13. labels = copy.copy(dialog_tokens)
  14. #determine token for system and user
  15. system_or_user = (tokenizer.encode("system")[-1], tokenizer.encode("user")[-1])
  16. last_idx = 0
  17. for n, idx in enumerate(eot_indices):
  18. role_token = labels[last_idx:idx+1][2]
  19. if role_token in system_or_user:
  20. # Set labels to -100 for system and user tokens to ignore in loss function
  21. labels[last_idx:idx+1] = [-100] * (idx-last_idx+1)
  22. last_idx = idx
  23. dialog_tokens = [dialog_tokens]
  24. labels_tokens = [labels]
  25. else:
  26. prompt_tokens = [tokenizer.encode(f"{tokenizer.bos_token}{B_INST} {(prompt['content']).strip()} {E_INST}", add_special_tokens=False) for prompt in dialog[::2]]
  27. answer_tokens = [tokenizer.encode(f"{answer['content'].strip()} {tokenizer.eos_token}", add_special_tokens=False) for answer in dialog[1::2]]
  28. dialog_tokens = list(itertools.chain.from_iterable(zip(prompt_tokens, answer_tokens)))
  29. #Add labels, convert prompt token to -100 in order to ignore in loss function
  30. labels_tokens = [len(c)*[-100,] if i % 2 == 0 else c for i,c in enumerate(dialog_tokens)]
  31. combined_tokens = {
  32. "input_ids": list(itertools.chain(*(t for t in dialog_tokens))),
  33. "labels": list(itertools.chain(*(t for t in labels_tokens))),
  34. }
  35. return dict(combined_tokens, attention_mask=[1]*len(combined_tokens["input_ids"]))
  36. def get_custom_dataset(dataset_config, tokenizer, split):
  37. dataset = datasets.load_dataset("OpenAssistant/oasst1", split=split)
  38. dataset = dataset.map(lambda sample: {
  39. "message_id": sample["message_id"],
  40. "parent_id": sample["parent_id"],
  41. "text": sample["text"],
  42. },
  43. batched=True,
  44. remove_columns=list(dataset.features),)
  45. nodes = {}
  46. messages = {}
  47. root_ids = []
  48. for data in dataset:
  49. if data["parent_id"]:
  50. nodes[data["parent_id"]] = nodes.get(data["parent_id"], []) + [data["message_id"]]
  51. else:
  52. root_ids.append(data["message_id"])
  53. messages[data["message_id"]]=data["text"]
  54. def follow(thread, current_id):
  55. thread = copy.copy(thread) + [messages[current_id]]
  56. if current_id in nodes:
  57. new_threads = []
  58. for next_id in nodes[current_id]:
  59. new_threads += follow(thread, next_id)
  60. return new_threads
  61. else:
  62. return [thread]
  63. def get_threads_from_root(root_id):
  64. all_threads = []
  65. thread = [messages[root_id]]
  66. for cid in nodes[root_id]:
  67. all_threads += follow(thread, cid)
  68. return all_threads
  69. dataset = dataset.filter(lambda x: x["message_id"] in root_ids)
  70. dataset = dataset.map(lambda x: {"thread": get_threads_from_root(x["message_id"])}, remove_columns=list(dataset.features))
  71. dataset = dataset.map(lambda x: {"thread": [i for row in x["thread"] for i in row]}, batched=True)
  72. def to_dialog(thread):
  73. dialog = []
  74. for i, content in enumerate(thread):
  75. dialog.append({
  76. "role": "user" if i % 2 == 0 else "assistant",
  77. "content": content,
  78. })
  79. return {"dialog": dialog}
  80. dataset = dataset.map(lambda x: to_dialog(x["thread"]), remove_columns=list(dataset.features))
  81. dataset = dataset.map(lambda x: tokenize_dialog(x["dialog"], tokenizer), remove_columns=list(dataset.features))
  82. return dataset