"""Qwen4 chat protocol encoder. Input : OpenAI-compatible messages (+ optional ``tools``). Output : an ordered list of ``EncodeSegment`` -- each a chunk of text tagged with ``allow_special``. Concatenating the segment texts yields the string; tokenizing each segment with its own ``allow_special`` flag yields the training token ids with exact control-token control. Why segments instead of a flat string + ``allowed_special="all"``? Only protocol delimiters use ``allow_special=True``; data cannot inject control tokens. The module has no hard dependency on the tokenizer: segment construction is pure Python. Tokenization is done lazily through any object exposing ``tokenize_segment(text, allow_special=bool)`` (see ``tokenization_qwen4.Qwen4Tokenizer``). """ from __future__ import annotations import copy import json import re from collections.abc import Iterable from dataclasses import dataclass from typing import Any, ClassVar, Literal, Protocol, TypeAlias, runtime_checkable # PUBLIC API (stable). # # Construct: # enc = Qwen4ChatEncoder(tokenizer) # # Encode (OpenAI-compatible messages + tools -> ...): # enc.encode(msgs, tools, *, add_generation_prompt=False) # -> list[EncodeSegment] # the IR # enc.render_tokens(msgs, tools, **opts) -> list[int] # for inference # enc.render_tokens_and_labels(msgs, tools, **opts) -> (ids, labels) # for training # enc.render_string(msgs, tools, **opts) -> str # for debug # # From the IR (when you already hold segments, e.g. after inspection): # enc.to_tokens(segments) -> list[int] # enc.to_tokens_and_labels(segments) -> (ids, labels) # # Parse an assistant body: # parse_assistant_response_ids(token_ids, tokenizer) # -> {reasoning_content, content, tool_calls} # # Labels use IGNORE_INDEX on non-trainable (context) tokens. # The tokenizer is any object satisfying `TokenizerProtocol`. __all__ = [ "IGNORE_INDEX", "EncodeSegment", "Qwen4ChatEncoder", "TokenizerProtocol", "parse_assistant_response_ids", ] # canonical control-token strings IM_START = "<|im_start|>" IM_END = "<|im_end|>" TOOL_CALL_O, TOOL_CALL_C = "", "" TOOL_RESP_O, TOOL_RESP_C = "", "" # no longer in use THINK_O, THINK_C = "", "" # vision / audio delimiters VISION_START, VISION_END, IMAGE_PAD, VIDEO_PAD = ( "<|vision_start|>", "<|vision_end|>", "<|image_pad|>", "<|video_pad|>", ) AUDIO_START, AUDIO_END, AUDIO_PAD = "<|audio_start|>", "<|audio_end|>", "<|audio_pad|>" IGNORE_INDEX = -100 # this is used in pytorch by default @runtime_checkable class TokenizerProtocol(Protocol): """Contract the encoder needs from a tokenizer. `allow_special=True` -> recognize special-token strings (scaffolding). `allow_special=False` -> encode ordinarily; special-looking substrings stay plain bytes and are never treated as control tokens. (`tokenization_qwen4.Qwen4Tokenizer` satisfies this.) """ def tokenize_segment( self, text: str, *, allow_special: bool = False ) -> list[int]: ... def decode(self, token_ids: int | list[int], **kwargs) -> str: ... ReasoningEffortType: TypeAlias = ( Literal["xhigh", "high", "low", "off"] | None ) # allowd reasoning effort values @dataclass class EncodeSegment: """One contiguous chunk of the rendered conversation. text : the raw string. allow_special: recognize control tokens; False for data. trainable : whether these tokens contribute to the training loss. tag : provenance label, for debugging / visualization. """ text: str allow_special: bool trainable: bool = False tag: str = "" def __repr__(self) -> str: flag = "S" if self.allow_special else "." tr = "T" if self.trainable else "." return f"Seg[{flag}{tr} {self.tag}]{self.text!r}" class Qwen4ChatEncoder: DEFAULT_TOOL_SYSTEM = "" # default empty message SUPPORTED_ROLES = ("system", "user", "assistant", "tool") SUPPORTED_REASONING_EFFORTS = ("xhigh", "high", "low", "off") REASONING_INSTRUCTIONS: ClassVar[dict[ReasoningEffortType, str]] = { effort_level: f"Reasoning effort is set to {effort_level}." for effort_level in SUPPORTED_REASONING_EFFORTS } # (enable_thinking, reasoning_effort) -> effective_reasoning_effort THINKING_MAPPING: ClassVar[ dict[ tuple[bool | None, ReasoningEffortType], ReasoningEffortType | None, ] ] = { (None, None): "high", (None, "off"): "off", (None, "low"): "low", (None, "high"): "high", (None, "xhigh"): "xhigh", (False, None): "off", (False, "off"): "off", (False, "low"): None, (False, "high"): None, (False, "xhigh"): None, (True, None): "high", (True, "off"): None, (True, "low"): "low", (True, "high"): "high", (True, "xhigh"): "xhigh", } def __init__( self, tokenizer: TokenizerProtocol, ): """ tokenizer: object with ``tokenize_segment(text, allow_special=bool)``. Assistant bodies (including tool calls) and closing ``<|im_end|>`` are trainable, except for prefilled think tags; all other segments are masked. """ self.tok = tokenizer self.strict_arguments = ( True # raise on un-parseable tool arguments instead of silently degrading ) self.reorder_tool_results = ( True # reorder tool response to match tool call ids if tool call ids exist ) @classmethod def normalize_thinking_controls( cls, enable_thinking: bool | None = None, reasoning_effort: ReasoningEffortType = "high", ) -> ReasoningEffortType: """Validate and normalize the thinking control values.""" if enable_thinking is not None and not isinstance(enable_thinking, bool): raise ValueError( f"unsupported enable_thinking value: {enable_thinking!r}, expected True, False, or None" ) if ( reasoning_effort is not None and reasoning_effort not in cls.SUPPORTED_REASONING_EFFORTS ): raise ValueError( f"unsupported reasoning_effort value: {reasoning_effort!r}, expected one of {cls.SUPPORTED_REASONING_EFFORTS}" ) effective_reasoning_effort = cls.THINKING_MAPPING.get( (enable_thinking, reasoning_effort), None ) if effective_reasoning_effort is None: raise ValueError( f"conflict thinking settings: {enable_thinking=} {reasoning_effort=} " ) return effective_reasoning_effort def normalize_messages( self, messages: list[dict], *, preserve_thinking: bool | None = True, ) -> list[dict]: """Return the message view shared by rendering and media extraction. Apply reasoning/role normalization, then align tool results. The input is not mutated; nested content may be shared. Prompt-only system instructions and generation prefixes are not added. """ if preserve_thinking is not None and not isinstance(preserve_thinking, bool): raise ValueError( f"unsupported preserve_thinking value: {preserve_thinking!r}, expected True, False, or None" ) if preserve_thinking is None: preserve_thinking = True msgs = copy.deepcopy(messages) for m in msgs: # `developer` role is rendered as a system turn if m.get("role") == "developer": m["role"] = "system" if m["role"] not in self.SUPPORTED_ROLES: raise ValueError( f"unsupported message role: {m['role']!r}, expected {self.SUPPORTED_ROLES}" ) # reasoning content could be passed as `reasoning` if "reasoning_content" not in m and "reasoning" in m: m["reasoning_content"] = m["reasoning"] del m["reasoning"] if not preserve_thinking: # A tool or system message does not begin a new user task. With no user turn, # retain all reasoning rather than guessing a history boundary. last_user = next( ( i for i in range(len(msgs) - 1, -1, -1) if msgs[i].get("role") == "user" ), -1, ) for i, m in enumerate(msgs): if i < last_user and m.get("role") == "assistant": m["reasoning_content"] = [] if self.reorder_tool_results: msgs = self._reorder_tool_results(msgs) return msgs def encode( self, messages: list[dict], tools: list[dict] | None = None, *, add_generation_prompt: bool = False, enable_thinking: bool | None = None, reasoning_effort: ReasoningEffortType = None, preserve_thinking: bool | None = True, ) -> list[EncodeSegment]: """Build the segment list for a whole conversation.""" reasoning_effort = self.normalize_thinking_controls( enable_thinking, reasoning_effort ) msgs = self.normalize_messages(messages, preserve_thinking=preserve_thinking) segs: list[EncodeSegment] = [] tools_norm = self._normalize_tools(tools) # reasoning effort instructions in system messages effort_instructions = self.REASONING_INSTRUCTIONS.get(reasoning_effort) if effort_instructions is not None: msgs.insert(0, {"role": "system", "content": effort_instructions}) # decide where tools go, synthesising a leading system turn if needed. tools_target = None if tools_norm: if msgs and msgs[0].get("role") == "system": tools_target = 0 else: msgs.insert(0, {"role": "system", "content": self.DEFAULT_TOOL_SYSTEM}) tools_target = 0 for i, m in enumerate(msgs): role = m.get("role") if role == "system": self._render_system( segs, m, tools_norm if i == tools_target else None, ) elif role == "user": self._render_user(segs, m) elif role == "assistant": self._render_assistant(segs, m, thinking_off=reasoning_effort == "off") elif role == "tool": self._render_tool(segs, m) else: # this is already checked in normalize_messages; kept here since no harm raise ValueError( f"unsupported message role: {role!r}, expected {self.SUPPORTED_ROLES}" ) if add_generation_prompt: self._sp(segs, f"{IM_START}assistant\n", "gen", trainable=False) # Adaptive mode: the next token may be (no reasoning) or # ordinary reasoning content. With thinking off (reasoning_effort == # "off"), pre-fill the empty think block. There is deliberately no # padding newline. self._sp(segs, THINK_O, "gen", trainable=False) if reasoning_effort == "off": self._sp(segs, THINK_C, "gen", trainable=False) return segs def render_string(self, messages, tools=None, **kw) -> str: """messages -> rendered string""" return "".join(s.text for s in self.encode(messages, tools, **kw)) def to_tokens(self, segments: list[EncodeSegment]) -> list[int]: """segments -> token ids""" ids: list[int] = [] for s in segments: ids.extend(self.tok.tokenize_segment(s.text, allow_special=s.allow_special)) return ids def to_tokens_and_labels( self, segments: list[EncodeSegment] ) -> tuple[list[int], list[int]]: """segments -> (token ids, label token ids) with IGNORE_INDEX on non-trainable tokens""" ids: list[int] = [] labels: list[int] = [] for s in segments: toks = self.tok.tokenize_segment(s.text, allow_special=s.allow_special) ids.extend(toks) labels.extend(toks if s.trainable else [IGNORE_INDEX] * len(toks)) return ids, labels def render_tokens(self, messages, tools=None, **kw) -> list[int]: """messages -> token ids""" return self.to_tokens(self.encode(messages, tools, **kw)) def render_tokens_and_labels( self, messages, tools=None, **kw ) -> tuple[list[int], list[int]]: """messages -> (token ids, label token ids) with IGNORE_INDEX on non-trainable tokens""" return self.to_tokens_and_labels(self.encode(messages, tools, **kw)) def _sp(self, segs, text, tag, trainable=False): """scaffolding (special tokens recognized).""" if not text: return segs.append( EncodeSegment(text, allow_special=True, trainable=trainable, tag=tag) ) def _dt(self, segs, text, tag, trainable=False): """data (special tokens NOT recognized -> anti-injection).""" if not text: return segs.append( EncodeSegment(text, allow_special=False, trainable=trainable, tag=tag) ) def _render_system(self, segs, m, tools_norm): self._sp(segs, f"{IM_START}system\n", "sys/role") content = m.get("content") content_segs: list[EncodeSegment] = [] self._render_content(content_segs, content, "sys/content", trainable=False) segs.extend(content_segs) if tools_norm: # Zero-text cache anchors must not introduce a separator. if any(s.text for s in content_segs): self._sp(segs, "\n\n", "sys/sep") self._render_tools_block(segs, tools_norm) self._sp(segs, f"{IM_END}\n", "sys/role") def _render_user(self, segs, m): self._sp(segs, f"{IM_START}user\n", "user/role") self._render_content(segs, m.get("content"), "user/content", trainable=False) self._sp(segs, f"{IM_END}\n", "user/role") def _render_tool(self, segs, m): self._sp(segs, f"{IM_START}tool\n", "tool/role") self._render_content(segs, m.get("content"), "tool/content", trainable=False) # Association IDs and legacy wrappers are not rendered. self._sp(segs, f"\n{IM_END}\n", "tool/role") def _render_assistant(self, segs, m, *, thinking_off=False): self._sp(segs, f"{IM_START}assistant\n", "asst/role", trainable=False) content = m.get("content") reasoning = m.get("reasoning_content") tool_calls = m.get("tool_calls") or [] # render the content block (text and/or images) into its own segment list content_block: list[EncodeSegment] = [] self._render_content(content_block, content, "asst/content", trainable=True) # Canonicalize only the outer data-text boundaries of the content field, # stopping at the first media/control segment. Generation-time trailing # or leading whitespace on a historical turn would otherwise re-encode to # a different token run and drift the prefix the cache keyed on. # Internal whitespace, media and tool arguments are untouched. Emptied # segments are kept: there may be cache boundary/breakpoint flags which still # describe real content-part boundaries at the trimmed offsets. for segment in content_block: if not segment.text: continue if segment.allow_special: break segment.text = segment.text.lstrip() if segment.text: break for segment in reversed(content_block): if not segment.text: continue if segment.allow_special: break segment.text = segment.text.rstrip() if segment.text: break # Every historical assistant turn has exactly one tight think block. # Empty reasoning is ````. Normalize the reasoning's outer # whitespace just as for content, so the think block is stable across # re-encodes of the same history. reasoning_text = self._reasoning_to_text(reasoning).strip() # Match compat's generation region: prefilled think tags carry no loss. self._sp(segs, THINK_O, "asst/think", trainable=False) self._dt( segs, reasoning_text, "asst/think", trainable=True, ) self._sp( segs, THINK_C, "asst/think", trainable=not (thinking_off and not reasoning_text), ) # Append calls directly after the normalized content. Internal content # whitespace and tool-argument values remain unchanged. if content_block: segs.extend(content_block) for tc in tool_calls: segs.extend(self._tool_call_segments(tc, trainable=True)) self._sp(segs, IM_END, "asst/role", trainable=True) self._sp(segs, "\n", "asst/role", trainable=False) def _tool_call_segments(self, tc: dict, *, trainable: bool) -> list[EncodeSegment]: name, arguments = self._tc_fields(tc) pairs = self._normalize_arguments(arguments) # TOOL_CALL_O / TOOL_CALL_C are real control tokens and therefore hard # tokenizer boundaries. Everything between them is ordinary XML-ish text. # Keep that whole body in one data segment so its token IDs are exactly # those obtained by continuously tokenizing the rendered text. Splitting # ```` into separate data segments creates # impossible-to-reproduce BPE boundaries, e.g. ``=`` + ``bash`` instead # of ``=b`` + ``ash`` for ````. # Tool call content is ordinary data without protocol-level anti-injection. body = ["\n"] for k, v in pairs: body.extend( ( "\n", self._as_text(v), "\n\n", ) ) body.append("\n") return [ EncodeSegment(f"{TOOL_CALL_O}\n", True, trainable, "tc/open"), EncodeSegment("".join(body), False, trainable, "tc/body"), EncodeSegment(TOOL_CALL_C, True, trainable, "tc/close"), ] @staticmethod def _tool_call_id_index(tool_calls: Any) -> dict[str, tuple[int, Any]]: """Map opaque call ids to rendered position and function name. Every list entry advances the 1-based position, malformed/id-less entries are skipped, and duplicate ids retain their first occurrence. """ index: dict[str, tuple[int, Any]] = {} if not isinstance(tool_calls, list): return index for position, tool_call in enumerate(tool_calls, start=1): if not isinstance(tool_call, dict): continue call_id = tool_call.get("id") if call_id is None: continue key = str(call_id) if key in index: continue function = tool_call.get("function") name = ( function.get("name") if isinstance(function, dict) else tool_call.get("name") ) index[key] = (position, name) return index def _reorder_tool_results(self, messages: list[dict]) -> list[dict]: """Reorder each run of consecutive ``tool`` messages to match the preceding assistant's ``tool_calls`` order, matched by ``tool_call_id == tool_calls[].id`` (explicit tool_call_id association). Side-effect free; a run that can't be fully matched (missing/unknown ids) is left untouched; idempotent. """ out: list[dict] = [] id_index: dict[str, tuple[int, Any]] = {} i, n = 0, len(messages) while i < n: m = messages[i] role = m.get("role") if role == "assistant": id_index = self._tool_call_id_index(m.get("tool_calls")) out.append(m) i += 1 continue if role != "tool": out.append(m) i += 1 continue run, off, unresolved = [], 0, False while i < n and messages[i].get("role") == "tool": tm = messages[i] cid = tm.get("tool_call_id", tm.get("id")) matched = id_index.get(str(cid)) if cid is not None else None if matched is None: unresolved = True run.append((None, off, tm, None)) else: pos, name = matched run.append((pos, off, tm, name)) off += 1 i += 1 if unresolved: out.extend(t[2] for t in run) else: run.sort(key=lambda t: (t[0], t[1])) for _, _, tool_message, name in run: # The matched call is authoritative. These metadata fields # are useful to callers but are not rendered by # _render_tool. resolved = dict(tool_message) if name is not None: resolved["tool"] = name if "name" in resolved: resolved["name"] = name out.append(resolved) return out @staticmethod def _tc_fields(tc: dict) -> tuple[str, Any]: if "function" in tc and isinstance(tc["function"], dict): fn = tc["function"] return fn.get("name", ""), fn.get("arguments") return tc.get("name", ""), tc.get("arguments") def _normalize_arguments(self, arguments: Any) -> list[tuple[str, Any]]: """Normalize arguments -> ordered list of (key, value). Accepts: - JSON string: OpenAI-compatibile - dict: Hugging Face transformers - list-of-dict (each dict's items expanded in order; duplicate / ordered keys preserved). """ if arguments is None: return [] if isinstance(arguments, str): s = arguments.strip() if s == "": return [] try: arguments = json.loads(s) except json.JSONDecodeError: if self.strict_arguments: raise ValueError(f"tool arguments not valid JSON: {arguments!r}") return [("", arguments)] if isinstance(arguments, dict): return list(arguments.items()) if isinstance(arguments, list): pairs: list[tuple[str, Any]] = [] for item in arguments: if isinstance(item, dict): pairs.extend(item.items()) else: if self.strict_arguments: raise ValueError( f"list argument element must be dict, got {item!r}" ) return pairs if self.strict_arguments: raise ValueError(f"unsupported arguments type: {type(arguments)}") return [("", arguments)] @staticmethod def _as_text(v: Any) -> str: if isinstance(v, str): return v return json.dumps(v, ensure_ascii=False) @classmethod def _reasoning_to_text(cls, reasoning: Any) -> str: """Collapse ``reasoning_content`` to the inner text of the think block. Accepts a str (used verbatim) or a list of parts. The think block is plain text, so only text parts carry meaning; a text part's ``text`` is concatenated, and any other part is stringified defensively as data (same fallback as ``_render_content``). ``None`` -> "" (empty think). Both ``"foo"`` and ``[{"type": "text", "text": "foo"}]`` yield ``"foo"``, so str and parts forms render to identical tokens. """ if reasoning is None: return "" if isinstance(reasoning, str): return reasoning if isinstance(reasoning, list): out: list[str] = [] for part in reasoning: if isinstance(part, str): out.append(part) elif isinstance(part, dict) and part.get("type") in (None, "text"): out.append(part.get("text", "")) else: out.append(cls._as_text(part)) return "".join(out) return cls._as_text(reasoning) def _render_tools_block(self, segs, tools_norm: list[dict]): self._sp( segs, "# Tools\n\n" "You may call one or more functions to assist with the user query.\n\n" "You are provided with function signatures within XML tags:\n" "\n", "tools/prose", ) for t in tools_norm: self._dt(segs, json.dumps(t, ensure_ascii=False), "tools/schema") self._sp(segs, "\n", "tools/sep") self._sp( segs, "\n\nIf you choose to call a function, use exactly this format:\n", "tools/prose2", ) # Only has dedicated boundary tokens. Dynamic function and # parameter names intentionally follow Qwen's plaintext XML-ish form. self._sp(segs, f"{TOOL_CALL_O}\n", "tools/ex") self._dt( segs, "\n" "\n" "{parameter-value}\n" "\n" "\n", "tools/ex", ) self._sp(segs, TOOL_CALL_C, "tools/ex") @staticmethod def _normalize_tools(tools) -> list[dict]: if not tools: return [] out = [] for t in tools: if isinstance(t, dict) and t.get("type") == "function" and "function" in t: out.append(t) elif isinstance(t, dict) and "function" in t: out.append({"type": "function", "function": t["function"]}) elif isinstance(t, dict): # bare function schema out.append({"type": "function", "function": t}) else: raise ValueError(f"unsupported tool spec: {t!r}") return out # ---- content (text + multimodal passthrough) ------------------------- def _render_content(self, segs, content, tag, *, trainable): if content is None: return if isinstance(content, str): self._dt(segs, content, tag, trainable=trainable) return if isinstance(content, list): for part in content: if isinstance(part, str): self._dt(segs, part, tag, trainable=trainable) continue ptype = part.get("type") if ptype == "text": self._dt(segs, part.get("text", ""), tag, trainable=trainable) elif ptype in ("image", "image_url"): self._sp( segs, f"{VISION_START}{IMAGE_PAD}{VISION_END}", f"{tag}/image" ) elif ptype in ("video", "video_url"): self._sp( segs, f"{VISION_START}{VIDEO_PAD}{VISION_END}", f"{tag}/video" ) elif ptype in ("audio", "audio_url"): self._sp( segs, f"{AUDIO_START}{AUDIO_PAD}{AUDIO_END}", f"{tag}/audio" ) else: # unknown part -> stringify defensively as data raise ValueError(f"unsupported content part type: {ptype!r}") return self._dt(segs, self._as_text(content), tag, trainable=trainable) _TOOLCALL_RE = re.compile( rf"{re.escape(TOOL_CALL_O)}\r?\n.*?)>\r?\n" rf"(?P.*?)\r?\n{re.escape(TOOL_CALL_C)}", re.DOTALL, ) _PARAMETER_RE = re.compile( r"(?:^|\r?\n).*?)>\r?\n" r"(?P.*?)\r?\n", re.DOTALL, ) def _parse_parameters(body: str) -> dict: args: dict = {} for parameter in _PARAMETER_RE.finditer(body): key, value = parameter.group("key"), parameter.group("value") try: args[key] = json.loads(value) except (json.JSONDecodeError, ValueError): args[key] = value return args def parse_assistant_response_ids( token_ids: Iterable[int], tokenizer: TokenizerProtocol ) -> dict: """Parse original body IDs, including think prefill, without a ChatML header. Boundaries are control token IDs; incomplete think/tool blocks raise ValueError. Returns :func:`parse_assistant_response` fields. Requires ``tokenize_segment`` and lossless ``decode``; never re-encode text. Terminal ``<|im_end|>`` is optional. """ controls: dict[str, int] = {} for tag in (THINK_O, THINK_C, TOOL_CALL_O, TOOL_CALL_C, IM_END): encoded = tokenizer.tokenize_segment(tag, allow_special=True) if len(encoded) != 1: raise ValueError(f"{tag!r} must encode to one control token ID") controls[tag] = encoded[0] if len(set(controls.values())) != len(controls): raise ValueError("protocol control token IDs must be distinct") ids = list(token_ids) if controls[IM_END] in ids: ids = ids[: ids.index(controls[IM_END])] def decode(start: int, end: int) -> str: return tokenizer.decode(ids[start:end]) def close_after(tag: str, start: int) -> int: try: return ids.index(controls[tag], start) except ValueError: raise ValueError( f"incomplete assistant block: missing {tag} control ID" ) from None reasoning = None start = 0 if ids and ids[0] == controls[THINK_O]: close = close_after(THINK_C, 1) reasoning = decode(1, close) start = close + 1 first = next( (i for i in range(start, len(ids)) if ids[i] == controls[TOOL_CALL_O]), len(ids) ) prefix = decode(start, first) result = { "reasoning_content": reasoning, "content": prefix or None, "tool_calls": [], } if first == len(ids): return result pos = first while pos < len(ids): close = close_after(TOOL_CALL_C, pos + 1) # IDs delimit the call; the inner function/parameter markup is XML-ish. match = _TOOLCALL_RE.fullmatch( TOOL_CALL_O + decode(pos + 1, close) + TOOL_CALL_C ) if match is None: raise ValueError("invalid tool-call function/parameter markup") result["tool_calls"].append( { "name": match.group("name"), "arguments": _parse_parameters(match.group("body")), } ) pos = next( (i for i in range(close + 1, len(ids)) if ids[i] == controls[TOOL_CALL_O]), len(ids), ) return result