embed.py 1.41 KB
Newer Older
1
# SPDX-License-Identifier: Apache-2.0
2
# SPDX-FileCopyrightText: Copyright contributors to the vLLM project
3
4
5
6
7
8
9

from argparse import Namespace

from vllm import LLM, EngineArgs
from vllm.utils import FlexibleArgumentParser


10
11
12
13
def parse_args():
    parser = FlexibleArgumentParser()
    parser = EngineArgs.add_cli_args(parser)
    # Set example specific arguments
14
    parser.set_defaults(
15
16
17
18
        model="intfloat/e5-mistral-7b-instruct",
        task="embed",
        enforce_eager=True,
        max_model_len=1024,
19
    )
20
21
22
    return parser.parse_args()


23
24
25
26
27
28
29
30
31
32
33
def main(args: Namespace):
    # Sample prompts.
    prompts = [
        "Hello, my name is",
        "The president of the United States is",
        "The capital of France is",
        "The future of AI is",
    ]

    # Create an LLM.
    # You should pass task="embed" for embedding models
34
    llm = LLM(**vars(args))
35
36

    # Generate embedding. The output is a list of EmbeddingRequestOutputs.
37
    outputs = llm.embed(prompts)
38
39

    # Print the outputs.
40
    print("\nGenerated Outputs:\n" + "-" * 60)
41
42
    for prompt, output in zip(prompts, outputs):
        embeds = output.outputs.embedding
43
44
45
46
        embeds_trimmed = (
            (str(embeds[:16])[:-1] + ", ...]") if len(embeds) > 16 else embeds
        )
        print(f"Prompt: {prompt!r} \nEmbeddings: {embeds_trimmed} (size={len(embeds)})")
47
        print("-" * 60)
48
49
50


if __name__ == "__main__":
51
    args = parse_args()
52
    main(args)