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

from argparse import Namespace

from vllm import LLM, EngineArgs
7
8
9
from vllm.attention.backends.registry import AttentionBackendEnum
from vllm.config import AttentionConfig
from vllm.platforms import current_platform
10
from vllm.utils.argparse_utils import FlexibleArgumentParser
11
12


13
14
15
16
def parse_args():
    parser = FlexibleArgumentParser()
    parser = EngineArgs.add_cli_args(parser)
    # Set example specific arguments
17
    parser.set_defaults(
18
        model="intfloat/e5-small",
19
        runner="pooling",
20
        enforce_eager=True,
21
    )
22
23
24
    return parser.parse_args()


25
def main(args: Namespace):
26
27
28
29
30
    if current_platform.is_rocm():
        args.attention_config = AttentionConfig(
            backend=AttentionBackendEnum.FLEX_ATTENTION
        )

31
32
33
34
35
36
37
38
39
    # 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.
40
    # You should pass runner="pooling" for embedding models
41
    llm = LLM(**vars(args))
42
43

    # Generate embedding. The output is a list of EmbeddingRequestOutputs.
44
    outputs = llm.embed(prompts)
45
46

    # Print the outputs.
47
    print("\nGenerated Outputs:\n" + "-" * 60)
48
49
    for prompt, output in zip(prompts, outputs):
        embeds = output.outputs.embedding
50
51
52
53
        embeds_trimmed = (
            (str(embeds[:16])[:-1] + ", ...]") if len(embeds) > 16 else embeds
        )
        print(f"Prompt: {prompt!r} \nEmbeddings: {embeds_trimmed} (size={len(embeds)})")
54
        print("-" * 60)
55
56
57


if __name__ == "__main__":
58
    args = parse_args()
59
    main(args)