-
Notifications
You must be signed in to change notification settings - Fork 273
/
run_streaming_llama_longalpaca.py
115 lines (97 loc) · 3.51 KB
/
run_streaming_llama_longalpaca.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
import warnings
warnings.filterwarnings("ignore")
import torch
import argparse
import json
import os
import time
import re
import sys
from tqdm import tqdm
from streaming_llm.utils import load, download_url, load_jsonl
from streaming_llm.enable_streaming_llm import enable_streaming_llm
@torch.no_grad()
def greedy_generate(model, tokenizer, input_ids, past_key_values, max_gen_len):
outputs = model(
input_ids=input_ids,
past_key_values=past_key_values,
use_cache=True,
)
past_key_values = outputs.past_key_values
pred_token_idx = outputs.logits[:, -1, :].argmax(dim=-1).unsqueeze(1)
generated_ids = [pred_token_idx.item()]
pos = 0
for _ in range(max_gen_len - 1):
outputs = model(
input_ids=pred_token_idx,
past_key_values=past_key_values,
use_cache=True,
)
past_key_values = outputs.past_key_values
pred_token_idx = outputs.logits[:, -1, :].argmax(dim=-1).unsqueeze(1)
generated_ids.append(pred_token_idx.item())
generated_text = (
tokenizer.decode(
generated_ids,
skip_special_tokens=True,
clean_up_tokenization_spaces=True,
spaces_between_special_tokens=False,
)
.strip()
.split(" ")
)
now = len(generated_text) - 1
if now > pos:
print(" ".join(generated_text[pos:now]), end=" ", flush=True)
pos = now
if pred_token_idx == tokenizer.eos_token_id:
break
print(" ".join(generated_text[pos:]), flush=True)
return past_key_values
@torch.no_grad()
def streaming_inference(model, tokenizer, prompts, kv_cache=None, max_gen_len=1000):
past_key_values = None
for idx, prompt in enumerate(prompts):
prompt = "USER: " + prompt + "\n\nASSISTANT: "
print("\n" + prompt, end="")
input_ids = tokenizer(prompt, return_tensors="pt").input_ids
input_ids = input_ids.to(model.device)
seq_len = input_ids.shape[1]
if kv_cache is not None:
space_needed = seq_len + max_gen_len
past_key_values = kv_cache.evict_for_space(past_key_values, space_needed)
past_key_values = greedy_generate(
model, tokenizer, input_ids, past_key_values, max_gen_len=max_gen_len
)
def main(args):
model_name_or_path = args.model_name_or_path
model, tokenizer = load(model_name_or_path)
print(f"Loading data from {args.test_filepath} ...")
list_data = json.load(open(args.test_filepath))
prompts = []
for sample in list_data:
prompts += [sample["instruction"]]
if args.enable_streaming:
kv_cache = enable_streaming_llm(
model, start_size=args.start_size, recent_size=args.recent_size, use_flash_attn=args.use_flash_attn
)
else:
kv_cache = None
streaming_inference(
model,
tokenizer,
prompts,
kv_cache,
)
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"--model_name_or_path", type=str, default="Yukang/LongAlpaca-7B"
)
parser.add_argument("--test_filepath", type=str, default="outputs_stream.json")
parser.add_argument("--enable_streaming", action="store_true")
parser.add_argument("--start_size", type=int, default=4)
parser.add_argument("--recent_size", type=int, default=8192)
parser.add_argument("--use_flash_attn", type=bool, default=True)
args = parser.parse_args()
main(args)