-
Notifications
You must be signed in to change notification settings - Fork 10
/
inference.py
185 lines (162 loc) · 5.9 KB
/
inference.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
# coding=utf-8
# Copyright 2023 42dot Inc.
#
# @author [email protected]
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import gc
import torch
from transformers import AutoTokenizer, AutoModelForCausalLM
from transformers.generation.logits_process import (
LogitsProcessorList,
RepetitionPenaltyLogitsProcessor,
TemperatureLogitsWarper,
TopKLogitsWarper,
TopPLogitsWarper,
)
# This code is heavily derived from FastChat implementation.
def prepare_logits_processor(
temperature: float, repetition_penalty: float, top_p: float, top_k: int
) -> LogitsProcessorList:
processor_list = LogitsProcessorList()
# TemperatureLogitsWarper doesn't accept 0.0, 1.0 makes it a no-op so we skip two cases.
if temperature >= 1e-5 and temperature != 1.0:
processor_list.append(TemperatureLogitsWarper(temperature))
if repetition_penalty > 1.0:
processor_list.append(RepetitionPenaltyLogitsProcessor(repetition_penalty))
if 1e-8 <= top_p < 1.0:
processor_list.append(TopPLogitsWarper(top_p))
if top_k > 0:
processor_list.append(TopKLogitsWarper(top_k))
return processor_list
def load_model(
model: str,
temperature: float,
repetition_penalty: float,
top_p: float,
top_k: int,
device: str,
):
tokenizer = AutoTokenizer.from_pretrained(model, use_fast=False, add_bos_token=True)
model = AutoModelForCausalLM.from_pretrained(model).to(device)
return model, tokenizer, prepare_logits_processor(
temperature, repetition_penalty, top_p, top_k
)
@torch.inference_mode()
def generate_stream(
model,
tokenizer,
logits_processor,
prompt,
temperature: float,
repetition_penalty: float,
top_p: float,
top_k: int,
max_new_tokens: int,
device: str,
debug: False,
):
input_ids = tokenizer(prompt).input_ids
output_ids = list(input_ids)
input_echo_len = len(input_ids)
stream_interval = 1 if debug else 2
for i in range(max_new_tokens):
if i == 0:
out = model(
input_ids=torch.as_tensor([input_ids], device=device),
use_cache=True,
)
logits = out.logits
past_key_values = out.past_key_values
else: # Use past_key_values and generate only one token for speed improvement.
out = model(
input_ids=torch.as_tensor([[last_token]], device=device),
use_cache=True,
past_key_values=past_key_values,
)
logits = out.logits
past_key_values = out.past_key_values
# If repetition_penalty is set, inject all_output_ids.
if repetition_penalty > 1.0:
all_output_ids = torch.as_tensor([output_ids], device=device)
else:
all_output_ids = None
# Aggregate raw probability tokens.
candidates = []
candidates_probs = torch.softmax(logits[:, -1, :][0], dim=-1)
_, indices = torch.topk(candidates_probs, 5)
for index in indices:
candidates.append({
index.item(): [tokenizer.decode(index.item()), round(candidates_probs[index].item(), 4)]
})
# Process transformers' LogitsProcessor using the last token's logit.
last_token_logits = logits_processor(all_output_ids, logits[:, -1, :])[0]
# Sampling from the multinomial probability distribution.
probs = torch.softmax(last_token_logits, dim=-1)
indices = torch.multinomial(probs, num_samples=5)
tokens = [int(token) for token in indices.tolist()]
# Aggregate processed probability tokens.
selected = []
for index in indices:
selected.append({
index.item(): [tokenizer.decode(index.item()), round(probs[index].item(), 4)]
})
# We saves only one token.
last_token = tokens[0]
output_ids.append(last_token)
# We've met `<|endoftext|>` token.
stopped = True if last_token == tokenizer.eos_token_id else False
# Streaming output.
if i % stream_interval == 0 or i == max_new_tokens - 1 or stopped:
tmp_output_ids = output_ids[input_echo_len:]
output = tokenizer.decode(
tmp_output_ids,
skip_special_tokens=True,
spaces_between_special_tokens=False,
clean_up_tokenization_spaces=True,
)
if debug:
yield {
"text": output,
"candidates": candidates,
"selected": selected,
"finish_reason": None,
}
else:
yield {
"text": output,
"finish_reason": None,
}
# Cause We've Ended As Lovers.
if stopped:
break
if i == max_new_tokens - 1:
finish_reason = "length"
elif stopped:
finish_reason = "stop"
else:
finish_reason = None
yield {
"text": output,
"output_ids": output_ids,
"usage": {
"prompt_tokens": input_echo_len,
"completion_tokens": i,
"total_tokens": input_echo_len + i,
},
"finish_reason": finish_reason,
}
# We come out with a clean slate.
del past_key_values, out
gc.collect()
torch.cuda.empty_cache()