File size: 10,947 Bytes
458260e | 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 | """JSONL ๊ธฐ๋ฐ supervised fine-tuning(SFT) ๋ฐ์ดํฐ ๋ก๋ฉ๊ณผ ๋ฐฐ์น ํจ๋ฉ."""
import json
from dataclasses import dataclass
from pathlib import Path
import torch
from torch.utils.data import Dataset as TorchDataset
from config import SFTConfig
from logger import get_logger
log = get_logger(__name__)
class SFTDataset(TorchDataset):
"""์ด๋ฏธ ํ ํฐํ๋ SFT ์์ . prompt ํ ํฐ์ label์ -100์ผ๋ก ๋ง์คํน๋๋ค."""
def __init__(self, examples: list[dict]):
self.examples = examples
def __len__(self) -> int:
return len(self.examples)
def __getitem__(self, idx: int) -> dict:
example = self.examples[idx]
return {
"input_ids": torch.tensor(example["input_ids"], dtype=torch.long),
"labels": torch.tensor(example["labels"], dtype=torch.long),
}
@dataclass
class SFTDataCollator:
pad_token_id: int
max_seq_length: int
def __call__(self, batch: list[dict]) -> dict:
max_len = min(max(item["input_ids"].size(0) for item in batch), self.max_seq_length)
padded_input_ids, padded_labels, attention_masks = [], [], []
for item in batch:
input_ids = item["input_ids"][:max_len]
labels = item["labels"][:max_len]
pad_len = max_len - input_ids.size(0)
padded_input_ids.append(torch.cat((input_ids, torch.full((pad_len,), self.pad_token_id, dtype=torch.long))))
padded_labels.append(torch.cat((labels, torch.full((pad_len,), -100, dtype=torch.long))))
attention_masks.append(torch.cat((torch.ones(input_ids.size(0), dtype=torch.long), torch.zeros(pad_len, dtype=torch.long))))
return {
"input_ids": torch.stack(padded_input_ids),
"labels": torch.stack(padded_labels),
"attention_mask": torch.stack(attention_masks),
}
def _text(value, field_name: str, line_number: int) -> str:
if not isinstance(value, str) or not value.strip():
raise ValueError(f"line {line_number}: '{field_name}' must be a non-empty string")
return value
def _encode_prompt_completion(tokenizer, prompt: str, completion: str, max_length: int) -> dict | None:
"""์ผ๋ฐ prompt/completion ํ์. completion(EOS ํฌํจ)๋ง loss๋ฅผ ๊ณ์ฐํ๋ค."""
prompt_ids = tokenizer(prompt, add_special_tokens=True)["input_ids"]
completion_ids = tokenizer(completion, add_special_tokens=False)["input_ids"]
if tokenizer.eos_token_id is not None and (not completion_ids or completion_ids[-1] != tokenizer.eos_token_id):
completion_ids.append(tokenizer.eos_token_id)
# ์๋ต์ด ์๋ฆฌ๋ ์์ ๋ ํ์ต ์ ํธ๊ฐ ์์ด์ง๋ฏ๋ก ๋ฒ๋ฆฐ๋ค.
if len(prompt_ids) >= max_length:
return None
input_ids = (prompt_ids + completion_ids)[:max_length]
labels = ([-100] * len(prompt_ids) + completion_ids)[:max_length]
return {"input_ids": input_ids, "labels": labels}
def _messages_to_ids(tokenizer, messages: list) -> list:
"""apply_chat_template ๊ฒฐ๊ณผ๋ฅผ ํญ์ 1์ฐจ์ int ๋ฆฌ์คํธ๋ก ์ ๊ทํํ๋ค."""
# return_dict=True๋ฅผ ๋ช
์ํ์ฌ transformers ๋ฒ์ ์ ์๊ด์์ด
# ํญ์ BatchEncoding(dict ํํ) ๊ฐ์ฒด๋ฅผ ๋ฐํ๋ฐ๋๋ก ๊ฐ์ ํฉ๋๋ค.
encoded = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=False,
return_dict=True
)
# ๋ช
์์ ์ผ๋ก input_ids๋ฅผ ์ถ์ถํฉ๋๋ค.
ids = encoded["input_ids"]
# 2์ฐจ์ ๋ฆฌ์คํธ(๋ฐฐ์น ์ฐจ์ ํฌํจ)๋ก ๋ฐํ๋ ๊ฒฝ์ฐ๋ฅผ ๋๋นํด 1์ฐจ์์ผ๋ก ํ์ด์ค๋๋ค.
if ids and isinstance(ids[0], list):
ids = ids[0]
return ids
def _encode_messages_native(tokenizer, messages: list, max_length: int) -> dict | None:
"""ํ ํฌ๋์ด์ ์ chat_template์ด {% generation %} ๋ธ๋ก(assistant mask)์ ์ง์ํ๋
๊ฒฝ์ฐ์ ์ฐ๋ ๋น ๋ฅธ ๊ฒฝ๋ก.
์ฃผ์: transformers๋ ํ
ํ๋ฆฟ์ด ์ด๋ฅผ ์ง์ํ์ง ์์๋ ์์ธ๋ฅผ ๋์ง์ง ์๊ณ
assistant_masks๋ฅผ ์ ๋ถ 0์ผ๋ก ์ฑ์์ '์กฐ์ฉํ' ๋ฐํํ๋ ๊ฒฝ์ฐ๊ฐ ์๋ค.
์ด ๊ฒฝ์ฐ ์ฌ๊ธฐ์๋ None์ ๋ฐํํด์ ํธ์ถ๋ถ๊ฐ manual ๋ฐฉ์์ผ๋ก ํด๋ฐฑํ๊ฒ ํ๋ค.
(์ด๊ฑธ ๊ฐ์งํ์ง ์์ผ๋ฉด ๋ชจ๋ ์์ ์ label์ด ์ ๋ถ -100์ด ๋์ด
'์ด์ ์์ด ์ ๋ถ skip ๋๋' ํ์์ด ๋ฐ์ํ๋ค.)
"""
encoded = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=False,
return_dict=True,
return_assistant_tokens_mask=True,
truncation=True,
max_length=max_length,
)
input_ids = encoded["input_ids"]
if input_ids and isinstance(input_ids[0], list):
input_ids = input_ids[0]
mask = encoded.get("assistant_masks")
if mask is None:
return None
if mask and isinstance(mask[0], list):
mask = mask[0]
if not any(mask):
# ๋ง์คํฌ๊ฐ ์ ๋ถ 0 โ ํ
ํ๋ฆฟ์ด assistant mask๋ฅผ ์ง์ํ์ง ์๋๋ค๋ ์ ํธ
return None
labels = [token if is_assistant else -100 for token, is_assistant in zip(input_ids, mask)]
return {"input_ids": input_ids, "labels": labels}
def _encode_messages_manual(tokenizer, messages: list, max_length: int) -> dict | None:
"""chat_template์ด assistant mask๋ฅผ ์ง์ํ์ง ์์ ๋ ์ฐ๋ ๋ฒ์ฉ ํด๋ฐฑ.
๋ฉ์์ง๋ฅผ ํ ๊ฐ์ฉ ๋๋ ค๊ฐ๋ฉฐ ๋งค๋ฒ ์ ์ฒด๋ฅผ ๋ค์ ํ ํฐํํ๊ณ , ์ง์ ๊ฒฐ๊ณผ์์
๊ณตํต ์ ๋์ฌ ์ดํ(diff)๋ฅผ '์ด๋ฒ์ ์ถ๊ฐ๋ ํด์ ํ ํฐ'์ผ๋ก ๊ฐ์ฃผํ๋ค.
ํด๋น ํด์ด assistant๋ฉด label๋ก, ์๋๋ฉด -100์ผ๋ก ์ฑ์ด๋ค.
์ด๋ค chat_template์ด๋ (์ฌ์ง์ด {% generation %} ์์ด) ํญ์ ๋์ํ๋ค.
"""
input_ids: list[int] = []
labels: list[int] = []
prev_ids: list[int] = []
for i in range(1, len(messages) + 1):
prefix = messages[:i]
ids = _messages_to_ids(tokenizer, prefix)
common = 0
limit = min(len(prev_ids), len(ids))
while common < limit and prev_ids[common] == ids[common]:
common += 1
new_tokens = ids[common:]
is_assistant = messages[i - 1].get("role") == "assistant"
input_ids = input_ids[:common] + new_tokens
if is_assistant:
labels = labels[:common] + new_tokens
else:
labels = labels[:common] + [-100] * len(new_tokens)
prev_ids = ids
input_ids = input_ids[:max_length]
labels = labels[:max_length]
return None if not any(label != -100 for label in labels) else {"input_ids": input_ids, "labels": labels}
# ํ๋ก์ธ์ค ์ ์ฒด์์ ํ ๋ฒ๋ง ํ๋ณ (True: native ์ฌ์ฉ ๊ฐ๋ฅ / False: manual๋ก ๊ณ ์ / None: ์์ง ๋ฏธํ๋ณ)
_native_mask_supported: bool | None = None
def _encode_messages(tokenizer, messages: list, max_length: int, line_number: int) -> dict | None:
"""chat template์ assistant mask๋ก assistant ๋ฐํ๋ง ์ ๋ต์ผ๋ก ์ง์ ํ๋ค.
native ๋ฐฉ์(๋น ๋ฆ)์ ์ฐ์ ์๋ํ๊ณ , ํ
ํ๋ฆฟ์ด ์ด๋ฅผ ์ง์ํ์ง ์์ผ๋ฉด
์๋์ผ๋ก manual(diff ๊ธฐ๋ฐ) ๋ฐฉ์์ผ๋ก ํด๋ฐฑํ๋ค."""
global _native_mask_supported
if not isinstance(messages, list) or not messages:
raise ValueError(f"line {line_number}: 'messages' must be a non-empty list")
if not any(isinstance(m, dict) and m.get("role") == "assistant" for m in messages):
raise ValueError(f"line {line_number}: messages must contain an assistant response")
if _native_mask_supported is not False:
try:
result = _encode_messages_native(tokenizer, messages, max_length)
except (AttributeError, TypeError, ValueError):
result = None
if result is not None:
_native_mask_supported = True
return result
if _native_mask_supported is None:
log.warning(
"Tokenizer์ chat_template์ด assistant mask(return_assistant_tokens_mask)๋ฅผ "
"์ง์ํ์ง ์๋ ๊ฒ์ผ๋ก ๋ณด์
๋๋ค. ์ดํ ๋ชจ๋ 'messages' ์์ ๋ ์๋์ผ๋ก "
"manual(diff ๊ธฐ๋ฐ) ๋ฐฉ์์ผ๋ก ์ธ์ฝ๋ฉํฉ๋๋ค."
)
_native_mask_supported = False
# ์ด๋ฒ ๋ผ์ธ์ ๋ฐ์ดํฐ ์์ค ์์ด ๋ฐ๋ก manual๋ก ์ธ์ฝ๋ฉ
return _encode_messages_manual(tokenizer, messages, max_length)
return _encode_messages_manual(tokenizer, messages, max_length)
def _record_to_example(record: dict, tokenizer, cfg: SFTConfig, line_number: int) -> dict | None:
if not isinstance(record, dict):
raise ValueError(f"line {line_number}: each JSONL row must be an object")
max_length = cfg.training.max_seq_length
data_format = cfg.data.format
if data_format in ("auto", "messages") and "messages" in record:
return _encode_messages(tokenizer, record["messages"], max_length, line_number)
if data_format in ("auto", "instruction") and "instruction" in record and "output" in record:
instruction = _text(record["instruction"], "instruction", line_number)
user_input = record.get("input", "")
if user_input and not isinstance(user_input, str):
raise ValueError(f"line {line_number}: 'input' must be a string")
prompt = f"### Instruction:\n{instruction}\n\n"
if user_input:
prompt += f"### Input:\n{user_input}\n\n"
prompt += "### Response:\n"
return _encode_prompt_completion(tokenizer, prompt, _text(record["output"], "output", line_number), max_length)
if data_format in ("auto", "prompt_completion") and "prompt" in record and "completion" in record:
return _encode_prompt_completion(
tokenizer,
_text(record["prompt"], "prompt", line_number),
_text(record["completion"], "completion", line_number),
max_length,
)
raise ValueError(
f"line {line_number}: unsupported JSONL schema. Expected messages, "
"instruction/output, or prompt/completion fields."
)
def load_dataset(cfg: SFTConfig, tokenizer) -> SFTDataset:
path = Path(cfg.paths.dataset_path)
examples, skipped = [], 0
with path.open("r", encoding="utf-8") as f:
for line_number, line in enumerate(f, start=1):
if not line.strip():
continue
try:
record = json.loads(line)
except json.JSONDecodeError as exc:
raise ValueError(f"line {line_number}: invalid JSON: {exc.msg}") from exc
example = _record_to_example(record, tokenizer, cfg, line_number)
if example is None:
skipped += 1
else:
examples.append(example)
if not examples:
raise ValueError("No trainable examples were found in the JSONL file.")
log.info("SFT dataset ready | examples=%s | skipped=%s | path=%s", len(examples), skipped, path)
return SFTDataset(examples)
|