| 157 | |
| 158 | |
| 159 | class LocalModel(object): |
| 160 | def __init__(self, model, device_num, llama = False, tensor_parallel_size = 4, temperature=0.7, n = 200) -> None: |
| 161 | self.name = model |
| 162 | self.sampling_params = SamplingParams(temperature=temperature, n = n, max_tokens = 512) |
| 163 | #self.sampling_params = SamplingParams(temperature=0, n = 1, max_tokens = 512) |
| 164 | self.model = LLM(model, trust_remote_code = True, tensor_parallel_size= tensor_parallel_size) |
| 165 | self.tokenizer = self.model.get_tokenizer() |
| 166 | |
| 167 | def get_prompt_length(self, prompt): |
| 168 | return len(self.tokenizer(prompt).input_ids) |
| 169 | |
| 170 | |
| 171 | def format_chats(self, dialogs, pad = False): |
| 172 | B_INST, E_INST = "[INST]", "[/INST]" |
| 173 | B_SYS, E_SYS = "SYS\n", "\n<</SYS>>\n\n" |
| 174 | |
| 175 | |
| 176 | prompt_tokens = [] |
| 177 | |
| 178 | |
| 179 | for dialog in dialogs: |
| 180 | if dialog[0]["role"] == "system": |
| 181 | dialog = [ |
| 182 | { |
| 183 | "role": dialog[1]["role"], |
| 184 | "content": B_SYS |
| 185 | + dialog[0]["content"] |
| 186 | + E_SYS |
| 187 | + dialog[1]["content"], |
| 188 | } |
| 189 | ] + dialog[2:] |
| 190 | |
| 191 | assert all([msg["role"] == "user" for msg in dialog[::2]]) and all( |
| 192 | [msg["role"] == "assistant" for msg in dialog[1::2]] |
| 193 | ), ( |
| 194 | "model only supports 'system', 'user' and 'assistant' roles, " |
| 195 | "starting with 'system', then 'user' and alternating (u/a/u/a/u...)" |
| 196 | ) |
| 197 | |
| 198 | dialog_tokens = sum( |
| 199 | [ |
| 200 | [ |
| 201 | [self.tokenizer.bos_token_id] |
| 202 | + self.tokenizer( |
| 203 | f"{B_INST} {(prompt['content']).strip()} {E_INST} {(answer['content']).strip()} " |
| 204 | ).input_ids |
| 205 | + [self.tokenizer.eos_token_id] |
| 206 | ] |
| 207 | for prompt, answer in zip( |
| 208 | dialog[::2], |
| 209 | dialog[1::2], |
| 210 | ) |
| 211 | ], |
| 212 | [], |
| 213 | ) |
| 214 | assert ( |
| 215 | dialog[-1]["role"] == "user" |
| 216 | ), f"Last message must be from user, got {dialog[-1]['role']}" |
no outgoing calls
no test coverage detected