| 1 | # Copyright 2025 the LlamaFactory team. |
| 2 | # |
| 3 | # Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | # you may not use this file except in compliance with the License. |
| 5 | # You may obtain a copy of the License at |
| 6 | # |
| 7 | # http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | # |
| 9 | # Unless required by applicable law or agreed to in writing, software |
| 10 | # distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | # See the License for the specific language governing permissions and |
| 13 | # limitations under the License. |
| 14 | |
| 15 | import os |
| 16 | from abc import abstractmethod |
| 17 | from dataclasses import dataclass |
| 18 | from typing import TYPE_CHECKING, Any, Optional, Union |
| 19 | |
| 20 | from ..framework import logging |
| 21 | from .template import Role |
| 22 | |
| 23 | |
| 24 | if TYPE_CHECKING: |
| 25 | from datasets import Dataset, IterableDataset |
| 26 | from transformers import Seq2SeqTrainingArguments |
| 27 | |
| 28 | from ..hparams import DataArguments |
| 29 | from .mm_plugin import PointCloudInput |
| 30 | from .loader import DatasetAttr |
| 31 | |
| 32 | MediaType = Union[PointCloudInput] |
| 33 | |
| 34 | |
| 35 | logger = logging.get_logger(__name__) |
| 36 | |
| 37 | |
| 38 | @dataclass |
| 39 | class DatasetConverter: |
| 40 | dataset_attr: "DatasetAttr" |
| 41 | data_args: "DataArguments" |
| 42 | |
| 43 | def _find_medias( |
| 44 | self, medias: Union["MediaType", list["MediaType"], None] |
| 45 | ) -> Optional[list["MediaType"]]: |
| 46 | r"""Optionally concatenate media path to media dir when loading from local disk.""" |
| 47 | if medias is None: |
| 48 | return None |
| 49 | elif not isinstance(medias, list): |
| 50 | medias = [medias] |
| 51 | elif len(medias) == 0: |
| 52 | return None |
| 53 | else: |
| 54 | medias = medias[:] |
| 55 | |
| 56 | if self.dataset_attr.load_from in ["file"]: |
| 57 | if isinstance(medias[0], str): |
| 58 | for i in range(len(medias)): |
| 59 | media_path = os.path.join(self.data_args.media_dir, medias[i]) |
| 60 | if os.path.isfile(media_path): |
| 61 | medias[i] = media_path |
| 62 | else: |
| 63 | logger.warning_rank0_once( |
| 64 | f"Media {medias[i]} does not exist in `media_dir`. Use original path." |
| 65 | ) |
| 66 | elif isinstance(medias[0], list): # for processed video frames |
| 67 | # medias is a list of lists, e.g., [[frame1.jpg, frame2.jpg], [frame3.jpg, frame4.jpg]] |
| 68 | for i in range(len(medias)): |
| 69 | for j in range(len(medias[i])): |
| 70 | media_path = os.path.join( |
| 71 | self.data_args.media_dir, medias[i][j] |
| 72 | ) |
| 73 | if os.path.isfile(media_path): |
| 74 | medias[i][j] = media_path |
| 75 | else: |
| 76 | logger.warning_rank0_once( |
| 77 | f"Media {medias[i][j]} does not exist in `media_dir`. Use original path." |
| 78 | ) |
| 79 | |
| 80 | return medias |
| 81 | |
| 82 | @abstractmethod |
| 83 | def __call__(self, example: dict[str, Any]) -> dict[str, Any]: |
| 84 | r"""Convert a single example in the dataset to the standard format.""" |
| 85 | ... |
| 86 | |
| 87 | |
| 88 | @dataclass |
| 89 | class AlpacaDatasetConverter(DatasetConverter): |
| 90 | def __call__(self, example: dict[str, Any]) -> dict[str, Any]: |
| 91 | prompt = [] |
| 92 | if self.dataset_attr.history and isinstance( |
| 93 | example[self.dataset_attr.history], list |
| 94 | ): |
| 95 | for old_prompt, old_response in example[self.dataset_attr.history]: |
| 96 | prompt.append({"role": Role.USER.value, "content": old_prompt}) |
| 97 | prompt.append({"role": Role.ASSISTANT.value, "content": old_response}) |
| 98 | |
| 99 | query = [] |
| 100 | if self.dataset_attr.prompt and example[self.dataset_attr.prompt]: |
| 101 | query.append(example[self.dataset_attr.prompt]) |
| 102 | |
| 103 | if self.dataset_attr.query and example[self.dataset_attr.query]: |
| 104 | query.append(example[self.dataset_attr.query]) |
| 105 | |
| 106 | prompt.append( |
| 107 | {"role": Role.USER.value, "content": "\n".join(query)} |
| 108 | ) # "prompt\nquery" |
| 109 | |
| 110 | if self.dataset_attr.response and isinstance( |
| 111 | example[self.dataset_attr.response], str |
| 112 | ): # normal example |
| 113 | response = [ |
| 114 | { |
| 115 | "role": Role.ASSISTANT.value, |
| 116 | "content": example[self.dataset_attr.response], |
| 117 | } |
| 118 | ] |
| 119 | else: # unsupervised |
| 120 | response = [] |
| 121 | |
| 122 | output = { |
| 123 | "_prompt": prompt, |
| 124 | "_response": response, |
| 125 | "_system": ( |
| 126 | example[self.dataset_attr.system] if self.dataset_attr.system else "" |
| 127 | ), |
| 128 | "_point_clouds": ( |
| 129 | self._find_medias(example[self.dataset_attr.point_clouds]) |
| 130 | if self.dataset_attr.point_clouds |
| 131 | else None |
| 132 | ), |
| 133 | } |
| 134 | return output |
| 135 | |
| 136 | |
| 137 | @dataclass |
| 138 | class SharegptDatasetConverter(DatasetConverter): |
| 139 | def __call__(self, example: dict[str, Any]) -> dict[str, Any]: |
| 140 | tag_mapping = { |
| 141 | self.dataset_attr.user_tag: Role.USER.value, |
| 142 | self.dataset_attr.assistant_tag: Role.ASSISTANT.value, |
| 143 | self.dataset_attr.system_tag: Role.SYSTEM.value, |
| 144 | } |
| 145 | odd_tags = (self.dataset_attr.user_tag,) |
| 146 | even_tags = (self.dataset_attr.assistant_tag,) |
| 147 | accept_tags = (odd_tags, even_tags) |
| 148 | messages = example[self.dataset_attr.messages] |
| 149 | if ( |
| 150 | self.dataset_attr.system_tag |
| 151 | and len(messages) != 0 |
| 152 | and messages[0][self.dataset_attr.role_tag] == self.dataset_attr.system_tag |
| 153 | ): |
| 154 | system = messages[0][self.dataset_attr.content_tag] |
| 155 | messages = messages[1:] |
| 156 | else: |
| 157 | system = ( |
| 158 | example[self.dataset_attr.system] if self.dataset_attr.system else "" |
| 159 | ) |
| 160 | |
| 161 | aligned_messages = [] |
| 162 | broken_data = False |
| 163 | for turn_idx, message in enumerate(messages): |
| 164 | if message[self.dataset_attr.role_tag] not in accept_tags[turn_idx % 2]: |
| 165 | logger.warning_rank0(f"Invalid role tag in {messages}.") |
| 166 | broken_data = True |
| 167 | break |
| 168 | |
| 169 | aligned_messages.append( |
| 170 | { |
| 171 | "role": tag_mapping[message[self.dataset_attr.role_tag]], |
| 172 | "content": message[self.dataset_attr.content_tag], |
| 173 | } |
| 174 | ) |
| 175 | |
| 176 | if len(aligned_messages) % 2 != 0: |
| 177 | logger.warning_rank0(f"Invalid message count in {messages}.") |
| 178 | broken_data = True |
| 179 | |
| 180 | if broken_data: |
| 181 | logger.warning_rank0("Skipping this abnormal example.") |
| 182 | prompt, response = [], [] |
| 183 | else: # normal example |
| 184 | prompt = aligned_messages[:-1] |
| 185 | response = aligned_messages[-1:] |
| 186 | |
| 187 | output = { |
| 188 | "_prompt": prompt, |
| 189 | "_response": response, |
| 190 | "_system": system, |
| 191 | "_point_clouds": ( |
| 192 | self._find_medias(example[self.dataset_attr.point_clouds]) |
| 193 | if self.dataset_attr.point_clouds |
| 194 | else None |
| 195 | ), |
| 196 | } |
| 197 | return output |
| 198 | |
| 199 | |
| 200 | DATASET_CONVERTERS = { |
| 201 | "alpaca": AlpacaDatasetConverter, |
| 202 | "sharegpt": SharegptDatasetConverter, |
| 203 | } |
| 204 | |
| 205 | |
| 206 | def register_dataset_converter( |
| 207 | name: str, dataset_converter: type["DatasetConverter"] |
| 208 | ) -> None: |
| 209 | r"""Register a new dataset converter.""" |
| 210 | if name in DATASET_CONVERTERS: |
| 211 | raise ValueError(f"Dataset converter {name} already exists.") |
| 212 | |
| 213 | DATASET_CONVERTERS[name] = dataset_converter |
| 214 | |
| 215 | |
| 216 | def get_dataset_converter( |
| 217 | name: str, dataset_attr: "DatasetAttr", data_args: "DataArguments" |
| 218 | ) -> "DatasetConverter": |
| 219 | r"""Get a dataset converter.""" |
| 220 | if name not in DATASET_CONVERTERS: |
| 221 | raise ValueError(f"Dataset converter {name} not found.") |
| 222 | |
| 223 | return DATASET_CONVERTERS[name](dataset_attr, data_args) |
| 224 | |
| 225 | |
| 226 | def align_dataset( |
| 227 | dataset: Union["Dataset", "IterableDataset"], |
| 228 | dataset_attr: "DatasetAttr", |
| 229 | data_args: "DataArguments", |
| 230 | training_args: "Seq2SeqTrainingArguments", |
| 231 | ) -> Union["Dataset", "IterableDataset"]: |
| 232 | r"""Align the dataset to a specific format. |
| 233 | |
| 234 | Aligned dataset: |
| 235 | _prompt: [{"role": "user", "content": "..."}] * (2T - 1) |
| 236 | _response: [{"role": "assistant", "content": "..."}] * N |
| 237 | _system: "..." |
| 238 | _point_clouds: [] |
| 239 | """ |
| 240 | column_names = list(next(iter(dataset)).keys()) |
| 241 | kwargs = dict( |
| 242 | num_proc=data_args.preprocessing_num_workers, |
| 243 | load_from_cache_file=(not data_args.overwrite_cache) |
| 244 | or (training_args.local_process_index != 0), |
| 245 | desc="Converting format of dataset", |
| 246 | ) |
| 247 | |
| 248 | dataset_converter = get_dataset_converter( |
| 249 | dataset_attr.formatting, dataset_attr, data_args |
| 250 | ) |
| 251 | return dataset.map( |
| 252 | dataset_converter, |
| 253 | batched=False, |
| 254 | remove_columns=column_names, |
| 255 | **kwargs, |
| 256 | ) |