sft_qat / dataset_loader.py
starcrow's picture
Upload folder using huggingface_hub
458260e verified
Raw History Blame Contribute Delete
10.9 kB
"""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)