eagle.py 4.54 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
import argparse
import json
import os

from transformers import AutoTokenizer

from vllm import LLM, SamplingParams
10
from vllm.v1.metrics.reader import Counter, Vector
11

Reid's avatar
Reid committed
12
13
14
15
16
17
18
19
20
21
22
23
24

def load_prompts(dataset_path, num_prompts):
    if os.path.exists(dataset_path):
        prompts = []
        try:
            with open(dataset_path) as f:
                for line in f:
                    data = json.loads(line)
                    prompts.append(data["turns"][0])
        except Exception as e:
            print(f"Error reading dataset: {e}")
            return []
    else:
25
        prompts = ["The future of AI is", "The president of the United States is"]
Reid's avatar
Reid committed
26
27
28
29

    return prompts[:num_prompts]


30
def parse_args():
Reid's avatar
Reid committed
31
32
33
34
35
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--dataset",
        type=str,
        default="./examples/data/gsm8k.jsonl",
36
37
38
39
40
        help="downloaded from the eagle repo "
        "https://github.com/SafeAILab/EAGLE/blob/main/eagle/data/",
    )
    parser.add_argument(
        "--method", type=str, default="eagle", choices=["eagle", "eagle3"]
Reid's avatar
Reid committed
41
42
43
44
45
46
    )
    parser.add_argument("--max_num_seqs", type=int, default=8)
    parser.add_argument("--num_prompts", type=int, default=80)
    parser.add_argument("--num_spec_tokens", type=int, default=2)
    parser.add_argument("--tp", type=int, default=1)
    parser.add_argument("--draft_tp", type=int, default=1)
47
48
    parser.add_argument("--enforce_eager", action="store_true")
    parser.add_argument("--enable_chunked_prefill", action="store_true")
Reid's avatar
Reid committed
49
50
    parser.add_argument("--max_num_batched_tokens", type=int, default=2048)
    parser.add_argument("--temp", type=float, default=0)
51
52
53
54
55
    return parser.parse_args()


def main():
    args = parse_args()
Reid's avatar
Reid committed
56

57
    model_dir = "meta-llama/Llama-3.1-8B-Instruct"
58

59
    if args.method == "eagle":
60
        eagle_dir = "yuhuili/EAGLE-LLaMA3.1-Instruct-8B"
61
    elif args.method == "eagle3":
62
63
64
        eagle_dir = "yuhuili/EAGLE3-LLaMA3.1-Instruct-8B"
    else:
        raise ValueError(f"unknown method: {args.method}")
Reid's avatar
Reid committed
65
66
67
68
69
70
71
72

    max_model_len = 2048

    tokenizer = AutoTokenizer.from_pretrained(model_dir)

    prompts = load_prompts(args.dataset, args.num_prompts)

    prompt_ids = [
73
74
75
        tokenizer.apply_chat_template(
            [{"role": "user", "content": prompt}], add_generation_prompt=True
        )
Reid's avatar
Reid committed
76
77
78
79
80
81
82
83
84
85
86
87
88
89
        for prompt in prompts
    ]

    llm = LLM(
        model=model_dir,
        trust_remote_code=True,
        tensor_parallel_size=args.tp,
        enable_chunked_prefill=args.enable_chunked_prefill,
        max_num_batched_tokens=args.max_num_batched_tokens,
        enforce_eager=args.enforce_eager,
        max_model_len=max_model_len,
        max_num_seqs=args.max_num_seqs,
        gpu_memory_utilization=0.8,
        speculative_config={
90
            "method": args.method,
Reid's avatar
Reid committed
91
92
93
94
95
96
97
98
99
100
            "model": eagle_dir,
            "num_speculative_tokens": args.num_spec_tokens,
            "draft_tensor_parallel_size": args.draft_tp,
            "max_model_len": max_model_len,
        },
        disable_log_stats=False,
    )

    sampling_params = SamplingParams(temperature=args.temp, max_tokens=256)

101
    outputs = llm.generate(prompt_token_ids=prompt_ids, sampling_params=sampling_params)
Reid's avatar
Reid committed
102

103
104
105
106
107
108
109
    # print the generated text
    for output in outputs:
        print("-" * 50)
        print(f"prompt: {output.prompt}")
        print(f"generated text: {output.outputs[0].text}")
        print("-" * 50)

110
111
112
113
    try:
        metrics = llm.get_metrics()
    except AssertionError:
        print("Metrics are not supported in the V0 engine.")
114
115
        return

116
117
118
119
120
121
122
123
124
125
126
127
128
    num_drafts = num_accepted = 0
    acceptance_counts = [0] * args.num_spec_tokens
    for metric in metrics:
        if metric.name == "vllm:spec_decode_num_drafts":
            assert isinstance(metric, Counter)
            num_drafts += metric.value
        elif metric.name == "vllm:spec_decode_num_accepted_tokens":
            assert isinstance(metric, Counter)
            num_accepted += metric.value
        elif metric.name == "vllm:spec_decode_num_accepted_tokens_per_pos":
            assert isinstance(metric, Vector)
            for pos in range(len(metric.values)):
                acceptance_counts[pos] += metric.values[pos]
Reid's avatar
Reid committed
129
130

    print("-" * 50)
131
    print(f"mean acceptance length: {1 + (num_accepted / num_drafts):.2f}")
Reid's avatar
Reid committed
132
133
    print("-" * 50)

134
135
    # print acceptance at each token position
    for i in range(len(acceptance_counts)):
136
        print(f"acceptance at token {i}:{acceptance_counts[i] / num_drafts:.2f}")
137

Reid's avatar
Reid committed
138
139
140

if __name__ == "__main__":
    main()