| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import pytest |
| 5 | from tokenizers import Tokenizer, models, pre_tokenizers |
| 6 | from transformers import TokenizersBackend |
| 7 | |
| 8 | from vllm.entrypoints.pooling.scoring.typing import ScoreInput |
| 9 | from vllm.entrypoints.pooling.scoring.utils import ( |
| 10 | truncate_text_to_tokens, |
| 11 | validate_score_input, |
| 12 | ) |
| 13 | from vllm.exceptions import VLLMValidationError |
| 14 | |
| 15 | |
| 16 | @pytest.mark.parametrize( |
| 17 | ("data_1", "data_2", "is_multimodal_model", "architecture", "message"), |
| 18 | [ |
| 19 | pytest.param( |
| 20 | {"content": []}, |
| 21 | "document", |
| 22 | False, |
| 23 | "TestModel", |
| 24 | "MultiModalParam is not supported for TestModel", |
| 25 | id="unsupported-multimodal-input", |
| 26 | ), |
| 27 | pytest.param( |
| 28 | ["query 1", "query 2"], |
| 29 | ["document"], |
| 30 | False, |
| 31 | "TestModel", |
| 32 | "Input lengths must be either 1:1, 1:N or N:N", |
| 33 | id="incompatible-input-lengths", |
| 34 | ), |
| 35 | pytest.param( |
| 36 | [], |
| 37 | ["document"], |
| 38 | False, |
| 39 | "TestModel", |
| 40 | "At least one text element must be given", |
| 41 | id="empty-first-input", |
| 42 | ), |
| 43 | pytest.param( |
| 44 | ["query"], |
| 45 | [], |
| 46 | False, |
| 47 | "TestModel", |
| 48 | "At least one text_pair element must be given", |
| 49 | id="empty-second-input", |
| 50 | ), |
| 51 | ], |
| 52 | ) |
| 53 | def test_validate_score_input_rejects_invalid_inputs( |
| 54 | data_1: ScoreInput | list[ScoreInput], |
| 55 | data_2: ScoreInput | list[ScoreInput], |
| 56 | is_multimodal_model: bool, |
| 57 | architecture: str, |
| 58 | message: str, |
| 59 | ): |
| 60 | with pytest.raises(VLLMValidationError) as exc_info: |
| 61 | validate_score_input( |
| 62 | data_1, |
| 63 | data_2, |
| 64 | is_multimodal_model=is_multimodal_model, |
| 65 | architecture=architecture, |
| 66 | ) |
| 67 | |
| 68 | assert str(exc_info.value) == message |
| 69 | assert exc_info.value.parameter is None |
| 70 | assert exc_info.value.value is None |
| 71 | |
| 72 | |
| 73 | def test_truncate_text_to_tokens_handles_shared_character_offsets(): |
| 74 | vocab = { |
| 75 | token: i for i, token in enumerate(sorted(pre_tokenizers.ByteLevel.alphabet())) |
| 76 | } |
| 77 | backend = Tokenizer(models.BPE(vocab=vocab, merges=[])) |
| 78 | backend.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) |
| 79 | tokenizer = TokenizersBackend(tokenizer_object=backend) |
| 80 | |
| 81 | truncated = truncate_text_to_tokens("aéx", tokenizer, max_tokens=2) |
| 82 | |
| 83 | assert truncated == "a" |
| 84 | assert len(tokenizer(truncated, add_special_tokens=False)["input_ids"]) == 1 |