#!/usr/bin/env python3 """학습과 평가가 **똑같은** 대화 형식을 쓰도록 한 곳에 모아둔다. 왜 공통 모듈로 빼는가: 학습 때와 추론 때 프롬프트 형식이 조금이라도 다르면 성능이 떨어지는데, 에러가 나지 않아서 원인을 찾기 어렵다. 양쪽에 같은 코드를 복사해두면 한쪽만 고쳐지는 순간 그 사고가 난다. 한 곳에서 가져다 쓰면 어긋날 수 없다. (docs/05_design_notes.md N-002) """ def detect_system_support(tok) -> bool: """이 토크나이저의 chat template이 system 롤을 받는지 실제로 시험한다. Gemma 계열은 버전에 따라 system 롤을 따로 두지 않는다. 모델 카드를 읽고 하드코딩하면 모델을 바꿀 때마다 다시 확인해야 하므로, 런타임에 물어본다. (N-003) """ try: tok.apply_chat_template( [{"role": "system", "content": "x"}, {"role": "user", "content": "y"}], add_generation_prompt=True, tokenize=False, ) return True except Exception: return False def build_user_turn(record: dict, system: str | None, supports_system: bool) -> tuple[list, str]: """학습쌍 하나를 (메시지 리스트, 정답) 으로 만든다. instruction 과 input 을 빈 줄 하나로 잇는다. 데이터의 input 은 상담 전문· 문서 본문처럼 긴 덩어리라, 지시문과 붙여 두면 경계가 흐려진다. """ user = record["instruction"] if record.get("input"): user += "\n\n" + record["input"] msgs = [] if system: if supports_system: msgs.append({"role": "system", "content": system}) else: user = system + "\n\n" + user msgs.append({"role": "user", "content": user}) return msgs, record.get("output", "") def derive_answer_suffix(tok) -> str: """정답 뒤에 붙는 턴 종료 표시를 **템플릿에서 뽑아낸다.** `\\n` 같은 토큰을 코드에 적어두면 모델이 바뀔 때 조용히 어긋난다(N-002). 표식(sentinel)을 정답 자리에 넣어 렌더링한 뒤, 그 뒤에 남는 문자열을 가져온다. """ sentinel = "<<>>" rendered = tok.apply_chat_template( [{"role": "user", "content": "x"}, {"role": "assistant", "content": sentinel}], add_generation_prompt=False, tokenize=False, ) return rendered.split(sentinel)[-1] def build_prompt_and_full(tok, msgs, answer, answer_suffix) -> tuple[str, str]: """학습에 쓸 (프롬프트, 프롬프트+정답) 문자열을 만든다. ⚠️ Gemma 4 특유의 문제 때문에 이렇게 한다. 이 모델의 **생성 프롬프트는 빈 사고(thought) 채널을 여닫은 뒤 끝난다**: <|turn>model\\n<|channel>thought\\n 그런데 템플릿에 정답까지 넣어 렌더링하면 사고 채널이 **아예 빠진다**: <|turn>model\\n답변\\n 즉 템플릿이 만드는 학습용 문자열과 추론 시 실제 입력이 서로 다르다. (`reasoning_content=""` 를 줘도 채널이 나오지 않고, 값을 주면 그 내용이 들어간다) 그대로 두면 **학습 때 본 적 없는 형태를 추론 때 만나게 된다.** 그래서 학습 문자열을 '추론과 똑같은 생성 프롬프트' 뒤에 정답을 이어 붙여 만든다. 이렇게 하면 프롬프트가 전체의 접두사가 되어 손실 마스킹도 정확해진다. """ prompt = tok.apply_chat_template(msgs, add_generation_prompt=True, tokenize=False) return prompt, prompt + answer + answer_suffix def encode_no_special(tok, text) -> list[int]: """chat template 결과를 토큰화한다. `add_special_tokens=False` 인 이유: 템플릿 문자열에 이미 `` 가 들어 있다. 기본값(True)으로 두면 `` 가 두 번 붙는다. 또한 `apply_chat_template(..., tokenize=True)` 를 쓰지 않는 이유: transformers 5.x 에서 이 함수는 리스트가 아니라 **BatchEncoding(dict)** 을 돌려준다. `len()` 이 토큰 수가 아니라 키 개수(2)가 되어, 길이 비교와 슬라이싱이 조용히 잘못된다. """ return tok(text, add_special_tokens=False)["input_ids"]