Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 23 additions & 3 deletions python/freetoken/tokenizer/effort.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,9 @@ class EffortProfile:
``default`` is the supported name whose rendering is byte-identical to
passing no effort at all. ``consumes_effort`` False means no probe round
ever changed its output or raised -- the template ignores the knob, so
requests should not carry it. ``validates`` True means the probe observed a
rejection: only then is ``supported`` a real vocabulary rather than "this
requests should not carry it. ``validates`` True means the probe saw a known
name rejected, or a made-up name rejected by a template that reads the effort:
only then is ``supported`` a real vocabulary rather than "this
template interpolates anything". ``strength_dialect`` True means the
template reads the ``reasoning_strength`` spelling (muse-glimmer's family,
whose documented ladder tops out at xhigh) rather than only
Expand Down Expand Up @@ -165,6 +166,8 @@ def quantize_effort(value: Any, profile: EffortProfile) -> str | int | None:
}
]

_UNKNOWN_EFFORT = "__freetoken_unknown_effort__"

#: (extra chat_template_kwargs, tools) per probe round: templates read effort
#: unconditionally, under tool-forced thinking, or only under an explicit
#: thinking opt-in -- one round per shape.
Expand All @@ -189,13 +192,20 @@ def probe_effort_profile(
matches_baseline: dict[str, bool] = {name: True for name in KNOWN_REASONING_EFFORTS}
ran_rounds = 0
integer_range = None
# a template that rejects a name off every scale checks its vocabulary, even when it
# accepts every known name (Inkling 2 grades all seven)
rejects_unknown = False

for base_kwargs, tools in _PROBE_ROUNDS:
try:
baseline = render(dict(base_kwargs), tools)
except Exception: # noqa: BLE001 -- template rejects the probe shape, not the effort
continue
ran_rounds += 1
try:
render({**base_kwargs, "reasoning_effort": _UNKNOWN_EFFORT}, tools)
except Exception: # noqa: BLE001 -- any raise means "not accepted"
rejects_unknown = True
for name in KNOWN_REASONING_EFFORTS:
try:
rendering = render({**base_kwargs, "reasoning_effort": name}, tools)
Expand Down Expand Up @@ -236,7 +246,7 @@ def probe_effort_profile(
supported=supported,
default=default,
consumes_effort=consumes,
validates=bool(rejected),
validates=bool(rejected) or (consumes and rejects_unknown),
strength_dialect=strength_dialect,
integer_range=integer_range,
)
Expand Down Expand Up @@ -294,6 +304,16 @@ def probe_thinking_profile(
)


def thinking_off_kwargs(chat_template_kwargs: dict[str, Any], profile: ThinkingProfile) -> dict[str, Any]:
"""A thinking-off request (``enable_thinking`` False, no effort) on a template without a
thinking toggle renders its "none" effort gear when it has one (Inkling 2: level 0.0)."""
if chat_template_kwargs.get("enable_thinking") is not False or chat_template_kwargs.get("reasoning_effort") is not None:
return chat_template_kwargs
if profile.toggleable or "none" not in effective_efforts(profile.efforts):
return chat_template_kwargs
return {**chat_template_kwargs, "reasoning_effort": "none"}


def _renderings_differ(a: Any, b: Any) -> bool:
try:
return bool(a != b)
Expand Down
3 changes: 3 additions & 0 deletions python/freetoken/tokenizer/tokenize.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
probe_effort_profile,
probe_thinking_profile,
quantize_effort,
thinking_off_kwargs,
)
from .inline_system import has_inline_system, normalize_inline_system, probe_inline_system

Expand Down Expand Up @@ -108,6 +109,8 @@ def render_prompt(self, msg: TokenizeMsg) -> str:
if not isinstance(msg.text, list):
return msg.text
kwargs = self._sanitize_effort(msg.chat_template_kwargs or {})
if kwargs.get("enable_thinking") is False:
kwargs = thinking_off_kwargs(kwargs, self.thinking_profile())
messages = msg.text
if msg.inline_system_policy is not None:
if msg.inline_system_policy not in ("auto", "preserve", "fold"):
Expand Down
53 changes: 53 additions & 0 deletions tests/tokenizer/test_effort.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,18 @@

import pytest

from freetoken.core import SamplingParams
from freetoken.message import TokenizeMsg
from freetoken.tokenizer.effort import (
EFFORT_SCALE,
EffortProfile,
KNOWN_REASONING_EFFORTS,
probe_effort_profile,
probe_thinking_profile,
quantize_effort,
thinking_off_kwargs,
)
from freetoken.tokenizer.tokenize import TokenizeManager

QWEN38 = EffortProfile(
supported=frozenset({"xhigh", "medium", "low"}), default="xhigh", consumes_effort=True
Expand Down Expand Up @@ -124,6 +129,54 @@ def test_probe_marks_an_interpolating_template_as_not_validating():
assert not profile.validates


def _inkling2_render(kwargs, tools):
# Inkling 2's template: every known name maps onto a numeric level (default high, 0.9),
# floats in [0, 0.99] pass through, any other string raises.
levels = {"none": 0.0, "minimal": 0.1, "low": 0.2, "medium": 0.7, "high": 0.9, "xhigh": 0.99, "max": 0.99}
effort = kwargs.get("reasoning_effort")
if effort is None:
effort = 0.9
if isinstance(effort, str):
if effort not in levels:
raise ValueError(f"Unknown reasoning_effort: {effort}")
effort = levels[effort]
return f"Thinking effort level: {effort}|tools={bool(tools)}"


def test_probe_serves_every_gear_of_a_template_that_rejects_unknown_names():
profile = probe_effort_profile(_inkling2_render)
assert profile.validates
for name in KNOWN_REASONING_EFFORTS:
assert quantize_effort(name, profile) == name


def test_thinking_off_renders_the_none_gear_only_without_a_toggle():
off = {"enable_thinking": False, "thinking_mode": "disabled"}
inkling = probe_thinking_profile(_inkling2_render, probe_effort_profile(_inkling2_render))
assert _inkling2_render(thinking_off_kwargs(off, inkling), None) == _inkling2_render({"reasoning_effort": 0.0}, None)

def toggled(kwargs, tools): # same gears, plus a thinking switch the template honors
return f"{_inkling2_render(kwargs, tools)}|think={kwargs.get('enable_thinking', True)}"

profile = probe_thinking_profile(toggled, probe_effort_profile(toggled))
assert thinking_off_kwargs(off, profile) == off


class _Inkling2Tokenizer:
chat_template = "inkling-shaped"

def apply_chat_template(self, messages, tokenize, add_generation_prompt, **kwargs):
return _inkling2_render(kwargs, kwargs.get("tools"))


def test_render_prompt_renders_thinking_off_as_the_none_gear():
manager = TokenizeManager(_Inkling2Tokenizer())
messages = [{"role": "user", "content": "hi"}]
for kwargs in ({"enable_thinking": False}, {"enable_thinking": False, "reasoning_effort": None}):
msg = TokenizeMsg(uid=0, text=messages, sampling_params=SamplingParams(), chat_template_kwargs=kwargs)
assert manager.render_prompt(msg) == _inkling2_render({"reasoning_effort": 0.0}, None), kwargs


def test_probe_skips_rounds_whose_baseline_fails():
def render(kwargs, tools):
if tools: # template rejects tools outright -- round is uninformative
Expand Down