"""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)