token_in_token_out_llm.py 1.32 KB
Newer Older
1
"""
2
This example demonstrates how to provide tokenized ids to LLM as input instead of text prompt, i.e. a token-in-token-out workflow.
3
4
5
6
7
8
9
"""

import sglang as sgl
from sglang.srt.hf_transformers_utils import get_tokenizer

MODEL_PATH = "meta-llama/Llama-3.1-8B-Instruct"

Chayenne's avatar
Chayenne committed
10

11
12
13
14
15
16
17
18
19
20
21
22
23
24
def main():
    # 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 a sampling params object.
    sampling_params = {"temperature": 0.8, "top_p": 0.95}

    # Tokenize inputs
    tokenizer = get_tokenizer(MODEL_PATH)
    token_ids_list = [tokenizer.encode(prompt) for prompt in prompts]
25

26
    # Create an LLM.
27
    llm = sgl.Engine(model_path=MODEL_PATH, skip_tokenizer_init=True)
28
29
30
31
32

    outputs = llm.generate(input_ids=token_ids_list, sampling_params=sampling_params)
    # Print the outputs.
    for prompt, output in zip(prompts, outputs):
        print("===============================")
33
        print(f"Prompt: {prompt}\nGenerated token ids: {output['token_ids']}")
34
35
36
37
38


# The __main__ condition is necessary here because we use "spawn" to create subprocesses
# Spawn starts a fresh program every time, if there is no __main__, it will run into infinite loop to keep spawning processes from sgl.Engine
if __name__ == "__main__":
39
    main()