loader.py 14.9 KB
Newer Older
chenych's avatar
chenych committed
1
# Copyright 2025 the LlamaFactory team.
chenych's avatar
chenych committed
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import os
import sys
from typing import TYPE_CHECKING, Dict, Literal, Optional, Sequence, Union

import numpy as np
from datasets import DatasetDict, load_dataset, load_from_disk

luopl's avatar
luopl committed
22
from ..extras import logging
chenych's avatar
chenych committed
23
from ..extras.constants import FILEEXT2TYPE
luopl's avatar
luopl committed
24
from ..extras.misc import check_version, has_tokenized_data
chenych's avatar
chenych committed
25
from .converter import align_dataset
chenych's avatar
chenych committed
26
27
from .data_utils import merge_dataset, split_dataset
from .parser import get_dataset_list
chenych's avatar
chenych committed
28
29
30
31
32
33
34
35
from .processor import (
    FeedbackDatasetProcessor,
    PackedSupervisedDatasetProcessor,
    PairwiseDatasetProcessor,
    PretrainDatasetProcessor,
    SupervisedDatasetProcessor,
    UnsupervisedDatasetProcessor,
)
chenych's avatar
chenych committed
36
37
38
39
40
41
42
43
44


if TYPE_CHECKING:
    from datasets import Dataset, IterableDataset
    from transformers import PreTrainedTokenizer, ProcessorMixin, Seq2SeqTrainingArguments

    from ..hparams import DataArguments, ModelArguments
    from .data_utils import DatasetModule
    from .parser import DatasetAttr
chenych's avatar
chenych committed
45
    from .processor import DatasetProcessor
chenych's avatar
chenych committed
46
47
48
    from .template import Template


luopl's avatar
luopl committed
49
logger = logging.get_logger(__name__)
chenych's avatar
chenych committed
50
51
52
53
54
55
56
57


def _load_single_dataset(
    dataset_attr: "DatasetAttr",
    model_args: "ModelArguments",
    data_args: "DataArguments",
    training_args: "Seq2SeqTrainingArguments",
) -> Union["Dataset", "IterableDataset"]:
luopl's avatar
luopl committed
58
59
60
    r"""
    Loads a single dataset and aligns it to the standard format.
    """
luopl's avatar
luopl committed
61
    logger.info_rank0(f"Loading dataset {dataset_attr}...")
chenych's avatar
chenych committed
62
    data_path, data_name, data_dir, data_files = None, None, None, None
luopl's avatar
luopl committed
63
    if dataset_attr.load_from in ["hf_hub", "ms_hub", "om_hub"]:
chenych's avatar
chenych committed
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
        data_path = dataset_attr.dataset_name
        data_name = dataset_attr.subset
        data_dir = dataset_attr.folder

    elif dataset_attr.load_from == "script":
        data_path = os.path.join(data_args.dataset_dir, dataset_attr.dataset_name)
        data_name = dataset_attr.subset
        data_dir = dataset_attr.folder

    elif dataset_attr.load_from == "file":
        data_files = []
        local_path = os.path.join(data_args.dataset_dir, dataset_attr.dataset_name)
        if os.path.isdir(local_path):  # is directory
            for file_name in os.listdir(local_path):
                data_files.append(os.path.join(local_path, file_name))
        elif os.path.isfile(local_path):  # is file
            data_files.append(local_path)
        else:
luopl's avatar
luopl committed
82
            raise ValueError(f"File {local_path} not found.")
chenych's avatar
chenych committed
83

luopl's avatar
luopl committed
84
        data_path = FILEEXT2TYPE.get(os.path.splitext(data_files[0])[-1][1:], None)
chenych's avatar
chenych committed
85
86
        if data_path is None:
            raise ValueError("Allowed file types: {}.".format(",".join(FILEEXT2TYPE.keys())))
luopl's avatar
luopl committed
87
88
89

        if any(data_path != FILEEXT2TYPE.get(os.path.splitext(data_file)[-1][1:], None) for data_file in data_files):
            raise ValueError("File types should be identical.")
chenych's avatar
chenych committed
90
    else:
luopl's avatar
luopl committed
91
        raise NotImplementedError(f"Unknown load type: {dataset_attr.load_from}.")
chenych's avatar
chenych committed
92
93

    if dataset_attr.load_from == "ms_hub":
luopl's avatar
luopl committed
94
        check_version("modelscope>=1.11.0", mandatory=True)
luopl's avatar
luopl committed
95
96
        from modelscope import MsDataset  # type: ignore
        from modelscope.utils.config_ds import MS_DATASETS_CACHE  # type: ignore
chenych's avatar
chenych committed
97
98
99
100
101
102
103
104
105
106

        cache_dir = model_args.cache_dir or MS_DATASETS_CACHE
        dataset = MsDataset.load(
            dataset_name=data_path,
            subset_name=data_name,
            data_dir=data_dir,
            data_files=data_files,
            split=dataset_attr.split,
            cache_dir=cache_dir,
            token=model_args.ms_hub_token,
luopl's avatar
luopl committed
107
            use_streaming=data_args.streaming,
chenych's avatar
chenych committed
108
109
110
        )
        if isinstance(dataset, MsDataset):
            dataset = dataset.to_hf_dataset()
luopl's avatar
luopl committed
111
112

    elif dataset_attr.load_from == "om_hub":
luopl's avatar
luopl committed
113
        check_version("openmind>=0.8.0", mandatory=True)
luopl's avatar
luopl committed
114
115
116
117
118
119
120
121
122
123
124
125
126
127
        from openmind import OmDataset  # type: ignore
        from openmind.utils.hub import OM_DATASETS_CACHE  # type: ignore

        cache_dir = model_args.cache_dir or OM_DATASETS_CACHE
        dataset = OmDataset.load_dataset(
            path=data_path,
            name=data_name,
            data_dir=data_dir,
            data_files=data_files,
            split=dataset_attr.split,
            cache_dir=cache_dir,
            token=model_args.om_hub_token,
            streaming=data_args.streaming,
        )
chenych's avatar
chenych committed
128
129
130
131
132
133
134
135
136
    else:
        dataset = load_dataset(
            path=data_path,
            name=data_name,
            data_dir=data_dir,
            data_files=data_files,
            split=dataset_attr.split,
            cache_dir=model_args.cache_dir,
            token=model_args.hf_hub_token,
luopl's avatar
luopl committed
137
            streaming=data_args.streaming,
luopl's avatar
luopl committed
138
139
            num_proc=data_args.preprocessing_num_workers,
            trust_remote_code=model_args.trust_remote_code,
chenych's avatar
chenych committed
140
141
142
143
        )

    if dataset_attr.num_samples is not None and not data_args.streaming:
        target_num = dataset_attr.num_samples
luopl's avatar
luopl committed
144
        indexes = np.random.permutation(len(dataset))[:target_num]  # all samples should be included
chenych's avatar
chenych committed
145
146
147
148
149
150
151
        target_num -= len(indexes)
        if target_num > 0:
            expand_indexes = np.random.choice(len(dataset), target_num)
            indexes = np.concatenate((indexes, expand_indexes), axis=0)

        assert len(indexes) == dataset_attr.num_samples, "Sample num mismatched."
        dataset = dataset.select(indexes)
luopl's avatar
luopl committed
152
        logger.info_rank0(f"Sampled {dataset_attr.num_samples} examples from dataset {dataset_attr}.")
chenych's avatar
chenych committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166

    if data_args.max_samples is not None:  # truncate dataset
        max_samples = min(data_args.max_samples, len(dataset))
        dataset = dataset.select(range(max_samples))

    return align_dataset(dataset, dataset_attr, data_args, training_args)


def _get_merged_dataset(
    dataset_names: Optional[Sequence[str]],
    model_args: "ModelArguments",
    data_args: "DataArguments",
    training_args: "Seq2SeqTrainingArguments",
    stage: Literal["pt", "sft", "rm", "ppo", "kto"],
chenych's avatar
chenych committed
167
168
    merge: bool = True,
) -> Optional[Union["Dataset", "IterableDataset", Dict[str, "Dataset"]]]:
luopl's avatar
luopl committed
169
    r"""
chenych's avatar
chenych committed
170
    Returns the merged datasets in the standard format.
luopl's avatar
luopl committed
171
    """
chenych's avatar
chenych committed
172
173
174
    if dataset_names is None:
        return None

chenych's avatar
chenych committed
175
176
    datasets = {}
    for dataset_name, dataset_attr in zip(dataset_names, get_dataset_list(dataset_names, data_args.dataset_dir)):
chenych's avatar
chenych committed
177
178
179
        if (stage == "rm" and dataset_attr.ranking is False) or (stage != "rm" and dataset_attr.ranking is True):
            raise ValueError("The dataset is not applicable in the current training stage.")

chenych's avatar
chenych committed
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
        datasets[dataset_name] = _load_single_dataset(dataset_attr, model_args, data_args, training_args)

    if merge:
        return merge_dataset(list(datasets.values()), data_args, seed=training_args.seed)
    else:
        return datasets


def _get_dataset_processor(
    data_args: "DataArguments",
    stage: Literal["pt", "sft", "rm", "ppo", "kto"],
    template: "Template",
    tokenizer: "PreTrainedTokenizer",
    processor: Optional["ProcessorMixin"],
    do_generate: bool = False,
) -> "DatasetProcessor":
    r"""
    Returns the corresponding dataset processor.
    """
    if stage == "pt":
        dataset_processor_class = PretrainDatasetProcessor
    elif stage == "sft" and not do_generate:
        if data_args.packing:
            if data_args.neat_packing:  # hack datasets to have int32 attention mask
                from datasets.arrow_writer import OptimizedTypedSequence, TypedSequence

                def __init__(self, data, **kwargs):
                    return TypedSequence.__init__(
                        self,
                        data,
                        type=kwargs.pop("type", None),
                        try_type=kwargs.pop("try_type", None),
                        optimized_int_type=kwargs.pop("optimized_int_type", None),
                    )

                OptimizedTypedSequence.__init__ = __init__
            dataset_processor_class = PackedSupervisedDatasetProcessor
        else:
            dataset_processor_class = SupervisedDatasetProcessor

    elif stage == "rm":
        dataset_processor_class = PairwiseDatasetProcessor
    elif stage == "kto":
        dataset_processor_class = FeedbackDatasetProcessor
    else:
        dataset_processor_class = UnsupervisedDatasetProcessor
chenych's avatar
chenych committed
226

chenych's avatar
chenych committed
227
    return dataset_processor_class(template=template, tokenizer=tokenizer, processor=processor, data_args=data_args)
chenych's avatar
chenych committed
228
229
230
231
232
233
234
235
236
237
238
239


def _get_preprocessed_dataset(
    dataset: Optional[Union["Dataset", "IterableDataset"]],
    data_args: "DataArguments",
    training_args: "Seq2SeqTrainingArguments",
    stage: Literal["pt", "sft", "rm", "ppo", "kto"],
    template: "Template",
    tokenizer: "PreTrainedTokenizer",
    processor: Optional["ProcessorMixin"] = None,
    is_eval: bool = False,
) -> Optional[Union["Dataset", "IterableDataset"]]:
luopl's avatar
luopl committed
240
241
242
    r"""
    Preprocesses the dataset, including format checking and tokenization.
    """
chenych's avatar
chenych committed
243
244
245
    if dataset is None:
        return None

chenych's avatar
chenych committed
246
    dataset_processor = _get_dataset_processor(
chenych's avatar
chenych committed
247
248
249
250
251
252
253
254
255
256
257
        data_args, stage, template, tokenizer, processor, do_generate=(training_args.predict_with_generate and is_eval)
    )
    column_names = list(next(iter(dataset)).keys())
    kwargs = {}
    if not data_args.streaming:
        kwargs = dict(
            num_proc=data_args.preprocessing_num_workers,
            load_from_cache_file=(not data_args.overwrite_cache) or (training_args.local_process_index != 0),
            desc="Running tokenizer on dataset",
        )

luopl's avatar
luopl committed
258
    dataset = dataset.map(
chenych's avatar
chenych committed
259
        dataset_processor.preprocess_dataset,
luopl's avatar
luopl committed
260
261
262
263
264
        batched=True,
        batch_size=data_args.preprocessing_batch_size,
        remove_columns=column_names,
        **kwargs,
    )
chenych's avatar
chenych committed
265
266
267
268

    if training_args.should_log:
        try:
            print("eval example:" if is_eval else "training example:")
chenych's avatar
chenych committed
269
            dataset_processor.print_data_example(next(iter(dataset)))
chenych's avatar
chenych committed
270
271
272
273
274
275
276
277
278
279
        except StopIteration:
            if stage == "pt":
                raise RuntimeError("Cannot find sufficient samples, consider increasing dataset size.")
            else:
                raise RuntimeError("Cannot find valid samples, check `data/README.md` for the data format.")

    return dataset


def get_dataset(
luopl's avatar
luopl committed
280
    template: "Template",
chenych's avatar
chenych committed
281
282
283
284
285
286
287
    model_args: "ModelArguments",
    data_args: "DataArguments",
    training_args: "Seq2SeqTrainingArguments",
    stage: Literal["pt", "sft", "rm", "ppo", "kto"],
    tokenizer: "PreTrainedTokenizer",
    processor: Optional["ProcessorMixin"] = None,
) -> "DatasetModule":
luopl's avatar
luopl committed
288
289
290
    r"""
    Gets the train dataset and optionally gets the evaluation dataset.
    """
chenych's avatar
chenych committed
291
    # Load tokenized dataset if path exists
chenych's avatar
chenych committed
292
293
    if data_args.tokenized_path is not None:
        if has_tokenized_data(data_args.tokenized_path):
luopl's avatar
luopl committed
294
            logger.warning_rank0("Loading dataset from disk will ignore other data arguments.")
luopl's avatar
luopl committed
295
            tokenized_data: Union["Dataset", "DatasetDict"] = load_from_disk(data_args.tokenized_path)
luopl's avatar
luopl committed
296
            logger.info_rank0(f"Loaded tokenized dataset from {data_args.tokenized_path}.")
chenych's avatar
chenych committed
297
298

            dataset_module: Dict[str, "Dataset"] = {}
luopl's avatar
luopl committed
299
300
301
302
303
304
            if isinstance(tokenized_data, DatasetDict):
                if "train" in tokenized_data:
                    dataset_module["train_dataset"] = tokenized_data["train"]

                if "validation" in tokenized_data:
                    dataset_module["eval_dataset"] = tokenized_data["validation"]
luopl's avatar
luopl committed
305

chenych's avatar
chenych committed
306
            else:  # single dataset
luopl's avatar
luopl committed
307
                dataset_module["train_dataset"] = tokenized_data
chenych's avatar
chenych committed
308
309
310
311
312
313
314
315
316
317
318
319

            if data_args.streaming:
                dataset_module = {k: v.to_iterable_dataset() for k, v in dataset_module.items()}

            return dataset_module

        if data_args.streaming:
            raise ValueError("Turn off `streaming` when saving dataset to disk.")

    # Load and preprocess dataset
    with training_args.main_process_first(desc="load dataset"):
        dataset = _get_merged_dataset(data_args.dataset, model_args, data_args, training_args, stage)
chenych's avatar
chenych committed
320
321
322
        eval_dataset = _get_merged_dataset(
            data_args.eval_dataset, model_args, data_args, training_args, stage, merge=training_args.do_predict
        )
chenych's avatar
chenych committed
323
324
325
326
327

    with training_args.main_process_first(desc="pre-process dataset"):
        dataset = _get_preprocessed_dataset(
            dataset, data_args, training_args, stage, template, tokenizer, processor, is_eval=False
        )
chenych's avatar
chenych committed
328
329
330
331
332
333
334
335
336
        if isinstance(eval_dataset, dict):
            for eval_name, eval_data in eval_dataset.items():
                eval_dataset[eval_name] = _get_preprocessed_dataset(
                    eval_data, data_args, training_args, stage, template, tokenizer, processor, is_eval=True
                )
        else:
            eval_dataset = _get_preprocessed_dataset(
                eval_dataset, data_args, training_args, stage, template, tokenizer, processor, is_eval=True
            )
chenych's avatar
chenych committed
337
338
339
340
341
342
343
344
345
346
347
348

        if data_args.val_size > 1e-6:
            dataset_dict = split_dataset(dataset, data_args, seed=training_args.seed)
        else:
            dataset_dict = {}
            if dataset is not None:
                if data_args.streaming:
                    dataset = dataset.shuffle(buffer_size=data_args.buffer_size, seed=training_args.seed)

                dataset_dict["train"] = dataset

            if eval_dataset is not None:
chenych's avatar
chenych committed
349
350
351
352
353
                if isinstance(eval_dataset, dict):
                    dataset_dict.update({f"validation_{name}": data for name, data in eval_dataset.items()})
                else:
                    if data_args.streaming:
                        eval_dataset = eval_dataset.shuffle(buffer_size=data_args.buffer_size, seed=training_args.seed)
chenych's avatar
chenych committed
354

chenych's avatar
chenych committed
355
                    dataset_dict["validation"] = eval_dataset
chenych's avatar
chenych committed
356
357
358

            dataset_dict = DatasetDict(dataset_dict)

chenych's avatar
chenych committed
359
        if data_args.tokenized_path is not None:  # save tokenized dataset to disk and exit
chenych's avatar
chenych committed
360
361
            if training_args.should_save:
                dataset_dict.save_to_disk(data_args.tokenized_path)
chenych's avatar
chenych committed
362
                logger.info_rank0(f"Tokenized dataset is saved at {data_args.tokenized_path}.")
luopl's avatar
luopl committed
363
                logger.info_rank0(f"Please restart the training with `tokenized_path: {data_args.tokenized_path}`.")
chenych's avatar
chenych committed
364
365
366
367
368
369

            sys.exit(0)

        dataset_module = {}
        if "train" in dataset_dict:
            dataset_module["train_dataset"] = dataset_dict["train"]
luopl's avatar
luopl committed
370

chenych's avatar
chenych committed
371
372
        if "validation" in dataset_dict:
            dataset_module["eval_dataset"] = dataset_dict["validation"]
chenych's avatar
chenych committed
373
374
375
376
377
378
379
380
        else:
            eval_dataset = {}
            for key in dataset_dict.keys():
                if key.startswith("validation_"):
                    eval_dataset[key[len("validation_") :]] = dataset_dict[key]

            if len(eval_dataset):
                dataset_module["eval_dataset"] = eval_dataset
chenych's avatar
chenych committed
381
382

        return dataset_module