| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | |
| 4 | from argparse import Namespace |
| 5 | |
| 6 | from vllm import LLM, EngineArgs |
| 7 | from vllm.config import PoolerConfig |
| 8 | from vllm.utils.argparse_utils import FlexibleArgumentParser |
| 9 | |
| 10 | |
| 11 | def parse_args(): |
| 12 | parser = FlexibleArgumentParser() |
| 13 | parser = EngineArgs.add_cli_args(parser) |
| 14 | # Set example specific arguments |
| 15 | parser.set_defaults( |
| 16 | model="BAAI/bge-m3", |
| 17 | pooler_config=PoolerConfig(task="token_embed"), |
| 18 | runner="pooling", |
| 19 | enforce_eager=True, |
| 20 | ) |
| 21 | return parser.parse_args() |
| 22 | |
| 23 | |
| 24 | def main(args: Namespace): |
| 25 | # Sample prompts. |
| 26 | prompts = [ |
| 27 | "Hello, my name is", |
| 28 | "The president of the United States is", |
| 29 | "The capital of France is", |
| 30 | "The future of AI is", |
| 31 | ] |
| 32 | |
| 33 | # Create an LLM. |
| 34 | # You should pass runner="pooling" for embedding models |
| 35 | llm = LLM(**vars(args)) |
| 36 | |
| 37 | # Generate embedding for each token. The output is a list of PoolingRequestOutput. |
| 38 | outputs = llm.encode(prompts, pooling_task="token_embed") |
| 39 | |
| 40 | # Print the outputs. |
| 41 | print("\nGenerated Outputs:\n" + "-" * 60) |
| 42 | for prompt, output in zip(prompts, outputs): |
| 43 | multi_vector = output.outputs.data |
| 44 | print(multi_vector.shape) |
| 45 | |
| 46 | query = "What is the capital of France?" |
| 47 | documents = [ |
| 48 | "The capital of Brazil is Brasilia.", |
| 49 | "The capital of France is Paris.", |
| 50 | ] |
| 51 | # Generate scores. |
| 52 | outputs = llm.score(query, documents) |
| 53 | # Print the outputs. |
| 54 | print("\nGenerated Outputs:\n" + "-" * 60) |
| 55 | for document, output in zip(documents, outputs): |
| 56 | score = output.outputs.score |
| 57 | print(f"Pair: {[query, document]!r} \nScore: {score}") |
| 58 | print("-" * 60) |
| 59 | |
| 60 | |
| 61 | if __name__ == "__main__": |
| 62 | args = parse_args() |
| 63 | main(args) |