hidden_states_engine.py 1.89 KB
Newer Older
1
2
3
4
"""
Usage:
python hidden_states.py

5
Note that each time you change the `return_hidden_states` parameter,
6
the cuda graph will be recaptured, which might lead to a performance hit.
7
So avoid getting hidden states and completions alternately.
8
9
"""

10
11
import torch

12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import sglang as sgl


def main():
    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.
    llm = sgl.Engine(
        model_path="Alibaba-NLP/gte-Qwen2-1.5B-instruct",
    )

27
28
29
30
31
    sampling_params = {
        "temperature": 0.8,
        "top_p": 0.95,
        "max_new_tokens": 10,
    }
32

33
34
35
    outputs = llm.generate(
        prompts, sampling_params=sampling_params, return_hidden_states=True
    )
36
37
38

    llm.shutdown()

39
    for prompt, output in zip(prompts, outputs):
40
41
42
43
        for i in range(len(output["meta_info"]["hidden_states"])):
            output["meta_info"]["hidden_states"][i] = torch.tensor(
                output["meta_info"]["hidden_states"][i], dtype=torch.bfloat16
            )
44
45
        print("===============================")
        print(
46
47
48
49
50
51
52
53
54
55
56
            f"Prompt: {prompt}\n"
            f"Generated text: {output['text']}\n"
            f"Prompt_Tokens: {output['meta_info']['prompt_tokens']}\t"
            f"Completion_tokens: {output['meta_info']['completion_tokens']}"
        )
        print("Hidden states: ")
        hidden_states = torch.cat(
            [
                i.unsqueeze(0) if len(i.shape) == 1 else i
                for i in output["meta_info"]["hidden_states"]
            ]
57
        )
58
        print(hidden_states)
59
60
61
62
63
64
65
        print()


# 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__":
    main()