File size: 12,266 Bytes
41d1bc5 15d89f9 41d1bc5 15d89f9 41d1bc5 15d89f9 41d1bc5 15d89f9 41d1bc5 15d89f9 41d1bc5 15d89f9 41d1bc5 15d89f9 41d1bc5 15d89f9 |
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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 |
from typing import List, Union, Optional, Literal
import dataclasses
from tenacity import (
retry,
stop_after_attempt, # type: ignore
wait_random_exponential, # type: ignore
)
import openai
import requests
import json
import os
from groq import Groq
MessageRole = Literal["system", "user", "assistant"]
@dataclasses.dataclass()
class Message():
role: MessageRole
content: str
def message_to_str(message: Message) -> str:
return f"{message.role}: {message.content}"
def messages_to_str(messages: List[Message]) -> str:
return "\n".join([message_to_str(message) for message in messages])
@retry(wait=wait_random_exponential(min=1, max=60), stop=stop_after_attempt(6))
def gpt_completion(
model: str,
prompt: str,
max_tokens: int = 1024,
stop_strs: Optional[List[str]] = None,
temperature: float = 0.0,
num_comps=1,
) -> Union[List[str], str]:
response = openai.Completion.create(
model=model,
prompt=prompt,
temperature=temperature,
max_tokens=max_tokens,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0,
stop=stop_strs,
n=num_comps,
)
if num_comps == 1:
return response.choices[0].text # type: ignore
return [choice.text for choice in response.choices] # type: ignore
@retry(wait=wait_random_exponential(min=1, max=180), stop=stop_after_attempt(6))
def gpt_chat(
model: str,
messages: List[Message],
max_tokens: int = 1024,
temperature: float = 0.0,
num_comps=1,
) -> Union[List[str], str]:
response = openai.ChatCompletion.create(
model=model,
messages=[dataclasses.asdict(message) for message in messages],
max_tokens=max_tokens,
temperature=temperature,
top_p=1,
frequency_penalty=0.0,
presence_penalty=0.0,
n=num_comps,
)
if num_comps == 1:
return response.choices[0].message.content # type: ignore
print("temp", temperature)
return [choice.message.content for choice in response.choices] # type: ignore
class ModelBase():
def __init__(self, name: str):
self.name = name
self.is_chat = False
def __repr__(self) -> str:
return f'{self.name}'
def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
raise NotImplementedError
def generate(self, prompt: str, max_tokens: int = 1024, stop_strs: Optional[List[str]] = None, temperature: float = 0.0, num_comps=1) -> Union[List[str], str]:
raise NotImplementedError
class GroqBase():
def __init__(self):
self.is_chat = True
self.client = Groq(
api_key=os.environ.get("GROQ_API_KEY"),
)
def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
resps = []
for i in range(num_comps):
chat_completion = self.client.chat.completions.create(
messages=[dataclasses.asdict(message) for message in messages],
model="llama3-8b-8192",
)
response_text = chat_completion.choices[0].message.content
resps.append(response_text)
if num_comps == 1:
return resps[0]
else:
return resps
class Samba():
def __init__(self):
self.is_chat = True
def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
resps = []
for i in range(num_comps):
payload = {
"inputs": [dataclasses.asdict(message) for message in messages],
"params": {
"do_sample": {"type": "bool", "value": True},
"max_tokens_allowed_in_completion": {"type": "int", "value": 500},
"min_token_capacity_for_completion": {"type": "int", "value": 2},
"temperature": {"type": "float", "value": 0.7},
"top_p": {"type": "float", "value": 0.1},
"top_k": {"type": "int", "value": 40},
"skip_special_token": {"type": "bool", "value": True},
"repetition_penalty": {"type": "float", "value": 1.15},
"stop_sequences": {"type": "list", "value": ["[INST]", "[INST]", "[/INST]", "[/INST]"]}
},
"expert": "llama3-8b"
}
url = 'https://kjddazcq2e2wzvzv.snova.ai/api/v1/chat/completion'
headers = {
"Authorization": "Basic bGlnaHRuaW5nOlUyM3pMcFlHY3dmVzRzUGFy",
"Content-Type": "application/json"
}
post_response = requests.post(url, json=payload, headers=headers, stream=True)
response_text = ""
for line in post_response.iter_lines():
if line.startswith(b"data: "):
data_str = line.decode('utf-8')[6:]
try:
line_json = json.loads(data_str)
content = line_json.get("stream_token", "")
if content:
response_text += content
except json.JSONDecodeError as e:
pass
resps.append(response_text)
if num_comps == 1:
return resps[0]
else:
return resps
class GPTChat(ModelBase):
def __init__(self, model_name: str):
self.name = model_name
self.is_chat = True
def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
return gpt_chat(self.name, messages, max_tokens, temperature, num_comps)
class GPT4(GPTChat):
def __init__(self):
super().__init__("gpt-4")
class GPT4o(GPTChat):
def __init__(self):
super().__init__("gpt-4o")
class GPT35(GPTChat):
def __init__(self):
super().__init__("gpt-3.5-turbo")
class GPTDavinci(ModelBase):
def __init__(self, model_name: str):
self.name = model_name
def generate(self, prompt: str, max_tokens: int = 1024, stop_strs: Optional[List[str]] = None, temperature: float = 0, num_comps=1) -> Union[List[str], str]:
return gpt_completion(self.name, prompt, max_tokens, stop_strs, temperature, num_comps)
class HFModelBase(ModelBase):
"""
Base for huggingface chat models
"""
def __init__(self, model_name: str, model, tokenizer, eos_token_id=None):
self.name = model_name
self.model = model
self.tokenizer = tokenizer
self.eos_token_id = eos_token_id if eos_token_id is not None else self.tokenizer.eos_token_id
self.is_chat = True
def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
# NOTE: HF does not like temp of 0.0.
if temperature < 0.0001:
temperature = 0.0001
prompt = self.prepare_prompt(messages)
outputs = self.model.generate(
prompt,
max_new_tokens=min(
max_tokens, self.model.config.max_position_embeddings),
use_cache=True,
do_sample=True,
temperature=temperature,
top_p=0.95,
eos_token_id=self.eos_token_id,
num_return_sequences=num_comps,
)
outs = self.tokenizer.batch_decode(outputs, skip_special_tokens=False)
assert isinstance(outs, list)
for i, out in enumerate(outs):
assert isinstance(out, str)
outs[i] = self.extract_output(out)
if len(outs) == 1:
return outs[0] # type: ignore
else:
return outs # type: ignore
def prepare_prompt(self, messages: List[Message]):
raise NotImplementedError
def extract_output(self, output: str) -> str:
raise NotImplementedError
class StarChat(HFModelBase):
def __init__(self):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
model = AutoModelForCausalLM.from_pretrained(
"HuggingFaceH4/starchat-beta",
torch_dtype=torch.bfloat16,
device_map="auto",
)
tokenizer = AutoTokenizer.from_pretrained(
"HuggingFaceH4/starchat-beta",
)
super().__init__("starchat", model, tokenizer, eos_token_id=49155)
def prepare_prompt(self, messages: List[Message]):
prompt = ""
for i, message in enumerate(messages):
prompt += f"<|{message.role}|>\n{message.content}\n<|end|>\n"
if i == len(messages) - 1:
prompt += "<|assistant|>\n"
return self.tokenizer.encode(prompt, return_tensors="pt").to(self.model.device)
def extract_output(self, output: str) -> str:
out = output.split("<|assistant|>")[1]
if out.endswith("<|end|>"):
out = out[:-len("<|end|>")]
return out
class CodeLlama(HFModelBase):
B_INST, E_INST = "[INST]", "[/INST]"
B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
DEFAULT_SYSTEM_PROMPT = """\
You are a helpful, respectful and honest assistant. Always answer as helpfully as possible, while being safe. Your answers should not include any harmful, unethical, racist, sexist, toxic, dangerous, or illegal content. Please ensure that your responses are socially unbiased and positive in nature.
If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information."""
def __init__(self, version: Literal["34b", "13b", "7b"] = "34b"):
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
tokenizer = AutoTokenizer.from_pretrained(
f"codellama/CodeLlama-{version}-Instruct-hf",
add_eos_token=True,
add_bos_token=True,
padding_side='left'
)
model = AutoModelForCausalLM.from_pretrained(
f"codellama/CodeLlama-{version}-Instruct-hf",
torch_dtype=torch.bfloat16,
device_map="auto",
)
super().__init__("codellama", model, tokenizer)
def prepare_prompt(self, messages: List[Message]):
if messages[0].role != "system":
messages = [
Message(role="system", content=self.DEFAULT_SYSTEM_PROMPT)
] + messages
messages = [
Message(role=messages[1].role, content=self.B_SYS +
messages[0].content + self.E_SYS + messages[1].content)
] + messages[2:]
assert all([msg.role == "user" for msg in messages[::2]]) and all(
[msg.role == "assistant" for msg in messages[1::2]]
), (
"model only supports 'system', 'user' and 'assistant' roles, "
"starting with 'system', then 'user' and alternating (u/a/u/a/u...)"
)
messages_tokens: List[int] = sum(
[
self.tokenizer.encode(
f"{self.B_INST} {(prompt.content).strip()} {self.E_INST} {(answer.content).strip()} ",
)
for prompt, answer in zip(
messages[::2],
messages[1::2],
)
],
[],
)
assert messages[-1].role == "user", f"Last message must be from user, got {messages[-1].role}"
messages_tokens += self.tokenizer.encode(
f"{self.B_INST} {(messages[-1].content).strip()} {self.E_INST}",
)
# remove eos token from last message
messages_tokens = messages_tokens[:-1]
import torch
return torch.tensor([messages_tokens]).to(self.model.device)
def extract_output(self, output: str) -> str:
out = output.split("[/INST]")[-1].split("</s>")[0].strip()
return out
|