custom_dataset.py 3.2 KB

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