Etash Guha commited on
Commit
15d89f9
1 Parent(s): 89a8b2b

added samba

Browse files
Files changed (3) hide show
  1. app.py +1 -1
  2. generators/factory.py +22 -1
  3. generators/model.py +240 -19
app.py CHANGED
@@ -51,7 +51,7 @@ def make_args(instruction, tree_depth, tree_width, iterations):
51
 
52
  parser.add_argument("--strategy", default="mcts", help="Strategy to use")
53
  parser.add_argument("--language", default="py", help="Programming language")
54
- parser.add_argument("--model", default="gpt-4", help="Model type")
55
  parser.add_argument("--max_iters", default=iterations, help="Maximum iterations")
56
  parser.add_argument("--instruction", default=instruction, help="Instruction text")
57
  parser.add_argument("--verbose", action="store_true", help="Verbose output")
 
51
 
52
  parser.add_argument("--strategy", default="mcts", help="Strategy to use")
53
  parser.add_argument("--language", default="py", help="Programming language")
54
+ parser.add_argument("--model", default="samba", help="Model type")
55
  parser.add_argument("--max_iters", default=iterations, help="Maximum iterations")
56
  parser.add_argument("--instruction", default=instruction, help="Instruction text")
57
  parser.add_argument("--verbose", action="store_true", help="Verbose output")
generators/factory.py CHANGED
@@ -1,10 +1,17 @@
1
  from .py_generate import PyGenerator
 
 
2
  from .generator_types import Generator
3
- from .model import ModelBase, GPT4, GPT35, GPTDavinci
 
4
 
5
  def generator_factory(lang: str) -> Generator:
6
  if lang == "py" or lang == "python":
7
  return PyGenerator()
 
 
 
 
8
  else:
9
  raise ValueError(f"Invalid language for generator: {lang}")
10
 
@@ -12,8 +19,22 @@ def generator_factory(lang: str) -> Generator:
12
  def model_factory(model_name: str) -> ModelBase:
13
  if model_name == "gpt-4":
14
  return GPT4()
 
 
 
 
 
 
15
  elif model_name == "gpt-3.5-turbo-0613":
16
  return GPT35()
 
 
 
 
 
 
 
 
17
  elif model_name.startswith("text-davinci"):
18
  return GPTDavinci(model_name)
19
  else:
 
1
  from .py_generate import PyGenerator
2
+ from .rs_generate import RsGenerator
3
+ from .go_generate import GoGenerator
4
  from .generator_types import Generator
5
+ from .model import CodeLlama, ModelBase, GPT4, GPT35, StarChat, GPTDavinci, Samba, GPT4o, GroqBase
6
+
7
 
8
  def generator_factory(lang: str) -> Generator:
9
  if lang == "py" or lang == "python":
10
  return PyGenerator()
11
+ elif lang == "rs" or lang == "rust":
12
+ return RsGenerator()
13
+ elif lang == "go" or lang == "golang":
14
+ return GoGenerator()
15
  else:
16
  raise ValueError(f"Invalid language for generator: {lang}")
17
 
 
19
  def model_factory(model_name: str) -> ModelBase:
20
  if model_name == "gpt-4":
21
  return GPT4()
22
+ elif model_name == "gpt-4o":
23
+ return GPT4o()
24
+ elif model_name == "samba":
25
+ return Samba()
26
+ elif model_name == "groq":
27
+ return GroqBase()
28
  elif model_name == "gpt-3.5-turbo-0613":
29
  return GPT35()
30
+ elif model_name == "starchat":
31
+ return StarChat()
32
+ elif model_name.startswith("codellama"):
33
+ # if it has `-` in the name, version was specified
34
+ kwargs = {}
35
+ if "-" in model_name:
36
+ kwargs["version"] = model_name.split("-")[1]
37
+ return CodeLlama(**kwargs)
38
  elif model_name.startswith("text-davinci"):
39
  return GPTDavinci(model_name)
40
  else:
generators/model.py CHANGED
@@ -7,6 +7,10 @@ from tenacity import (
7
  wait_random_exponential, # type: ignore
8
  )
9
  import openai
 
 
 
 
10
 
11
  MessageRole = Literal["system", "user", "assistant"]
12
 
@@ -54,29 +58,26 @@ def gpt_completion(
54
  @retry(wait=wait_random_exponential(min=1, max=180), stop=stop_after_attempt(6))
55
  def gpt_chat(
56
  model: str,
57
- messages: List,
58
  max_tokens: int = 1024,
59
  temperature: float = 0.0,
60
  num_comps=1,
61
  ) -> Union[List[str], str]:
62
- try:
63
- response = openai.ChatCompletion.create(
64
- model=model,
65
- messages=[dataclasses.asdict(message) for message in messages],
66
- max_tokens=max_tokens,
67
- temperature=temperature,
68
- top_p=1,
69
- frequency_penalty=0.0,
70
- presence_penalty=0.0,
71
- n=num_comps,
72
- )
73
- if num_comps == 1:
74
- return response.choices[0].message.content # type: ignore
75
- return [choice.message.content for choice in response.choices] # type: ignore
76
 
77
- except Exception as e:
78
- print(f"An error occurred while calling OpenAI: {e}")
79
- raise
80
 
81
  class ModelBase():
82
  def __init__(self, name: str):
@@ -91,8 +92,78 @@ class ModelBase():
91
 
92
  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]:
93
  raise NotImplementedError
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
94
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
95
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96
  class GPTChat(ModelBase):
97
  def __init__(self, model_name: str):
98
  self.name = model_name
@@ -106,6 +177,9 @@ class GPT4(GPTChat):
106
  def __init__(self):
107
  super().__init__("gpt-4")
108
 
 
 
 
109
 
110
  class GPT35(GPTChat):
111
  def __init__(self):
@@ -117,4 +191,151 @@ class GPTDavinci(ModelBase):
117
  self.name = model_name
118
 
119
  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]:
120
- return gpt_completion(self.name, prompt, max_tokens, stop_strs, temperature, num_comps)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7
  wait_random_exponential, # type: ignore
8
  )
9
  import openai
10
+ import requests
11
+ import json
12
+ import os
13
+ from groq import Groq
14
 
15
  MessageRole = Literal["system", "user", "assistant"]
16
 
 
58
  @retry(wait=wait_random_exponential(min=1, max=180), stop=stop_after_attempt(6))
59
  def gpt_chat(
60
  model: str,
61
+ messages: List[Message],
62
  max_tokens: int = 1024,
63
  temperature: float = 0.0,
64
  num_comps=1,
65
  ) -> Union[List[str], str]:
66
+ response = openai.ChatCompletion.create(
67
+ model=model,
68
+ messages=[dataclasses.asdict(message) for message in messages],
69
+ max_tokens=max_tokens,
70
+ temperature=temperature,
71
+ top_p=1,
72
+ frequency_penalty=0.0,
73
+ presence_penalty=0.0,
74
+ n=num_comps,
75
+ )
76
+ if num_comps == 1:
77
+ return response.choices[0].message.content # type: ignore
78
+ print("temp", temperature)
79
+ return [choice.message.content for choice in response.choices] # type: ignore
80
 
 
 
 
81
 
82
  class ModelBase():
83
  def __init__(self, name: str):
 
92
 
93
  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]:
94
  raise NotImplementedError
95
+
96
+ class GroqBase():
97
+ def __init__(self):
98
+ self.is_chat = True
99
+ self.client = Groq(
100
+ api_key=os.environ.get("GROQ_API_KEY"),
101
+ )
102
+
103
+ def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
104
+ resps = []
105
+ for i in range(num_comps):
106
+ chat_completion = self.client.chat.completions.create(
107
+ messages=[dataclasses.asdict(message) for message in messages],
108
+ model="llama3-8b-8192",
109
+ )
110
 
111
+ response_text = chat_completion.choices[0].message.content
112
+ resps.append(response_text)
113
+
114
+ if num_comps == 1:
115
+ return resps[0]
116
+ else:
117
+ return resps
118
+
119
+
120
+ class Samba():
121
+ def __init__(self):
122
+ self.is_chat = True
123
+
124
+ def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
125
+ resps = []
126
+ for i in range(num_comps):
127
+ payload = {
128
+ "inputs": [dataclasses.asdict(message) for message in messages],
129
+ "params": {
130
+ "do_sample": {"type": "bool", "value": True},
131
+ "max_tokens_allowed_in_completion": {"type": "int", "value": 500},
132
+ "min_token_capacity_for_completion": {"type": "int", "value": 2},
133
+ "temperature": {"type": "float", "value": 0.7},
134
+ "top_p": {"type": "float", "value": 0.1},
135
+ "top_k": {"type": "int", "value": 40},
136
+ "skip_special_token": {"type": "bool", "value": True},
137
+ "repetition_penalty": {"type": "float", "value": 1.15},
138
+ "stop_sequences": {"type": "list", "value": ["[INST]", "[INST]", "[/INST]", "[/INST]"]}
139
+ },
140
+ "expert": "llama3-8b"
141
+ }
142
+ url = 'https://kjddazcq2e2wzvzv.snova.ai/api/v1/chat/completion'
143
+ headers = {
144
+ "Authorization": "Basic bGlnaHRuaW5nOlUyM3pMcFlHY3dmVzRzUGFy",
145
+ "Content-Type": "application/json"
146
+ }
147
+ post_response = requests.post(url, json=payload, headers=headers, stream=True)
148
 
149
+ response_text = ""
150
+ for line in post_response.iter_lines():
151
+ if line.startswith(b"data: "):
152
+ data_str = line.decode('utf-8')[6:]
153
+ try:
154
+ line_json = json.loads(data_str)
155
+ content = line_json.get("stream_token", "")
156
+ if content:
157
+ response_text += content
158
+ except json.JSONDecodeError as e:
159
+ pass
160
+ resps.append(response_text)
161
+
162
+ if num_comps == 1:
163
+ return resps[0]
164
+ else:
165
+ return resps
166
+
167
  class GPTChat(ModelBase):
168
  def __init__(self, model_name: str):
169
  self.name = model_name
 
177
  def __init__(self):
178
  super().__init__("gpt-4")
179
 
180
+ class GPT4o(GPTChat):
181
+ def __init__(self):
182
+ super().__init__("gpt-4o")
183
 
184
  class GPT35(GPTChat):
185
  def __init__(self):
 
191
  self.name = model_name
192
 
193
  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]:
194
+ return gpt_completion(self.name, prompt, max_tokens, stop_strs, temperature, num_comps)
195
+
196
+
197
+ class HFModelBase(ModelBase):
198
+ """
199
+ Base for huggingface chat models
200
+ """
201
+
202
+ def __init__(self, model_name: str, model, tokenizer, eos_token_id=None):
203
+ self.name = model_name
204
+ self.model = model
205
+ self.tokenizer = tokenizer
206
+ self.eos_token_id = eos_token_id if eos_token_id is not None else self.tokenizer.eos_token_id
207
+ self.is_chat = True
208
+
209
+ def generate_chat(self, messages: List[Message], max_tokens: int = 1024, temperature: float = 0.2, num_comps: int = 1) -> Union[List[str], str]:
210
+ # NOTE: HF does not like temp of 0.0.
211
+ if temperature < 0.0001:
212
+ temperature = 0.0001
213
+
214
+ prompt = self.prepare_prompt(messages)
215
+
216
+ outputs = self.model.generate(
217
+ prompt,
218
+ max_new_tokens=min(
219
+ max_tokens, self.model.config.max_position_embeddings),
220
+ use_cache=True,
221
+ do_sample=True,
222
+ temperature=temperature,
223
+ top_p=0.95,
224
+ eos_token_id=self.eos_token_id,
225
+ num_return_sequences=num_comps,
226
+ )
227
+
228
+ outs = self.tokenizer.batch_decode(outputs, skip_special_tokens=False)
229
+ assert isinstance(outs, list)
230
+ for i, out in enumerate(outs):
231
+ assert isinstance(out, str)
232
+ outs[i] = self.extract_output(out)
233
+
234
+ if len(outs) == 1:
235
+ return outs[0] # type: ignore
236
+ else:
237
+ return outs # type: ignore
238
+
239
+ def prepare_prompt(self, messages: List[Message]):
240
+ raise NotImplementedError
241
+
242
+ def extract_output(self, output: str) -> str:
243
+ raise NotImplementedError
244
+
245
+
246
+
247
+ class StarChat(HFModelBase):
248
+ def __init__(self):
249
+ import torch
250
+ from transformers import AutoModelForCausalLM, AutoTokenizer
251
+ model = AutoModelForCausalLM.from_pretrained(
252
+ "HuggingFaceH4/starchat-beta",
253
+ torch_dtype=torch.bfloat16,
254
+ device_map="auto",
255
+ )
256
+ tokenizer = AutoTokenizer.from_pretrained(
257
+ "HuggingFaceH4/starchat-beta",
258
+ )
259
+ super().__init__("starchat", model, tokenizer, eos_token_id=49155)
260
+
261
+ def prepare_prompt(self, messages: List[Message]):
262
+ prompt = ""
263
+ for i, message in enumerate(messages):
264
+ prompt += f"<|{message.role}|>\n{message.content}\n<|end|>\n"
265
+ if i == len(messages) - 1:
266
+ prompt += "<|assistant|>\n"
267
+
268
+ return self.tokenizer.encode(prompt, return_tensors="pt").to(self.model.device)
269
+
270
+ def extract_output(self, output: str) -> str:
271
+ out = output.split("<|assistant|>")[1]
272
+ if out.endswith("<|end|>"):
273
+ out = out[:-len("<|end|>")]
274
+
275
+ return out
276
+
277
+
278
+ class CodeLlama(HFModelBase):
279
+ B_INST, E_INST = "[INST]", "[/INST]"
280
+ B_SYS, E_SYS = "<<SYS>>\n", "\n<</SYS>>\n\n"
281
+
282
+ DEFAULT_SYSTEM_PROMPT = """\
283
+ 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.
284
+
285
+ 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."""
286
+
287
+ def __init__(self, version: Literal["34b", "13b", "7b"] = "34b"):
288
+ import torch
289
+ from transformers import AutoModelForCausalLM, AutoTokenizer
290
+ tokenizer = AutoTokenizer.from_pretrained(
291
+ f"codellama/CodeLlama-{version}-Instruct-hf",
292
+ add_eos_token=True,
293
+ add_bos_token=True,
294
+ padding_side='left'
295
+ )
296
+ model = AutoModelForCausalLM.from_pretrained(
297
+ f"codellama/CodeLlama-{version}-Instruct-hf",
298
+ torch_dtype=torch.bfloat16,
299
+ device_map="auto",
300
+ )
301
+ super().__init__("codellama", model, tokenizer)
302
+
303
+ def prepare_prompt(self, messages: List[Message]):
304
+ if messages[0].role != "system":
305
+ messages = [
306
+ Message(role="system", content=self.DEFAULT_SYSTEM_PROMPT)
307
+ ] + messages
308
+ messages = [
309
+ Message(role=messages[1].role, content=self.B_SYS +
310
+ messages[0].content + self.E_SYS + messages[1].content)
311
+ ] + messages[2:]
312
+ assert all([msg.role == "user" for msg in messages[::2]]) and all(
313
+ [msg.role == "assistant" for msg in messages[1::2]]
314
+ ), (
315
+ "model only supports 'system', 'user' and 'assistant' roles, "
316
+ "starting with 'system', then 'user' and alternating (u/a/u/a/u...)"
317
+ )
318
+ messages_tokens: List[int] = sum(
319
+ [
320
+ self.tokenizer.encode(
321
+ f"{self.B_INST} {(prompt.content).strip()} {self.E_INST} {(answer.content).strip()} ",
322
+ )
323
+ for prompt, answer in zip(
324
+ messages[::2],
325
+ messages[1::2],
326
+ )
327
+ ],
328
+ [],
329
+ )
330
+ assert messages[-1].role == "user", f"Last message must be from user, got {messages[-1].role}"
331
+ messages_tokens += self.tokenizer.encode(
332
+ f"{self.B_INST} {(messages[-1].content).strip()} {self.E_INST}",
333
+ )
334
+ # remove eos token from last message
335
+ messages_tokens = messages_tokens[:-1]
336
+ import torch
337
+ return torch.tensor([messages_tokens]).to(self.model.device)
338
+
339
+ def extract_output(self, output: str) -> str:
340
+ out = output.split("[/INST]")[-1].split("</s>")[0].strip()
341
+ return out