embed.py 1.37 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
15
16
    parser.set_defaults(
        model="intfloat/e5-mistral-7b-instruct", task="embed", enforce_eager=True
    )
17
18
19
    return parser.parse_args()


20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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
    model = LLM(**vars(args))

    # Generate embedding. The output is a list of EmbeddingRequestOutputs.
    outputs = model.embed(prompts)

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


if __name__ == "__main__":
48
    args = parse_args()
49
    main(args)