| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | import importlib |
| 5 | import importlib.util |
| 6 | import json |
| 7 | import warnings |
| 8 | from types import SimpleNamespace |
| 9 | |
| 10 | import numpy as np |
| 11 | import pytest |
| 12 | import torch |
| 13 | |
| 14 | from vllm.entrypoints.pooling.utils import encode_pooling_output_float_or_ndarray |
| 15 | |
| 16 | |
| 17 | def _pooling_output(data): |
| 18 | return SimpleNamespace(outputs=SimpleNamespace(data=data)) |
| 19 | |
| 20 | |
| 21 | def test_encode_pooling_output_float_or_ndarray_returns_numpy_array(): |
| 22 | output = _pooling_output(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32)) |
| 23 | |
| 24 | encoded = encode_pooling_output_float_or_ndarray(output) |
| 25 | |
| 26 | assert isinstance(encoded, np.ndarray) |
| 27 | np.testing.assert_allclose(encoded, [1.0, 2.0, 3.0]) |
| 28 | |
| 29 | |
| 30 | @pytest.mark.skipif( |
| 31 | importlib.util.find_spec("orjson") is None, |
| 32 | reason="orjson is not installed", |
| 33 | ) |
| 34 | def test_orjson_serializes_numpy_array(): |
| 35 | from fastapi.responses import ORJSONResponse |
| 36 | |
| 37 | output = _pooling_output(torch.tensor([1.0, 2.0, 3.0], dtype=torch.float32)) |
| 38 | encoded = encode_pooling_output_float_or_ndarray(output) |
| 39 | |
| 40 | with warnings.catch_warnings(): |
| 41 | warnings.simplefilter("ignore", DeprecationWarning) |
| 42 | response = ORJSONResponse(content={"embedding": encoded}) |
| 43 | assert json.loads(response.body)["embedding"] == pytest.approx([1.0, 2.0, 3.0]) |
| 44 | |
| 45 | |
| 46 | def test_encode_pooling_output_float_or_ndarray_falls_back_to_list(): |
| 47 | class DataWithUnsupportedNumpy: |
| 48 | def is_contiguous(self): |
| 49 | return True |
| 50 | |
| 51 | def numpy(self): |
| 52 | raise TypeError("unsupported dtype") |
| 53 | |
| 54 | def tolist(self): |
| 55 | return [1.0, 2.0, 3.0] |
| 56 | |
| 57 | output = _pooling_output(DataWithUnsupportedNumpy()) |
| 58 | |
| 59 | assert encode_pooling_output_float_or_ndarray(output) == [1.0, 2.0, 3.0] |