2024-03-20 07:45:46 +08:00
|
|
|
import json
|
|
|
|
from pathlib import Path
|
2025-01-14 02:01:18 +08:00
|
|
|
from typing import Dict, List, Optional
|
2024-03-20 07:45:46 +08:00
|
|
|
|
|
|
|
from transformers import PreTrainedTokenizer
|
|
|
|
|
|
|
|
|
|
|
|
class Dataset:
|
|
|
|
"""
|
2024-06-27 01:20:50 +08:00
|
|
|
Light-weight wrapper to hold a dataset.
|
2024-03-20 07:45:46 +08:00
|
|
|
"""
|
|
|
|
|
2025-01-04 02:50:59 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
data: List[Dict[str, str]],
|
|
|
|
tokenizer: PreTrainedTokenizer,
|
|
|
|
text_key: str = "text",
|
|
|
|
):
|
|
|
|
self._data = [tokenizer.encode(d[text_key]) for d in data]
|
|
|
|
for d in self._data:
|
|
|
|
if d[-1] != tokenizer.eos_token_id:
|
|
|
|
d.append(tokenizer.eos_token_id)
|
2024-03-20 07:45:46 +08:00
|
|
|
|
|
|
|
def __getitem__(self, idx: int):
|
2025-01-04 02:50:59 +08:00
|
|
|
return self._data[idx]
|
2024-03-20 07:45:46 +08:00
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self._data)
|
|
|
|
|
|
|
|
|
2025-01-04 02:50:59 +08:00
|
|
|
class ChatDataset:
|
2024-03-20 07:45:46 +08:00
|
|
|
"""
|
|
|
|
A dataset for chat data in the format of {"messages": [...]}
|
|
|
|
https://platform.openai.com/docs/guides/fine-tuning/example-format
|
|
|
|
"""
|
|
|
|
|
2024-11-04 08:11:54 +08:00
|
|
|
def __init__(self, data: List[Dict[str, str]], tokenizer: PreTrainedTokenizer, chat_key: str = "messages"):
|
2025-01-04 02:50:59 +08:00
|
|
|
self._data = [
|
|
|
|
tokenizer.apply_chat_template(
|
2024-11-04 08:11:54 +08:00
|
|
|
d[chat_key],
|
2025-01-04 02:50:59 +08:00
|
|
|
tools=d.get("tools", None),
|
|
|
|
)
|
|
|
|
for d in data
|
|
|
|
]
|
2024-11-04 08:11:54 +08:00
|
|
|
self._chat_key = chat_key
|
2024-03-20 07:45:46 +08:00
|
|
|
|
|
|
|
def __getitem__(self, idx: int):
|
2025-01-04 02:50:59 +08:00
|
|
|
return self._data[idx]
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self._data)
|
2024-03-20 07:45:46 +08:00
|
|
|
|
|
|
|
|
2025-01-04 02:50:59 +08:00
|
|
|
class CompletionsDataset:
|
2024-03-20 07:45:46 +08:00
|
|
|
"""
|
|
|
|
A dataset for prompt-completion data in the format of {"prompt": ..., "completion": ...}
|
2024-06-27 01:20:50 +08:00
|
|
|
or using user-provided keys for prompt and completion values
|
2024-03-20 07:45:46 +08:00
|
|
|
https://platform.openai.com/docs/guides/fine-tuning/example-format
|
|
|
|
"""
|
|
|
|
|
2024-06-27 01:20:50 +08:00
|
|
|
def __init__(
|
|
|
|
self,
|
|
|
|
data: List[Dict[str, str]],
|
|
|
|
tokenizer: PreTrainedTokenizer,
|
2025-01-14 02:01:18 +08:00
|
|
|
prompt_key: str,
|
|
|
|
completion_key: str,
|
2024-06-27 01:20:50 +08:00
|
|
|
):
|
2025-01-04 02:50:59 +08:00
|
|
|
self._data = [
|
|
|
|
tokenizer.apply_chat_template(
|
|
|
|
[
|
|
|
|
{"role": "user", "content": d[prompt_key]},
|
|
|
|
{"role": "assistant", "content": d[completion_key]},
|
|
|
|
],
|
|
|
|
)
|
|
|
|
for d in data
|
|
|
|
]
|
2024-11-06 04:17:23 +08:00
|
|
|
|
2024-03-20 07:45:46 +08:00
|
|
|
def __getitem__(self, idx: int):
|
2025-01-04 02:50:59 +08:00
|
|
|
return self._data[idx]
|
|
|
|
|
|
|
|
def __len__(self):
|
|
|
|
return len(self._data)
|
2024-03-20 07:45:46 +08:00
|
|
|
|
|
|
|
|
2024-11-04 08:11:54 +08:00
|
|
|
class CompletionsDatasetCollection:
|
|
|
|
def __init__(self, data: List[Union[ChatDataset, CompletionsDataset]]):
|
|
|
|
self.collection = data
|
|
|
|
|
2024-11-07 01:53:54 +08:00
|
|
|
def __fetch_and_process_item__(self, idx: int, handler_fn: Callable):
|
2024-11-04 09:30:47 +08:00
|
|
|
iteration = iter(self.collection)
|
|
|
|
item = next(iteration)
|
2024-11-04 08:11:54 +08:00
|
|
|
|
|
|
|
curr_idx = idx
|
|
|
|
|
|
|
|
while True:
|
|
|
|
try:
|
2024-11-04 09:36:55 +08:00
|
|
|
if (curr_idx + 1) <= len(item):
|
2024-11-07 01:53:54 +08:00
|
|
|
return handler_fn(item, curr_idx)
|
2024-11-04 08:11:54 +08:00
|
|
|
else:
|
|
|
|
curr_idx -= len(item)
|
2024-11-04 09:30:47 +08:00
|
|
|
item = next(iteration)
|
2024-11-04 08:11:54 +08:00
|
|
|
except StopIteration:
|
|
|
|
raise IndexError(idx)
|
|
|
|
|
2024-11-07 01:53:54 +08:00
|
|
|
def __getitem__(self, idx: int):
|
|
|
|
def getitem(dataset: CompletionsDataset, index: int):
|
|
|
|
return dataset[index]
|
|
|
|
|
|
|
|
return self.__fetch_and_process_item__(idx, getitem)
|
|
|
|
|
|
|
|
def get_prompt_and_completion(self, idx: int):
|
|
|
|
def getitem(dataset: CompletionsDataset, index: int):
|
2024-11-07 01:58:00 +08:00
|
|
|
return dataset.get_prompt_and_completion(index)
|
2024-11-07 01:53:54 +08:00
|
|
|
|
|
|
|
return self.__fetch_and_process_item__(idx, getitem)
|
|
|
|
|
2024-11-04 08:11:54 +08:00
|
|
|
def __len__(self):
|
|
|
|
return sum(map(len, self.collection))
|
|
|
|
|
|
|
|
|
2025-01-14 02:01:18 +08:00
|
|
|
def create_dataset(
|
|
|
|
data,
|
|
|
|
tokenizer: PreTrainedTokenizer,
|
|
|
|
prompt_feature: Optional[str] = None,
|
|
|
|
completion_feature: Optional[str] = None,
|
|
|
|
):
|
|
|
|
prompt_feature = prompt_feature or "prompt"
|
|
|
|
completion_feature = completion_feature or "completion"
|
2024-09-30 22:36:21 +08:00
|
|
|
sample = data[0]
|
|
|
|
if "messages" in sample:
|
2024-06-27 01:20:50 +08:00
|
|
|
return ChatDataset(data, tokenizer)
|
2025-01-14 02:01:18 +08:00
|
|
|
elif prompt_feature in sample and completion_feature in sample:
|
|
|
|
return CompletionsDataset(data, tokenizer, prompt_feature, completion_feature)
|
2024-09-30 22:36:21 +08:00
|
|
|
elif "text" in sample:
|
2025-01-04 02:50:59 +08:00
|
|
|
return Dataset(data, tokenizer)
|
2024-03-20 07:45:46 +08:00
|
|
|
else:
|
|
|
|
raise ValueError(
|
|
|
|
"Unsupported data format, check the supported formats here:\n"
|
|
|
|
"https://github.com/ml-explore/mlx-examples/blob/main/llms/mlx_lm/LORA.md#data."
|
|
|
|
)
|
|
|
|
|
|
|
|
|
2025-01-14 02:01:18 +08:00
|
|
|
def load_local_dataset(
|
|
|
|
data_path: Path,
|
|
|
|
tokenizer: PreTrainedTokenizer,
|
|
|
|
prompt_feature: Optional[str] = None,
|
|
|
|
completion_feature: Optional[str] = None,
|
|
|
|
):
|
2024-09-30 22:36:21 +08:00
|
|
|
def load_subset(path):
|
|
|
|
if not path.exists():
|
|
|
|
return []
|
|
|
|
with open(path, "r") as fid:
|
|
|
|
data = [json.loads(l) for l in fid]
|
2025-01-14 02:01:18 +08:00
|
|
|
return create_dataset(data, tokenizer, prompt_feature, completion_feature)
|
2024-09-30 22:36:21 +08:00
|
|
|
|
|
|
|
names = ("train", "valid", "test")
|
|
|
|
train, valid, test = [load_subset(data_path / f"{n}.jsonl") for n in names]
|
|
|
|
return train, valid, test
|
|
|
|
|
|
|
|
|
2025-01-14 02:01:18 +08:00
|
|
|
def load_hf_dataset(
|
|
|
|
data_id: str,
|
|
|
|
tokenizer: PreTrainedTokenizer,
|
|
|
|
prompt_feature: Optional[str] = None,
|
|
|
|
completion_feature: Optional[str] = None,
|
|
|
|
):
|
2024-09-30 22:36:21 +08:00
|
|
|
from datasets import exceptions, load_dataset
|
|
|
|
|
|
|
|
try:
|
|
|
|
dataset = load_dataset(data_id)
|
2024-06-27 01:20:50 +08:00
|
|
|
|
|
|
|
names = ("train", "valid", "test")
|
|
|
|
|
|
|
|
train, valid, test = [
|
2025-01-14 02:01:18 +08:00
|
|
|
(
|
|
|
|
create_dataset(
|
|
|
|
dataset[n], tokenizer, prompt_feature, completion_feature
|
|
|
|
)
|
|
|
|
if n in dataset.keys()
|
|
|
|
else []
|
|
|
|
)
|
2024-09-30 22:36:21 +08:00
|
|
|
for n in names
|
2024-06-27 01:20:50 +08:00
|
|
|
]
|
2024-09-30 22:36:21 +08:00
|
|
|
|
|
|
|
except exceptions.DatasetNotFoundError:
|
|
|
|
raise ValueError(f"Not found Hugging Face dataset: {data_id} .")
|
|
|
|
|
|
|
|
return train, valid, test
|
|
|
|
|
|
|
|
|
|
|
|
def load_custom_hf_dataset(args, tokenizer: PreTrainedTokenizer):
|
|
|
|
import datasets
|
|
|
|
|
2024-11-04 08:11:54 +08:00
|
|
|
def create_hf_dataset(
|
|
|
|
dataset_name,
|
|
|
|
text_feature,
|
|
|
|
prompt_feature,
|
|
|
|
completion_feature,
|
|
|
|
chat_feature,
|
|
|
|
split,
|
|
|
|
):
|
2024-09-30 22:36:21 +08:00
|
|
|
ds = datasets.load_dataset(
|
|
|
|
dataset_name,
|
|
|
|
split=split,
|
|
|
|
**hf_args.get("config", {}),
|
|
|
|
)
|
|
|
|
if prompt_feature and completion_feature:
|
|
|
|
return CompletionsDataset(ds, tokenizer, prompt_feature, completion_feature)
|
2024-11-04 08:11:54 +08:00
|
|
|
elif chat_feature:
|
|
|
|
return ChatDataset(ds, tokenizer, chat_key=chat_feature)
|
2024-09-30 22:36:21 +08:00
|
|
|
elif text_feature:
|
2025-01-22 06:12:43 +08:00
|
|
|
return Dataset(ds, tokenizer, text_key=text_feature)
|
2024-09-30 22:36:21 +08:00
|
|
|
else:
|
|
|
|
raise ValueError(
|
2024-11-04 08:11:54 +08:00
|
|
|
"Specify either a prompt and completion feature, a chat feature,"
|
|
|
|
" or a text feature for the Hugging Face dataset."
|
2024-09-30 22:36:21 +08:00
|
|
|
)
|
|
|
|
|
2024-11-04 08:11:54 +08:00
|
|
|
def get_train_and_valid_splits(hf_args, ds_name):
|
|
|
|
text_f = hf_args.get("text_feature", None)
|
|
|
|
prompt_f = hf_args.get("prompt_feature", None)
|
|
|
|
completion_f = hf_args.get("completion_feature", None)
|
|
|
|
chat_f = hf_args.get("chat_feature", None)
|
|
|
|
if args.train:
|
|
|
|
train_split = hf_args.get("train_split", "train[:80%]")
|
|
|
|
valid_split = hf_args.get("valid_split", "train[-10%:]")
|
|
|
|
train = create_hf_dataset(
|
|
|
|
ds_name, text_f, prompt_f, completion_f, chat_f, split=train_split
|
|
|
|
)
|
|
|
|
valid = create_hf_dataset(
|
|
|
|
ds_name, text_f, prompt_f, completion_f, chat_f, split=valid_split
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
train, valid = [], []
|
2024-09-30 22:36:21 +08:00
|
|
|
|
2024-11-04 08:11:54 +08:00
|
|
|
if args.test:
|
|
|
|
test_split = hf_args.get("test_split")
|
|
|
|
test = create_hf_dataset(
|
|
|
|
ds_name, text_f, prompt_f, completion_f, chat_f, split=test_split,
|
|
|
|
)
|
|
|
|
else:
|
|
|
|
test = []
|
|
|
|
|
|
|
|
return train, valid, test
|
|
|
|
|
|
|
|
if args.datasets:
|
|
|
|
dataset_collection = args.hf_datasets
|
|
|
|
else:
|
|
|
|
dataset_collection = {"hf_dataset": args.hf_dataset}
|
|
|
|
|
|
|
|
datasets = []
|
|
|
|
for ds in dataset_collection:
|
|
|
|
hf_args = ds["hf_dataset"]
|
|
|
|
dataset_name = hf_args["name"]
|
|
|
|
print(f"Loading Hugging Face dataset {dataset_name}.")
|
|
|
|
datasets.append(get_splits(hf_args, dataset_name))
|
|
|
|
if len(datsets) == 1:
|
|
|
|
return *datasets
|
|
|
|
|
|
|
|
# Otherwise concatenate them
|
|
|
|
train, valid, test = zip(*datasets)
|
|
|
|
return tuple(map, Concatenate, zip(*datasets))
|
2024-09-30 22:36:21 +08:00
|
|
|
|
|
|
|
|
|
|
|
def load_dataset(args, tokenizer: PreTrainedTokenizer):
|
2024-11-04 09:04:15 +08:00
|
|
|
if getattr(args, "hf_dataset", False) or getattr(args, "hf_datasets", False):
|
2024-09-30 22:36:21 +08:00
|
|
|
train, valid, test = load_custom_hf_dataset(args, tokenizer)
|
|
|
|
else:
|
|
|
|
data_path = Path(args.data)
|
2025-01-14 02:01:18 +08:00
|
|
|
|
|
|
|
prompt_feature = getattr(args, "prompt_feature", None)
|
|
|
|
completion_feature = getattr(args, "completion_feature", None)
|
2024-09-30 22:36:21 +08:00
|
|
|
if data_path.exists():
|
2025-01-14 02:01:18 +08:00
|
|
|
train, valid, test = load_local_dataset(
|
|
|
|
data_path, tokenizer, prompt_feature, completion_feature
|
|
|
|
)
|
2024-09-30 22:36:21 +08:00
|
|
|
else:
|
|
|
|
print(f"Loading Hugging Face dataset {args.data}.")
|
2025-01-14 02:01:18 +08:00
|
|
|
train, valid, test = load_hf_dataset(
|
|
|
|
args.data, tokenizer, prompt_feature, completion_feature
|
|
|
|
)
|
2024-09-30 22:36:21 +08:00
|
|
|
|
2024-03-20 07:45:46 +08:00
|
|
|
if args.train and len(train) == 0:
|
|
|
|
raise ValueError(
|
|
|
|
"Training set not found or empty. Must provide training set for fine-tuning."
|
|
|
|
)
|
|
|
|
if args.train and len(valid) == 0:
|
|
|
|
raise ValueError(
|
|
|
|
"Validation set not found or empty. Must provide validation set for fine-tuning."
|
|
|
|
)
|
|
|
|
if args.test and len(test) == 0:
|
|
|
|
raise ValueError(
|
|
|
|
"Test set not found or empty. Must provide test set for evaluation."
|
|
|
|
)
|
|
|
|
return train, valid, test
|