matt HOFFNER commited on
Commit
5b04582
1 Parent(s): 3366fc4

chat completions

Browse files
Files changed (2) hide show
  1. dialogue.py +241 -0
  2. main.py +19 -2
dialogue.py ADDED
@@ -0,0 +1,241 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The HuggingFace Team. All rights reserved.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+ import json
17
+ import os
18
+ from dataclasses import asdict, dataclass
19
+ from pathlib import Path
20
+ from typing import Any, Dict, List, Optional, Type, TypeVar, Union
21
+
22
+ from huggingface_hub import ModelHubMixin, hf_hub_download
23
+
24
+ # Generic variable that is either ModelHubMixin or a subclass thereof
25
+ T = TypeVar("T", bound="ModelHubMixin")
26
+
27
+ TEMPLATE_FILENAME = "dialogue_template.json"
28
+ IGNORE_INDEX = -100
29
+
30
+
31
+ @dataclass
32
+ class DialogueTemplate(ModelHubMixin):
33
+ """Converts all turns of a dialogue between a user and assistant to a standardized format.
34
+
35
+ Adapted from OpenAI's ChatML (https://github.com/openai/openai-python/blob/main/chatml.md) and Vicuna (https://github.com/lm-sys/FastChat/blob/main/fastchat/conversation.py)
36
+ """
37
+
38
+ system: str
39
+ messages: List[Dict[str, str]] = None
40
+ system_token: str = "<|system|>"
41
+ user_token: str = "<|user|>"
42
+ assistant_token: str = "<|assistant|>"
43
+ end_token: str = "<|end|>"
44
+
45
+ def get_training_prompt(self) -> str:
46
+ prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
47
+ if self.messages is None:
48
+ raise ValueError("Dialogue template must have at least one message.")
49
+ for message in self.messages:
50
+ if message["role"] == "user":
51
+ prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
52
+ else:
53
+ prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
54
+ return prompt
55
+
56
+ def get_inference_prompt(self) -> str:
57
+ prompt = self.system_token + "\n" + self.system + self.end_token + "\n"
58
+ if self.messages is None:
59
+ raise ValueError("Dialogue template must have at least one message.")
60
+ for message in self.messages:
61
+ if message["role"] == "user":
62
+ prompt += self.user_token + "\n" + message["content"] + self.end_token + "\n"
63
+ else:
64
+ prompt += self.assistant_token + "\n" + message["content"] + self.end_token + "\n"
65
+ prompt += self.assistant_token
66
+ return prompt
67
+
68
+ def get_dialogue(self):
69
+ """Helper function to format the messages as an easy-to-read dialogue."""
70
+ prompt = ""
71
+ if self.messages is None:
72
+ raise ValueError("Dialogue template must have at least one message.")
73
+ for message in self.messages:
74
+ if message["role"] == "user":
75
+ prompt += "\n\nHuman: " + message["content"]
76
+ else:
77
+ prompt += "\n\nAssistant: " + message["content"]
78
+ return prompt
79
+
80
+ def get_special_tokens(self) -> List[str]:
81
+ return [self.system_token, self.user_token, self.assistant_token, self.end_token]
82
+
83
+ def copy(self):
84
+ return DialogueTemplate(
85
+ system=self.system,
86
+ messages=self.messages,
87
+ system_token=self.system_token,
88
+ user_token=self.user_token,
89
+ assistant_token=self.assistant_token,
90
+ end_token=self.end_token,
91
+ )
92
+
93
+ def to_dict(self) -> Dict[str, Any]:
94
+ return {k: v for k, v in asdict(self).items()}
95
+
96
+ @classmethod
97
+ def from_dict(cls, data):
98
+ return DialogueTemplate(
99
+ system=data["system"] if "system" in data else "",
100
+ messages=data["messages"] if "messages" in data else None,
101
+ system_token=data["system_token"] if "system_token" in data else "<|system|>",
102
+ user_token=data["user_token"] if "user_token" in data else "<|user|>",
103
+ assistant_token=data["assistant_token"] if "assistant_token" in data else "<|assistant|>",
104
+ end_token=data["end_token"] if "end_token" in data else "<|end|>",
105
+ )
106
+
107
+ def _save_pretrained(self, save_directory: Union[str, Path]) -> None:
108
+ save_directory = Path(save_directory)
109
+ save_directory.mkdir(exist_ok=True)
110
+ with open(save_directory / "dialogue_template.json", "w") as f:
111
+ json.dump(self.to_dict(), f, indent=2)
112
+
113
+ @classmethod
114
+ def _from_pretrained(
115
+ cls: Type[T],
116
+ *,
117
+ model_id: str,
118
+ revision: Optional[str],
119
+ cache_dir: Optional[Union[str, Path]],
120
+ force_download: bool,
121
+ proxies: Optional[Dict],
122
+ resume_download: bool,
123
+ local_files_only: bool,
124
+ token: Optional[Union[str, bool]],
125
+ **model_kwargs,
126
+ ) -> T:
127
+ """Loads the dialogue template from a local directory or the Huggingface Hub.
128
+
129
+ Args:
130
+ model_id (`str`):
131
+ ID of the model to load from the Huggingface Hub (e.g. `bigscience/bloom`).
132
+ revision (`str`, *optional*):
133
+ Revision of the model on the Hub. Can be a branch name, a git tag or any commit id. Defaults to the
134
+ latest commit on `main` branch.
135
+ force_download (`bool`, *optional*, defaults to `False`):
136
+ Whether to force (re-)downloading the model weights and configuration files from the Hub, overriding
137
+ the existing cache.
138
+ resume_download (`bool`, *optional*, defaults to `False`):
139
+ Whether to delete incompletely received files. Will attempt to resume the download if such a file exists.
140
+ proxies (`Dict[str, str]`, *optional*):
141
+ A dictionary of proxy servers to use by protocol or endpoint (e.g., `{'http': 'foo.bar:3128',
142
+ 'http://hostname': 'foo.bar:4012'}`).
143
+ token (`str` or `bool`, *optional*):
144
+ The token to use as HTTP bearer authorization for remote files. By default, it will use the token
145
+ cached when running `huggingface-cli login`.
146
+ cache_dir (`str`, `Path`, *optional*):
147
+ Path to the folder where cached files are stored.
148
+ local_files_only (`bool`, *optional*, defaults to `False`):
149
+ If `True`, avoid downloading the file and return the path to the local cached file if it exists.
150
+ model_kwargs:
151
+ Additional keyword arguments passed along to the [`~ModelHubMixin._from_pretrained`] method.
152
+ """
153
+ if os.path.isdir(model_id): # Can either be a local directory
154
+ print("Loading dialogue template from local directory")
155
+ template_file = os.path.join(model_id, TEMPLATE_FILENAME)
156
+ else: # Or a template on the Hub
157
+ template_file = hf_hub_download( # Download from the hub, passing same input args
158
+ repo_id=model_id,
159
+ filename=TEMPLATE_FILENAME,
160
+ revision=revision,
161
+ cache_dir=cache_dir,
162
+ force_download=force_download,
163
+ proxies=proxies,
164
+ resume_download=resume_download,
165
+ token=token,
166
+ local_files_only=local_files_only,
167
+ )
168
+
169
+ # Load template
170
+ with open(template_file, "r") as f:
171
+ data = json.load(f)
172
+ return cls.from_dict(data=data)
173
+
174
+
175
+ # A shortened version of the system message in Anthropic's HHH prompt: https://gist.github.com/jareddk/2509330f8ef3d787fc5aaac67aab5f11#file-hhh_prompt-txt
176
+ default_template = DialogueTemplate(
177
+ system="Below is a dialogue between a human user and an AI assistant. The assistant is happy to help with almost anything, and will do its best to understand exactly what is needed.",
178
+ )
179
+
180
+ # OpenAI and OpenAssistant train on few to no system messages.
181
+ # TODO: consider defining this as the `default` template
182
+ no_system_template = DialogueTemplate(
183
+ system="",
184
+ )
185
+
186
+ alpaca_template = DialogueTemplate(
187
+ system="Below is an instruction that describes a task. Write a response that appropriately completes the request.",
188
+ user_token="### Instruction:",
189
+ assistant_token="### Response:",
190
+ )
191
+
192
+ SUPPORTED_DIALOGUE_TEMPLATES = {
193
+ "default": default_template,
194
+ "no_system": no_system_template,
195
+ "alpaca": alpaca_template,
196
+ }
197
+
198
+
199
+ def get_dialogue_template(template: str) -> DialogueTemplate:
200
+ if template not in SUPPORTED_DIALOGUE_TEMPLATES.keys():
201
+ raise ValueError(f"Template {template} is not supported!")
202
+ return SUPPORTED_DIALOGUE_TEMPLATES[template].copy()
203
+
204
+
205
+ def prepare_dialogue(example, dialogue_template, is_train=True):
206
+ """Format example to single- or multi-turn dialogue."""
207
+ # TODO: make this simpler by just ensuring every dataset has a messages column
208
+ if "messages" in example.keys() and example["messages"] is not None:
209
+ dialogue_template.messages = example["messages"]
210
+ elif all(k in example.keys() for k in ("prompt", "completion")):
211
+ # Construct single-turn dialogue from prompt and completion
212
+ dialogue_template.messages = [
213
+ {"role": "user", "content": example["prompt"]},
214
+ {"role": "assistant", "content": example["completion"]},
215
+ ]
216
+ elif "prompt" in example.keys():
217
+ # Construct single-turn dialogue from prompt (inference only)
218
+ dialogue_template.messages = [
219
+ {"role": "user", "content": example["prompt"]},
220
+ ]
221
+ else:
222
+ raise ValueError(
223
+ f"Could not format example as dialogue! Require either `messages` or `[prompt, completion]` or `[prompt]` keys but found {list(example.keys())}"
224
+ )
225
+ if is_train:
226
+ example["text"] = dialogue_template.get_training_prompt()
227
+ else:
228
+ example["text"] = dialogue_template.get_inference_prompt()
229
+ return example
230
+
231
+
232
+ def mask_user_labels(tokenizer, dialogue_template, labels):
233
+ """Masks the user turns of a dialogue from the loss"""
234
+ user_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.user_token)
235
+ assistant_token_id = tokenizer.convert_tokens_to_ids(dialogue_template.assistant_token)
236
+ for idx, label_id in enumerate(labels):
237
+ if label_id == user_token_id:
238
+ current_idx = idx
239
+ while labels[current_idx] != assistant_token_id and current_idx < len(labels):
240
+ labels[current_idx] = IGNORE_INDEX
241
+ current_idx += 1
main.py CHANGED
@@ -1,3 +1,4 @@
 
1
  import fastapi
2
  import markdown
3
  import uvicorn
@@ -7,6 +8,8 @@ from fastapi.middleware.cors import CORSMiddleware
7
  from sse_starlette.sse import EventSourceResponse
8
  from pydantic import BaseModel
9
 
 
 
10
  llm = AutoModelForCausalLM.from_pretrained("NeoDim/starchat-alpha-GGML",
11
  model_file="starchat-alpha-ggml-q4_0.bin",
12
  model_type="starcoder")
@@ -112,9 +115,23 @@ async def chat(prompt = "<|user|> Write an express server with server sent event
112
 
113
  return EventSourceResponse(server_sent_events(tokens, llm))
114
 
 
 
 
 
 
 
 
 
 
 
115
  @app.post("/v1/chat/completions")
116
- async def chat(request, response_mode=None):
117
- tokens = llm.tokenize(request.messages)
 
 
 
 
118
  async def server_sent_events(chat_chunks, llm):
119
  for token in llm.generate(chat_chunks):
120
  yield llm.detokenize(token)
 
1
+ from typing import List
2
  import fastapi
3
  import markdown
4
  import uvicorn
 
8
  from sse_starlette.sse import EventSourceResponse
9
  from pydantic import BaseModel
10
 
11
+ from dialogue import DialogueTemplate
12
+
13
  llm = AutoModelForCausalLM.from_pretrained("NeoDim/starchat-alpha-GGML",
14
  model_file="starchat-alpha-ggml-q4_0.bin",
15
  model_type="starcoder")
 
115
 
116
  return EventSourceResponse(server_sent_events(tokens, llm))
117
 
118
+
119
+ class ChatCompletion(BaseModel):
120
+ role: str
121
+ content: str
122
+
123
+ class ChatCompletionRequest(BaseModel):
124
+ messages: List[ChatCompletion]
125
+
126
+ system_message = "Below is a conversation between a human user and a helpful AI coding assistant."
127
+
128
  @app.post("/v1/chat/completions")
129
+ async def chat(request: ChatCompletionRequest, response_mode=None):
130
+ dialogue_template = DialogueTemplate(
131
+ system=system_message, messages=[request.messages]
132
+ )
133
+ prompt = dialogue_template.get_inference_prompt()
134
+ tokens = llm.tokenize(prompt)
135
  async def server_sent_events(chat_chunks, llm):
136
  for token in llm.generate(chat_chunks):
137
  yield llm.detokenize(token)