|
| 1 | +""" |
| 2 | +Author: |
| 3 | +Date: 2026-03-31 10:40:18 |
| 4 | +LastEditors: |
| 5 | +LastEditTime: 2026-04-01 11:00:47 |
| 6 | +FilePath: /fastdeploy/test_decode_token.py |
| 7 | +""" |
| 8 | + |
| 9 | +""" |
| 10 | +# Copyright (c) 2025 PaddlePaddle Authors. All Rights Reserved. |
| 11 | +# |
| 12 | +# Licensed under the Apache License, Version 2.0 (the "License" |
| 13 | +# you may not use this file except in compliance with the License. |
| 14 | +# You may obtain a copy of the License at |
| 15 | +# |
| 16 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 17 | +# |
| 18 | +# Unless required by applicable law or agreed to in writing, software |
| 19 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 20 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 21 | +# See the License for the specific language governing permissions and |
| 22 | +# limitations under the License. |
| 23 | +""" |
| 24 | + |
| 25 | +import os |
| 26 | +import sys |
| 27 | +import unittest |
| 28 | +from unittest.mock import MagicMock, patch |
| 29 | + |
| 30 | +sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "..")) |
| 31 | + |
| 32 | +from fastdeploy.engine.common_engine import EngineService |
| 33 | +from fastdeploy.utils import envs |
| 34 | + |
| 35 | + |
| 36 | +def _make_mock_ids2tokens(decode_status, undecoded_tokens=None): |
| 37 | + """ |
| 38 | + Create a mock ids2tokens that simulates incremental decoding behavior. |
| 39 | +
|
| 40 | + Simulates the non-HF path of DataProcessor.ids2tokens: |
| 41 | + - decode_status[task_id] = [prefix_offset, read_offset, cumulative_token_ids, cumulative_text] |
| 42 | + - Returns (delta_text, previous_token_ids, previous_texts) |
| 43 | +
|
| 44 | + Args: |
| 45 | + decode_status: shared dict for tracking decode state |
| 46 | + undecoded_tokens: set of token IDs that produce no visible text (delta_text=""), |
| 47 | + simulating tokens that cannot be decoded incrementally. |
| 48 | + read_offset will NOT advance for these tokens. |
| 49 | + """ |
| 50 | + undecoded_tokens = undecoded_tokens or set() |
| 51 | + |
| 52 | + # Simple token->char mapping for testing |
| 53 | + token_map = { |
| 54 | + 1000: "你", |
| 55 | + 1001: "好", |
| 56 | + } |
| 57 | + |
| 58 | + def mock_ids2tokens(token_ids, task_id): |
| 59 | + if task_id not in decode_status: |
| 60 | + decode_status[task_id] = [0, 0, [], ""] |
| 61 | + |
| 62 | + previous_token_ids = list(decode_status[task_id][2]) |
| 63 | + previous_texts = decode_status[task_id][3] |
| 64 | + |
| 65 | + # Append new tokens to cumulative list |
| 66 | + decode_status[task_id][2] += token_ids |
| 67 | + |
| 68 | + # Check if all new tokens are "undecoded" (produce no visible text) |
| 69 | + all_undecoded = all(tid in undecoded_tokens for tid in token_ids) if token_ids else True |
| 70 | + |
| 71 | + if all_undecoded and token_ids: |
| 72 | + # These tokens can't be decoded yet - don't advance read_offset |
| 73 | + delta_text = "" |
| 74 | + else: |
| 75 | + # Normal decoding |
| 76 | + delta_text = "" |
| 77 | + for tid in token_ids: |
| 78 | + delta_text += token_map.get(tid, f"<{tid}>") |
| 79 | + |
| 80 | + if token_ids: |
| 81 | + # Only advance offsets when there are actual tokens |
| 82 | + cum_len = len(decode_status[task_id][2]) |
| 83 | + decode_status[task_id][0] = max(0, cum_len - 1) # prefix_offset |
| 84 | + decode_status[task_id][1] = cum_len # read_offset |
| 85 | + decode_status[task_id][3] += delta_text |
| 86 | + |
| 87 | + return delta_text, previous_token_ids, previous_texts |
| 88 | + |
| 89 | + return mock_ids2tokens |
| 90 | + |
| 91 | + |
| 92 | +class TestDecodeToken(unittest.TestCase): |
| 93 | + """Test case for _decode_token method with mocked tokenizer""" |
| 94 | + |
| 95 | + def setUp(self): |
| 96 | + self.req_id = "test_req_123" |
| 97 | + self._setup_engine() |
| 98 | + |
| 99 | + def _setup_engine(self, undecoded_tokens=None): |
| 100 | + self.decode_status = {} |
| 101 | + |
| 102 | + self.data_processor = MagicMock() |
| 103 | + self.data_processor.decode_status = self.decode_status |
| 104 | + self.data_processor.ids2tokens = _make_mock_ids2tokens(self.decode_status, undecoded_tokens) |
| 105 | + |
| 106 | + self.engine = MagicMock(spec=EngineService) |
| 107 | + self.engine.data_processor = self.data_processor |
| 108 | + self.engine._decode_token = EngineService._decode_token.__get__(self.engine, EngineService) |
| 109 | + |
| 110 | + # Common init for decode_status |
| 111 | + self.decode_status[self.req_id] = [0, 0, [], ""] |
| 112 | + |
| 113 | + def _assert_cleaned_up(self): |
| 114 | + self.assertNotIn(self.req_id, self.data_processor.decode_status) |
| 115 | + |
| 116 | + def test_empty_end(self): |
| 117 | + """Empty token_ids with is_end=True should return empty and cleanup""" |
| 118 | + with patch.object(envs, "FD_ENABLE_RETURN_TEXT", True): |
| 119 | + delta_text, returned_tokens = self.engine._decode_token([], self.req_id, is_end=True) |
| 120 | + self.assertEqual(delta_text, "") |
| 121 | + self.assertEqual(returned_tokens, []) |
| 122 | + self._assert_cleaned_up() |
| 123 | + |
| 124 | + def test_incremental_decoding_and_cleanup(self): |
| 125 | + """Tokens added in multiple steps should decode correctly and cleanup at end""" |
| 126 | + with patch.object(envs, "FD_ENABLE_RETURN_TEXT", True): |
| 127 | + for token_id in [1000, 1001]: # "你", "好" |
| 128 | + delta_text, _ = self.engine._decode_token([token_id], self.req_id, is_end=False) |
| 129 | + self.assertTrue(len(delta_text) > 0) |
| 130 | + |
| 131 | + delta_text, _ = self.engine._decode_token([], self.req_id, is_end=True) |
| 132 | + self._assert_cleaned_up() |
| 133 | + |
| 134 | + def test_undecoded_tokens_on_end(self): |
| 135 | + """Test that tokens which produce no visible text during streaming |
| 136 | + are force-decoded when is_end=True""" |
| 137 | + # Re-setup with 109584 as an undecoded token (produces no delta_text during streaming) |
| 138 | + self._setup_engine(undecoded_tokens={109584}) |
| 139 | + self.decode_status[self.req_id] = [0, 0, [], ""] |
| 140 | + |
| 141 | + with patch.object(envs, "FD_ENABLE_RETURN_TEXT", True), patch.dict(os.environ, {"DEBUG_DECODE": "1"}): |
| 142 | + all_delta = "" |
| 143 | + |
| 144 | + delta_text, _ = self.engine._decode_token([109584], self.req_id, is_end=False) |
| 145 | + all_delta += delta_text |
| 146 | + |
| 147 | + # Now end the stream - force decode should recover any remaining text |
| 148 | + delta_end, _ = self.engine._decode_token([109584], self.req_id, is_end=False) |
| 149 | + all_delta += delta_end |
| 150 | + delta_end, _ = self.engine._decode_token([109584], self.req_id, is_end=False) |
| 151 | + all_delta += delta_end |
| 152 | + delta_end, token_ids = self.engine._decode_token([], self.req_id, is_end=True) |
| 153 | + all_delta += delta_end |
| 154 | + |
| 155 | + # The full text must be recovered either during streaming or at end |
| 156 | + self.assertEqual(token_ids, [109584, 109584, 109584]) |
| 157 | + self._assert_cleaned_up() |
| 158 | + |
| 159 | + |
| 160 | +if __name__ == "__main__": |
| 161 | + unittest.main() |
0 commit comments