Download kawk50m/chat.py from Infinity08/KAWK50M-Project: direct link, hf CLI and curl.
- Browser
- Download file 3.84 kB
-
https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/kawk50m/chat.py
- Command line
-
hf download hf://datasets/Infinity08/KAWK50M-Project/kawk50m/chat.py
-
curl -L -o chat.py https://huggingface.co/datasets/Infinity08/KAWK50M-Project/resolve/main/kawk50m/chat.py
3.84 kB
| from __future__ import annotations | |
| import re | |
| from collections.abc import Iterable, Sequence | |
| from typing import Any | |
| CHATML_BLOCK_RE = re.compile( | |
| r"<\|im_start\|>\s*(system|user|assistant)\s*\n?(.*?)<\|im_end\|>", | |
| re.IGNORECASE | re.DOTALL, | |
| ) | |
| ROLE_HEADERS = { | |
| "system": "### 지침:\n", | |
| "user": "### 사용자:\n", | |
| "assistant": "### 도우미:\n", | |
| } | |
| KOREAN_CHAT_TEMPLATE = """{{ bos_token }}{% for message in messages %}{% if message['role'] == 'system' %}### 지침: | |
| {{ message['content'] }} | |
| {% elif message['role'] == 'user' %}### 사용자: | |
| {{ message['content'] }} | |
| {% elif message['role'] == 'assistant' %}### 도우미: | |
| {{ message['content'] }}{{ eos_token }} | |
| {% endif %}{% endfor %}{% if add_generation_prompt %}### 도우미: | |
| {% endif %}""" | |
| def parse_chatml(text: str) -> list[tuple[str, str]]: | |
| if not isinstance(text, str): | |
| return [] | |
| return [ | |
| (role.casefold(), content.strip()) | |
| for role, content in CHATML_BLOCK_RE.findall(text) | |
| if content.strip() | |
| ] | |
| def format_generation_prompt( | |
| user_text: str, | |
| *, | |
| system_text: str | None = None, | |
| ) -> str: | |
| sections: list[str] = [] | |
| if system_text: | |
| sections.append(ROLE_HEADERS["system"] + system_text.strip()) | |
| sections.append(ROLE_HEADERS["user"] + user_text.strip()) | |
| sections.append(ROLE_HEADERS["assistant"]) | |
| return "\n\n".join(sections) | |
| def _encode(tokenizer: Any, text: str) -> list[int]: | |
| return list( | |
| tokenizer( | |
| text, | |
| add_special_tokens=False, | |
| return_attention_mask=False, | |
| return_token_type_ids=False, | |
| )["input_ids"] | |
| ) | |
| def _encode_context_block( | |
| tokenizer: Any, | |
| role: str, | |
| content: str, | |
| ) -> list[int]: | |
| result = _encode(tokenizer, ROLE_HEADERS[role] + content.strip()) | |
| if role == "assistant": | |
| result.append(int(tokenizer.eos_token_id)) | |
| result.extend(_encode(tokenizer, "\n\n")) | |
| return result | |
| def build_assistant_examples( | |
| blocks: Sequence[tuple[str, str]], | |
| tokenizer: Any, | |
| *, | |
| max_length: int, | |
| min_prompt_tokens: int = 32, | |
| ) -> Iterable[tuple[list[int], list[int]]]: | |
| """Yield one assistant-only-loss example for every assistant turn. | |
| Earlier assistant turns remain masked context. The current assistant response | |
| and its EOS token are supervised. Long prompts are cropped from the left so | |
| the most recent user request and assistant header are retained. | |
| """ | |
| if max_length <= min_prompt_tokens + 2: | |
| raise ValueError("max_length is too small for an SFT example") | |
| if tokenizer.bos_token_id is None or tokenizer.eos_token_id is None: | |
| raise ValueError("Tokenizer must define BOS and EOS token IDs") | |
| context_ids = [int(tokenizer.bos_token_id)] | |
| for role, content in blocks: | |
| if role not in ROLE_HEADERS or not content.strip(): | |
| continue | |
| if role != "assistant": | |
| context_ids.extend(_encode_context_block(tokenizer, role, content)) | |
| continue | |
| assistant_header = _encode(tokenizer, ROLE_HEADERS["assistant"]) | |
| prompt_ids = context_ids + assistant_header | |
| response_ids = _encode(tokenizer, content.strip()) | |
| response_budget = max_length - min_prompt_tokens - 1 | |
| if len(response_ids) > response_budget: | |
| response_ids = response_ids[:response_budget] | |
| target_ids = response_ids + [int(tokenizer.eos_token_id)] | |
| prompt_budget = max_length - len(target_ids) | |
| prompt_tail = prompt_ids[-prompt_budget:] | |
| input_ids = prompt_tail + target_ids | |
| loss_mask = [0] * len(prompt_tail) + [1] * len(target_ids) | |
| if response_ids and len(input_ids) <= max_length: | |
| yield input_ids, loss_mask | |
| context_ids.extend(_encode_context_block(tokenizer, role, content)) | |