|
| 1 | +"""Cppmega C++ tool-use prompt templates and loss masks.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +from collections.abc import Mapping, Sequence |
| 6 | +from dataclasses import dataclass |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from cppmega_mlx.data.tokenizer_contract import TOOL_USE_SPECIAL_TOKEN_IDS |
| 10 | + |
| 11 | + |
| 12 | +TOOL_USE_SPECIAL_TOKEN_TEXT: dict[str, str] = { |
| 13 | + "bos": "<BOS>", |
| 14 | + "eos": "<EOS>", |
| 15 | + "code_start": "<CODE_START>", |
| 16 | + "code_end": "<CODE_END>", |
| 17 | + "think_start": "<THINK_START>", |
| 18 | + "think_end": "<THINK_END>", |
| 19 | + "query_tool": "<QUERY_TOOL>", |
| 20 | + "tool_result": "<TOOL_RESULT>", |
| 21 | +} |
| 22 | + |
| 23 | +_RESERVED_TOOL_USE_TOKENS = frozenset(TOOL_USE_SPECIAL_TOKEN_TEXT.values()) |
| 24 | + |
| 25 | + |
| 26 | +@dataclass(frozen=True) |
| 27 | +class ToolUseSpecialTokenIds: |
| 28 | + """Stable IDs for the deployed cppmega tool-use tokenizer protocol.""" |
| 29 | + |
| 30 | + bos: int = TOOL_USE_SPECIAL_TOKEN_IDS["BOS"] |
| 31 | + eos: int = TOOL_USE_SPECIAL_TOKEN_IDS["EOS"] |
| 32 | + code_start: int = TOOL_USE_SPECIAL_TOKEN_IDS["CODE_START"] |
| 33 | + code_end: int = TOOL_USE_SPECIAL_TOKEN_IDS["CODE_END"] |
| 34 | + think_start: int = TOOL_USE_SPECIAL_TOKEN_IDS["THINK_START"] |
| 35 | + think_end: int = TOOL_USE_SPECIAL_TOKEN_IDS["THINK_END"] |
| 36 | + query_tool: int = TOOL_USE_SPECIAL_TOKEN_IDS["QUERY_TOOL"] |
| 37 | + tool_result: int = TOOL_USE_SPECIAL_TOKEN_IDS["TOOL_RESULT"] |
| 38 | + |
| 39 | + @classmethod |
| 40 | + def from_mapping(cls, mapping: Mapping[str, int]) -> "ToolUseSpecialTokenIds": |
| 41 | + """Build IDs from a mapping using either canonical or lowercase keys.""" |
| 42 | + |
| 43 | + return cls( |
| 44 | + bos=_lookup_id(mapping, "BOS", "bos"), |
| 45 | + eos=_lookup_id(mapping, "EOS", "EOT", "eos"), |
| 46 | + code_start=_lookup_id(mapping, "CODE_START", "code_start"), |
| 47 | + code_end=_lookup_id(mapping, "CODE_END", "code_end"), |
| 48 | + think_start=_lookup_id(mapping, "THINK_START", "think_start"), |
| 49 | + think_end=_lookup_id(mapping, "THINK_END", "think_end"), |
| 50 | + query_tool=_lookup_id(mapping, "QUERY_TOOL", "query_tool"), |
| 51 | + tool_result=_lookup_id(mapping, "TOOL_RESULT", "tool_result"), |
| 52 | + ) |
| 53 | + |
| 54 | + def as_mapping(self) -> dict[str, int]: |
| 55 | + return { |
| 56 | + "bos": self.bos, |
| 57 | + "eos": self.eos, |
| 58 | + "code_start": self.code_start, |
| 59 | + "code_end": self.code_end, |
| 60 | + "think_start": self.think_start, |
| 61 | + "think_end": self.think_end, |
| 62 | + "query_tool": self.query_tool, |
| 63 | + "tool_result": self.tool_result, |
| 64 | + } |
| 65 | + |
| 66 | + |
| 67 | +@dataclass(frozen=True) |
| 68 | +class ToolUseBlock: |
| 69 | + """One ordered cppmega tool-use turn. |
| 70 | +
|
| 71 | + Fields are rendered in protocol order: model thinking, tool query, injected |
| 72 | + tool result, then final or intermediate code. |
| 73 | + """ |
| 74 | + |
| 75 | + think: str | None = None |
| 76 | + query_tool: str | None = None |
| 77 | + tool_result: str | None = None |
| 78 | + code: str | None = None |
| 79 | + |
| 80 | + |
| 81 | +def render_tool_use_template( |
| 82 | + instruction: str, |
| 83 | + blocks: Sequence[ToolUseBlock] = (), |
| 84 | + *, |
| 85 | + include_bos: bool = True, |
| 86 | + include_eos: bool = True, |
| 87 | + allow_special_tokens: bool = False, |
| 88 | +) -> str: |
| 89 | + """Render cppmega's C++ tool-call protocol as plain text.""" |
| 90 | + |
| 91 | + if not allow_special_tokens: |
| 92 | + _reject_reserved_tokens("instruction", instruction) |
| 93 | + for block_index, block in enumerate(blocks): |
| 94 | + _reject_block_reserved_tokens(block_index, block) |
| 95 | + |
| 96 | + parts: list[str] = [] |
| 97 | + if include_bos: |
| 98 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["bos"]) |
| 99 | + if instruction: |
| 100 | + parts.append(instruction.rstrip("\n")) |
| 101 | + |
| 102 | + for block in blocks: |
| 103 | + _append_block(parts, block) |
| 104 | + |
| 105 | + if include_eos: |
| 106 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["eos"]) |
| 107 | + |
| 108 | + return "\n".join(parts) |
| 109 | + |
| 110 | + |
| 111 | +def encode_tool_use_template( |
| 112 | + tokenizer: Any, |
| 113 | + instruction: str, |
| 114 | + blocks: Sequence[ToolUseBlock] = (), |
| 115 | + *, |
| 116 | + include_bos: bool = True, |
| 117 | + include_eos: bool = True, |
| 118 | + allow_special_tokens: bool = False, |
| 119 | +) -> list[int]: |
| 120 | + """Render and encode with a caller-owned tokenizer.""" |
| 121 | + |
| 122 | + rendered = render_tool_use_template( |
| 123 | + instruction, |
| 124 | + blocks, |
| 125 | + include_bos=include_bos, |
| 126 | + include_eos=include_eos, |
| 127 | + allow_special_tokens=allow_special_tokens, |
| 128 | + ) |
| 129 | + encoded = tokenizer.encode(rendered) |
| 130 | + if not isinstance(encoded, list) or any(isinstance(item, list) for item in encoded): |
| 131 | + raise TypeError("tokenizer.encode(text) must return a flat list[int]") |
| 132 | + if any(not isinstance(item, int) or isinstance(item, bool) for item in encoded): |
| 133 | + raise TypeError("tokenizer.encode(text) must return integer token IDs") |
| 134 | + return encoded |
| 135 | + |
| 136 | + |
| 137 | +def compute_tool_use_loss_mask( |
| 138 | + token_ids: Sequence[int], |
| 139 | + special_ids: ToolUseSpecialTokenIds | Mapping[str, int] | None = None, |
| 140 | +) -> list[int]: |
| 141 | + """Compute next-token loss mask for cppmega tool-use SFT examples.""" |
| 142 | + |
| 143 | + ids = _normalize_special_ids(special_ids) |
| 144 | + response_start_tokens = {ids.think_start, ids.code_start, ids.query_tool} |
| 145 | + mask = [0] * len(token_ids) |
| 146 | + |
| 147 | + response_start = len(token_ids) |
| 148 | + for index, token_id in enumerate(token_ids): |
| 149 | + if int(token_id) in response_start_tokens: |
| 150 | + response_start = index |
| 151 | + break |
| 152 | + |
| 153 | + in_tool_result = False |
| 154 | + for index in range(response_start, len(token_ids)): |
| 155 | + token_id = int(token_ids[index]) |
| 156 | + |
| 157 | + if token_id == ids.bos or token_id == ids.eos: |
| 158 | + mask[index] = 0 |
| 159 | + continue |
| 160 | + |
| 161 | + if token_id == ids.tool_result: |
| 162 | + in_tool_result = True |
| 163 | + mask[index] = 0 |
| 164 | + continue |
| 165 | + |
| 166 | + if in_tool_result: |
| 167 | + if token_id == ids.code_end: |
| 168 | + in_tool_result = False |
| 169 | + mask[index] = 0 |
| 170 | + elif token_id in response_start_tokens: |
| 171 | + in_tool_result = False |
| 172 | + mask[index] = 1 |
| 173 | + else: |
| 174 | + mask[index] = 0 |
| 175 | + continue |
| 176 | + |
| 177 | + mask[index] = 1 |
| 178 | + |
| 179 | + return mask |
| 180 | + |
| 181 | + |
| 182 | +def _append_block(parts: list[str], block: ToolUseBlock) -> None: |
| 183 | + if block.think is not None: |
| 184 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["think_start"]) |
| 185 | + if block.think: |
| 186 | + parts.append(block.think.rstrip("\n")) |
| 187 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["think_end"]) |
| 188 | + |
| 189 | + if block.query_tool is not None: |
| 190 | + query = block.query_tool.strip() |
| 191 | + parts.append(f'{TOOL_USE_SPECIAL_TOKEN_TEXT["query_tool"]} {query} {TOOL_USE_SPECIAL_TOKEN_TEXT["code_end"]}') |
| 192 | + |
| 193 | + if block.tool_result is not None: |
| 194 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["tool_result"]) |
| 195 | + if block.tool_result: |
| 196 | + parts.append(block.tool_result.rstrip("\n")) |
| 197 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["code_end"]) |
| 198 | + |
| 199 | + if block.code is not None: |
| 200 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["code_start"]) |
| 201 | + if block.code: |
| 202 | + parts.append(block.code.rstrip("\n")) |
| 203 | + parts.append(TOOL_USE_SPECIAL_TOKEN_TEXT["code_end"]) |
| 204 | + |
| 205 | + |
| 206 | +def _reject_block_reserved_tokens(block_index: int, block: ToolUseBlock) -> None: |
| 207 | + for field_name in ("think", "query_tool", "tool_result", "code"): |
| 208 | + value = getattr(block, field_name) |
| 209 | + if value is not None: |
| 210 | + _reject_reserved_tokens(f"blocks[{block_index}].{field_name}", value) |
| 211 | + |
| 212 | + |
| 213 | +def _reject_reserved_tokens(field_name: str, value: str) -> None: |
| 214 | + for token in _RESERVED_TOOL_USE_TOKENS: |
| 215 | + if token in value: |
| 216 | + raise ValueError( |
| 217 | + f"{field_name} contains reserved tool-use token {token!r}; " |
| 218 | + "pass allow_special_tokens=True only for trusted preformatted data" |
| 219 | + ) |
| 220 | + |
| 221 | + |
| 222 | +def _normalize_special_ids( |
| 223 | + special_ids: ToolUseSpecialTokenIds | Mapping[str, int] | None, |
| 224 | +) -> ToolUseSpecialTokenIds: |
| 225 | + if special_ids is None: |
| 226 | + return ToolUseSpecialTokenIds() |
| 227 | + if isinstance(special_ids, ToolUseSpecialTokenIds): |
| 228 | + return special_ids |
| 229 | + return ToolUseSpecialTokenIds.from_mapping(special_ids) |
| 230 | + |
| 231 | + |
| 232 | +def _lookup_id(mapping: Mapping[str, int], *keys: str) -> int: |
| 233 | + for key in keys: |
| 234 | + if key in mapping: |
| 235 | + value = mapping[key] |
| 236 | + if isinstance(value, bool) or not isinstance(value, int): |
| 237 | + raise TypeError(f"special token id {key!r} must be an int") |
| 238 | + return value |
| 239 | + raise ValueError(f"missing tool-use special token id for {keys[0]!r}") |
| 240 | + |
| 241 | + |
| 242 | +__all__ = [ |
| 243 | + "TOOL_USE_SPECIAL_TOKEN_TEXT", |
| 244 | + "ToolUseBlock", |
| 245 | + "ToolUseSpecialTokenIds", |
| 246 | + "compute_tool_use_loss_mask", |
| 247 | + "encode_tool_use_template", |
| 248 | + "render_tool_use_template", |
| 249 | +] |
0 commit comments