-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
Copy pathinference.py
executable file
·207 lines (196 loc) · 7.27 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
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
import json
import random
import Shared_vars
import requests
import traceback
if Shared_vars.config.compat:
from transformers import AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(Shared_vars.config.tokenmodel)
API_ENDPOINT_URI = Shared_vars.API_ENDPOINT_URI
API_KEY = Shared_vars.API_KEY
TABBY = Shared_vars.TABBY
if TABBY:
API_ENDPOINT_URI += "v1/completions"
else:
API_ENDPOINT_URI += "completion"
def tokenize(input):
if Shared_vars.config.compat:
encoded_input = tokenizer.encode(input, return_tensors=None)
tokens = tokenizer.convert_ids_to_tokens(encoded_input)
return {"length": len(encoded_input), "tokens": tokens}
else:
if TABBY:
payload = {
"add_bos_token": "true",
"encode_special_tokens": "true",
"decode_special_tokens": "true",
"text": input,
}
request = requests.post(
API_ENDPOINT_URI.replace("completions", "token/encode"),
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
},
json=payload,
timeout=360,
)
return request.json()
else:
payload = {"content": input}
request = requests.post(
API_ENDPOINT_URI.replace("completion", "tokenize"),
json=payload,
timeout=360,
)
return {"length": len(request.json()["tokens"])}
def infer(
prmpt,
system="",
temperature=0.7,
username="",
bsysep=Shared_vars.config.llm_parameters["bsysep"],
esysep=Shared_vars.config.llm_parameters["esysep"],
modelname="",
eos="</s><s>",
beginsep=Shared_vars.config.llm_parameters["beginsep"],
endsep=Shared_vars.config.llm_parameters["endsep"],
mem=[],
few_shot="",
max_tokens=250,
stopstrings=[],
top_p=1.0,
top_k=Shared_vars.config.llm_parameters["top_k"],
min_p=0.0,
streamresp=False,
reppenalty=Shared_vars.config.llm_parameters["repetition_penalty"] if "repetition_penalty" in Shared_vars.config.llm_parameters else 1.0,
max_temp=Shared_vars.config.llm_parameters["max_temp"] if "max_temp" in Shared_vars.config.llm_parameters else 0,
min_temp=Shared_vars.config.llm_parameters["min_temp"] if "min_temp" in Shared_vars.config.llm_parameters else 0
):
content = ""
memory = mem
prompt = (
f"{bsysep}\n"
+ system
+ f"\n{esysep}\n"
+ few_shot
+ "".join(memory)
+ f"\n{beginsep} {username} {prmpt}{endsep} {modelname}"
)
# This feels wrong.
print(f"Token count: {tokenize(prompt)['length']}")
removal = 0
while (
tokenize(prompt)["length"] + max_tokens / 2 > Shared_vars.config.ctxlen
and len(memory) > 2
):
print(f"Removing old memories: Pass:{removal}")
removal += 1
memory = memory[removal:]
prompt = (
f"{bsysep}\n"
+ system
+ f"\n{esysep}\n"
+ few_shot
+ "".join(memory)
+ f"\n{beginsep} {username} {prmpt} {endsep} {modelname}"
)
stopstrings += ["</s>", "<</SYS>>", "[Inst]", "[/INST]", Shared_vars.config.llm_parameters["bsysep"], Shared_vars.config.llm_parameters["esysep"], Shared_vars.config.llm_parameters["beginsep"], Shared_vars.config.llm_parameters["endsep"]]
payload = {
"prompt": prompt,
"model": "gpt-3.5-turbo-instruct",
"max_tokens": max_tokens,
"n_predict": max_tokens,
"min_p": min_p,
"repetition_penalty": reppenalty,
"stream": True,
"seed": random.randint(
1000002406736107, 3778562406736107
), # Was acting weird without this
"top_k": top_k,
"top_p": top_p,
"stop": [beginsep] + stopstrings,
"temperature": temperature,
}
if min_temp != 0 and max_temp != 0:
payload["min_temp"] = min_temp
payload["max_temp"] = max_temp
request = requests.post(
API_ENDPOINT_URI,
headers={
"Accept": "application/json",
"Content-Type": "application/json",
"Authorization": f"Bearer {API_KEY}",
},
json=payload,
stream=True,
timeout=360,
)
if request.encoding is None:
request.encoding = "utf-8"
prevtoken = ""
repetitioncount = 0
for line in request.iter_lines(decode_unicode=True):
if line:
if TABBY:
try:
if " ".join(line.split(" ")[1:]) != "[DONE]":
if (
prevtoken
== json.loads(" ".join(line.split(" ")[1:]))["choices"][0][
"text"
]
):
repetitioncount += 1
if repetitioncount > 25:
print("Stopping loop due to repetition")
break
else:
repetitioncount = 0
prevtoken = json.loads(" ".join(line.split(" ")[1:]))["choices"][0][
"text"
]
print(
json.loads(" ".join(line.split(" ")[1:]))["choices"][0]["text"],
end="",
flush=True,
)
if streamresp:
yield json.loads(" ".join(line.split(" ")[1:]))["choices"][0][
"text"
]
content += json.loads(" ".join(line.split(" ")[1:]))["choices"][0][
"text"
]
except Exception:
pass
else:
try:
if "data" in line:
print(
json.loads(" ".join(line.split(" ")[1:]))["content"],
end="",
flush=True,
)
if (
prevtoken
== json.loads(" ".join(line.split(" ")[1:]))["content"]
):
repetitioncount += 1
if repetitioncount > 25:
print("Stopping loop due to repetition")
break
else:
repetitioncount = 0
prevtoken = json.loads(" ".join(line.split(" ")[1:]))["content"]
if streamresp:
yield json.loads(" ".join(line.split(" ")[1:]))["content"]
content += json.loads(" ".join(line.split(" ")[1:]))["content"]
except Exception:
print(traceback.format_exc())
print("")
memory.append(
f"\n{beginsep} {username} {prmpt.strip()}\n{endsep} {modelname} {content.strip()}{eos}"
)
yield [content, memory, tokenize(prompt)["length"]]