File size: 13,825 Bytes
f8f0e4e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
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
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
import json
import os
import re
from pathlib import Path
from typing import Any, Dict, Iterable, Optional, Tuple

from datasets import Dataset, DatasetDict, load_dataset, load_from_disk

from utils import SYSTEM_PROMPT


_LOCAL_DATASET_LOADERS = {
    ".json": "json",
    ".jsonl": "json",
    ".csv": "csv",
    ".parquet": "parquet",
}


def load_sft_dataset(
    dataset_name: str,
    dataset_sub_name: str = "",
    split: str = "train",
    default_system_prompt: str = SYSTEM_PROMPT,
) -> Dataset:
    dataset = load_dataset_split(dataset_name, dataset_sub_name=dataset_sub_name, split=split)
    return dataset.map(
        lambda example: normalize_sft_example(example, default_system_prompt=default_system_prompt),
        remove_columns=dataset.column_names,
    )


def load_preference_dataset(
    dataset_name: str,
    dataset_sub_name: str = "",
    split: str = "train",
    default_system_prompt: str = SYSTEM_PROMPT,
) -> Dataset:
    dataset = load_dataset_split(dataset_name, dataset_sub_name=dataset_sub_name, split=split)
    return dataset.map(
        lambda example: normalize_preference_example(example, default_system_prompt=default_system_prompt),
        remove_columns=dataset.column_names,
    )


def load_prompt_dataset(
    dataset_name: str,
    dataset_sub_name: str = "",
    split: str = "train",
    default_system_prompt: str = SYSTEM_PROMPT,
) -> Dataset:
    dataset = load_dataset_split(dataset_name, dataset_sub_name=dataset_sub_name, split=split)
    return dataset.map(
        lambda example: normalize_prompt_example(example, default_system_prompt=default_system_prompt),
        remove_columns=dataset.column_names,
    )


def load_dataset_split(dataset_name: str, dataset_sub_name: str = "", split: str = "train") -> Dataset:
    expanded_name = os.path.expanduser(dataset_name)
    if os.path.exists(expanded_name):
        dataset = _load_local_dataset(Path(expanded_name), split=split)
        return _select_split(dataset, split)

    if dataset_sub_name:
        return load_dataset(dataset_name, dataset_sub_name, split=split)
    return load_dataset(dataset_name, split=split)


def normalize_sft_example(example: Dict[str, Any], default_system_prompt: str = SYSTEM_PROMPT) -> Dict[str, str]:
    if "messages" in example or "conversations" in example:
        messages = _coerce_messages(example.get("messages", example.get("conversations")))
        if messages:
            system_prompt, prompt, response = _messages_to_sft_fields(messages, default_system_prompt)
            return {
                "system": system_prompt,
                "prompt": prompt,
                "response": response,
            }

    prompt = _get_first_value(example, ("prompt", "question"))
    response = _get_first_value(example, ("response", "answer", "output", "completion"))

    if prompt is None and "instruction" in example and "output" in example:
        prompt = " ".join(
            part for part in (_stringify_text(example["instruction"]), _stringify_text(example.get("input"))) if part
        )
        response = _stringify_text(example["output"])

    if prompt is None or response is None:
        raise ValueError(
            "Unsupported SFT dataset schema. Expected prompt/response, question/answer, instruction/output, "
            f"or messages. Found columns: {sorted(example.keys())}"
        )

    return {
        "system": _extract_system_prompt(example, default_system_prompt),
        "prompt": _stringify_text(prompt),
        "response": _stringify_text(response),
    }


def normalize_preference_example(
    example: Dict[str, Any],
    default_system_prompt: str = SYSTEM_PROMPT,
) -> Dict[str, str]:
    if {"chosen", "rejected"}.issubset(example.keys()) and "prompt" not in example and "question" not in example:
        system_prompt, prompt, chosen = _extract_hh_prompt_and_response(
            _stringify_text(example["chosen"]),
            default_system_prompt=default_system_prompt,
        )
        _, rejected_prompt, rejected = _extract_hh_prompt_and_response(
            _stringify_text(example["rejected"]),
            default_system_prompt=default_system_prompt,
        )
        prompt = prompt or rejected_prompt
        return {
            "system": system_prompt,
            "prompt": prompt,
            "chosen": chosen,
            "rejected": rejected,
        }

    if {
        "prompt",
        "response_0",
        "response_1",
        "better_response_id",
    }.issubset(example.keys()):
        chosen, rejected = _select_pairwise_responses(example)
        return {
            "system": _extract_system_prompt(example, default_system_prompt),
            "prompt": _stringify_text(example["prompt"]),
            "chosen": chosen,
            "rejected": rejected,
        }

    prompt = _get_first_value(example, ("prompt", "question"))
    chosen = _get_first_value(example, ("chosen", "response_chosen", "preferred"))
    rejected = _get_first_value(example, ("rejected", "response_rejected", "dispreferred"))

    if prompt is None or chosen is None or rejected is None:
        raise ValueError(
            "Unsupported preference dataset schema. Expected prompt/chosen/rejected, "
            "question/response_chosen/response_rejected, SafeRLHF columns, or HH-RLHF chosen/rejected. "
            f"Found columns: {sorted(example.keys())}"
        )

    return {
        "system": _extract_system_prompt(example, default_system_prompt),
        "prompt": _stringify_text(prompt),
        "chosen": _stringify_text(chosen),
        "rejected": _stringify_text(rejected),
    }


def normalize_prompt_example(example: Dict[str, Any], default_system_prompt: str = SYSTEM_PROMPT) -> Dict[str, str]:
    if "messages" in example or "conversations" in example:
        messages = _coerce_messages(example.get("messages", example.get("conversations")))
        if messages:
            system_prompt, prompt, _ = _messages_to_sft_fields(messages, default_system_prompt)
            return {
                "system": system_prompt,
                "prompt": prompt,
            }

    if {
        "chosen",
        "rejected",
    }.issubset(example.keys()) and "prompt" not in example and "question" not in example:
        system_prompt, prompt, _ = _extract_hh_prompt_and_response(
            _stringify_text(example["chosen"]),
            default_system_prompt=default_system_prompt,
        )
        return {
            "system": system_prompt,
            "prompt": prompt,
        }

    prompt = _get_first_value(example, ("prompt", "question"))
    if prompt is None and "instruction" in example:
        prompt = " ".join(
            part for part in (_stringify_text(example["instruction"]), _stringify_text(example.get("input"))) if part
        )

    if prompt is None:
        raise ValueError(
            "Unsupported prompt dataset schema. Expected prompt/question/instruction, messages, or HH-RLHF chosen. "
            f"Found columns: {sorted(example.keys())}"
        )

    return {
        "system": _extract_system_prompt(example, default_system_prompt),
        "prompt": _stringify_text(prompt),
    }


def _load_local_dataset(dataset_path: Path, split: str):
    if dataset_path.is_file():
        loader_name = _loader_name_from_suffix(dataset_path.suffix)
        return load_dataset(loader_name, data_files={split: str(dataset_path)})

    try:
        return load_from_disk(str(dataset_path))
    except (FileNotFoundError, ValueError):
        data_file = _discover_local_data_file(dataset_path, split=split)
        loader_name = _loader_name_from_suffix(data_file.suffix)
        return load_dataset(loader_name, data_files={split: str(data_file)})


def _select_split(dataset, split: str) -> Dataset:
    if isinstance(dataset, DatasetDict):
        if split in dataset:
            return dataset[split]
        first_split = next(iter(dataset.keys()))
        return dataset[first_split]
    return dataset


def _discover_local_data_file(dataset_dir: Path, split: str) -> Path:
    for suffix in _LOCAL_DATASET_LOADERS:
        candidate = dataset_dir / f"{split}{suffix}"
        if candidate.exists():
            return candidate

    candidates = []
    for suffix in _LOCAL_DATASET_LOADERS:
        candidates.extend(sorted(dataset_dir.glob(f"*{suffix}")))

    if len(candidates) == 1:
        return candidates[0]

    raise ValueError(
        f"Could not infer dataset file under {dataset_dir}. "
        f"Expected {split}.jsonl/.json/.csv/.parquet or exactly one supported file."
    )


def _loader_name_from_suffix(suffix: str) -> str:
    if suffix not in _LOCAL_DATASET_LOADERS:
        raise ValueError(f"Unsupported local dataset format: {suffix}")
    return _LOCAL_DATASET_LOADERS[suffix]


def _extract_system_prompt(example: Dict[str, Any], default_system_prompt: str) -> str:
    system_prompt = _get_first_value(example, ("system", "system_prompt", "system_message"))
    system_prompt = _stringify_text(system_prompt)
    return system_prompt or default_system_prompt


def _get_first_value(example: Dict[str, Any], keys: Iterable[str]):
    for key in keys:
        if key in example and example[key] is not None:
            return example[key]
    return None


def _stringify_text(value: Any) -> str:
    if value is None:
        return ""
    if isinstance(value, str):
        return value.strip()
    if isinstance(value, list):
        parts = [_stringify_text(item) for item in value]
        return "\n".join(part for part in parts if part).strip()
    if isinstance(value, dict):
        text_value = value.get("text")
        if text_value is not None:
            return _stringify_text(text_value)
        content_value = value.get("content")
        if content_value is not None:
            return _stringify_text(content_value)
        return json.dumps(value, ensure_ascii=False, sort_keys=True)
    return str(value).strip()


def _coerce_messages(raw_messages: Any):
    if raw_messages is None:
        return None
    if isinstance(raw_messages, str):
        raw_messages = json.loads(raw_messages)
    if not isinstance(raw_messages, list):
        raise ValueError(f"Unsupported messages payload: {type(raw_messages)}")
    return raw_messages


def _messages_to_sft_fields(messages, default_system_prompt: str) -> Tuple[str, str, str]:
    if not messages:
        raise ValueError("Empty messages payload.")

    assistant_indexes = [
        index for index, message in enumerate(messages) if _normalize_role(message.get("role", message.get("from"))) == "assistant"
    ]
    if not assistant_indexes:
        raise ValueError("messages must contain at least one assistant turn.")

    final_assistant_index = assistant_indexes[-1]
    system_parts = []
    prompt_lines = []
    response = ""

    for index, message in enumerate(messages):
        role = _normalize_role(message.get("role", message.get("from", message.get("speaker"))))
        content = _stringify_text(message.get("content", message.get("value", message.get("text"))))
        if not content:
            continue
        if role == "system":
            system_parts.append(content)
            continue
        if index == final_assistant_index:
            response = content
            continue
        prompt_lines.append(f"{_render_role(role)}: {content}")

    if not response:
        raise ValueError("The final assistant turn is empty.")

    system_prompt = "\n".join(system_parts).strip() or default_system_prompt
    prompt = "\n".join(prompt_lines).strip()
    return system_prompt, prompt, response


def _normalize_role(role: Optional[str]) -> str:
    normalized_role = (role or "").strip().lower()
    role_map = {
        "human": "user",
        "user": "user",
        "assistant": "assistant",
        "gpt": "assistant",
        "bot": "assistant",
        "system": "system",
        "tool": "tool",
        "function": "tool",
    }
    return role_map.get(normalized_role, normalized_role or "user")


def _render_role(role: str) -> str:
    label_map = {
        "user": "User",
        "assistant": "Assistant",
        "tool": "Tool",
    }
    return label_map.get(role, role.title())


def _extract_hh_prompt_and_response(text: str, default_system_prompt: str) -> Tuple[str, str, str]:
    cleaned_text = text.lstrip()
    chunks = re.split(r"\n\nAssistant:", cleaned_text)
    if len(chunks) < 2:
        raise ValueError("Invalid HH-RLHF transcript: missing assistant response.")

    prompt_part = "\n\nAssistant:".join(chunks[:-1]).strip()
    response = chunks[-1].strip()
    prompt_lines = []
    for block in re.split(r"\n\n", prompt_part):
        current_block = block.strip()
        if current_block.startswith("Human:"):
            prompt_lines.append(f"User: {current_block[len('Human:'):].strip()}")
        elif current_block.startswith("Assistant:"):
            prompt_lines.append(f"Assistant: {current_block[len('Assistant:'):].strip()}")

    return default_system_prompt, "\n".join(prompt_lines).strip(), response


def _select_pairwise_responses(example: Dict[str, Any]) -> Tuple[str, str]:
    response_0 = _stringify_text(example["response_0"])
    response_1 = _stringify_text(example["response_1"])
    better_id = int(example["better_response_id"])

    if {
        "is_response_0_safe",
        "is_response_1_safe",
    }.issubset(example.keys()):
        response_0_safe = bool(example["is_response_0_safe"])
        response_1_safe = bool(example["is_response_1_safe"])
        if response_0_safe and not response_1_safe:
            return response_0, response_1
        if response_1_safe and not response_0_safe:
            return response_1, response_0

    if better_id == 0:
        return response_0, response_1
    return response_1, response_0