Skip to content

Commit 39c4019

Browse files
authored
Fix server 404 on short prompts: clamp negative start in think-token search (ml-explore#1327)
mlx_lm.server computes start = len(prompt) - 11 and passes it to rfind_think_start; for prompts under 11 tokens start is negative, so _find indexes past the token list and raises IndexError (surfaced as HTTP 404) on common one-word messages like "hi". Clamp start to 0 in _find; add a regression test.
1 parent e476a22 commit 39c4019

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

mlx_lm/tokenizer_utils.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -354,8 +354,9 @@ def add_eos_token(self, token: str):
354354

355355
self._eos_token_ids.add(token_id)
356356

357-
def _find(self, tokens, sequence, start=None, end=None, reverse=False):
358-
start = start or 0
357+
@staticmethod
358+
def _find(tokens, sequence, start=None, end=None, reverse=False):
359+
start = max(start or 0, 0)
359360
end = end or len(tokens)
360361
outer_loop = (
361362
range(end - len(sequence), start - 1, -1)

tests/test_tokenizers.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
BPEStreamingDetokenizer,
1010
NaiveStreamingDetokenizer,
1111
SPMStreamingDetokenizer,
12+
TokenizerWrapper,
1213
)
1314
from mlx_lm.utils import load_tokenizer
1415

@@ -109,6 +110,19 @@ def test_thinking(self):
109110
self.assertIsNone(tokenizer.think_start_id)
110111
self.assertIsNone(tokenizer.think_end_id)
111112

113+
def test_find_token(self):
114+
# Check that _find returns a valid index when
115+
# searching for a think token in short system prompts
116+
HI, THINK_START, THINK_END = 200, 100, 101
117+
find = TokenizerWrapper._find
118+
prompt = [HI]
119+
start = len(prompt) - 11
120+
self.assertEqual(find(prompt, [THINK_START], start=start), -1)
121+
self.assertEqual(find(prompt, [THINK_START], start=start, reverse=True), -1)
122+
prompt = [HI, THINK_START, THINK_END, THINK_START]
123+
self.assertEqual(find(prompt, [THINK_START], start=0), 1)
124+
self.assertEqual(find(prompt, [THINK_START], start=0, reverse=True), 3)
125+
112126

113127
if __name__ == "__main__":
114128
unittest.main()

0 commit comments

Comments
 (0)