jiajunlong commited on
Commit
a1e35e6
1 Parent(s): 8320341

Delete conversion.py

Browse files
Files changed (1) hide show
  1. conversion.py +0 -496
conversion.py DELETED
@@ -1,496 +0,0 @@
1
- import dataclasses
2
- from enum import auto, Enum
3
- from typing import List, Tuple
4
-
5
-
6
- class SeparatorStyle(Enum):
7
- """Different separator style."""
8
- SINGLE = auto()
9
- TWO = auto()
10
- MPT = auto()
11
- PLAIN = auto()
12
- LLAMA_2 = auto()
13
- TINY_LLAMA = auto()
14
- QWEN_2 = auto()
15
-
16
-
17
- @dataclasses.dataclass
18
- class Conversation:
19
- """A class that keeps all conversation history."""
20
- system: str
21
- roles: List[str]
22
- messages: List[List[str]]
23
- offset: int
24
- sep_style: SeparatorStyle = SeparatorStyle.SINGLE
25
- sep: str = "###"
26
- sep2: str = None
27
- version: str = "Unknown"
28
-
29
- skip_next: bool = False
30
-
31
- def get_prompt(self):
32
- messages = self.messages
33
- if len(messages) > 0 and type(messages[0][1]) is tuple:
34
- messages = self.messages.copy()
35
- init_role, init_msg = messages[0].copy()
36
- init_msg = init_msg[0].replace("<image>", "").strip()
37
- if 'mmtag' in self.version:
38
- messages[0] = (init_role, init_msg)
39
- messages.insert(0, (self.roles[0], "<Image><image></Image>"))
40
- messages.insert(1, (self.roles[1], "Received."))
41
- else:
42
- messages[0] = (init_role, "<image>\n" + init_msg)
43
-
44
- if self.sep_style == SeparatorStyle.SINGLE:
45
- ret = self.system + self.sep
46
- for role, message in messages:
47
- if message:
48
- if type(message) is tuple:
49
- message, _, _ = message
50
- ret += role + ": " + message + self.sep
51
- else:
52
- ret += role + ":"
53
- elif self.sep_style == SeparatorStyle.TWO:
54
- seps = [self.sep, self.sep2]
55
- ret = self.system + seps[0]
56
- for i, (role, message) in enumerate(messages):
57
- if message:
58
- if type(message) is tuple:
59
- message, _, _ = message
60
- ret += role + ": " + message + seps[i % 2]
61
- else:
62
- ret += role + ":"
63
- elif self.sep_style == SeparatorStyle.MPT:
64
- ret = self.system + self.sep
65
- for role, message in messages:
66
- if message:
67
- if type(message) is tuple:
68
- message, _, _ = message
69
- ret += role + message + self.sep
70
- else:
71
- ret += role
72
- elif self.sep_style == SeparatorStyle.LLAMA_2:
73
- wrap_sys = lambda msg: f"<<SYS>>\n{msg}\n<</SYS>>\n\n" if len(msg) > 0 else msg
74
- wrap_inst = lambda msg: f"[INST] {msg} [/INST]"
75
- ret = ""
76
-
77
- for i, (role, message) in enumerate(messages):
78
- if i == 0:
79
- assert message, "first message should not be none"
80
- assert role == self.roles[0], "first message should come from user"
81
- if message:
82
- if type(message) is tuple:
83
- message, _, _ = message
84
- if i == 0: message = wrap_sys(self.system) + message
85
- if i % 2 == 0:
86
- message = wrap_inst(message)
87
- ret += self.sep + message
88
- else:
89
- ret += " " + message + " " + self.sep2
90
- else:
91
- ret += ""
92
- ret = ret.lstrip(self.sep)
93
- elif self.sep_style == SeparatorStyle.TINY_LLAMA:
94
- sep = "</s>"
95
- wrap_sys = lambda msg: f"<|system|>\n{msg}\n"
96
- wrap_user = lambda msg: f"<|user|>\n{msg}\n"
97
- wrap_assistant = lambda msg: f"<|assistant|>\n{msg}"
98
- ret = ""
99
-
100
- for i, (role, message) in enumerate(messages):
101
- if i == 0:
102
- assert message, "first message should not be none"
103
- assert role == self.roles[0], "first message should come from user"
104
- if message:
105
- if type(message) is tuple:
106
- message, _, _ = message
107
- if i % 2 == 0:
108
- message = wrap_user(message)
109
- if i == 0:
110
- message = wrap_sys(self.system) + message
111
- ret += self.sep + message
112
- else:
113
- message = wrap_assistant(message) + self.sep2
114
- ret += message
115
- else:
116
- ret += "<|assistant|>\n"
117
- ret = ret.lstrip(self.sep)
118
- elif self.sep_style == SeparatorStyle.QWEN_2:
119
- ret = self.system + self.sep
120
- for role, message in messages:
121
- if message:
122
- if type(message) is tuple:
123
- message, _, _ = message
124
- ret += role + message + self.sep
125
- else:
126
- ret += role
127
- elif self.sep_style == SeparatorStyle.PLAIN:
128
- seps = [self.sep, self.sep2]
129
- ret = self.system
130
- for i, (role, message) in enumerate(messages):
131
- if message:
132
- if type(message) is tuple:
133
- message, _, _ = message
134
- ret += message + seps[i % 2]
135
- else:
136
- ret += ""
137
- else:
138
- raise ValueError(f"Invalid style: {self.sep_style}")
139
-
140
- return ret
141
-
142
- def append_message(self, role, message):
143
- self.messages.append([role, message])
144
-
145
- def get_images(self, return_pil=False):
146
- images = []
147
- for i, (role, msg) in enumerate(self.messages[self.offset:]):
148
- if i % 2 == 0:
149
- if type(msg) is tuple:
150
- import base64
151
- from io import BytesIO
152
- from PIL import Image
153
- msg, image, image_process_mode = msg
154
- if image_process_mode == "Pad":
155
- def expand2square(pil_img, background_color=(122, 116, 104)):
156
- width, height = pil_img.size
157
- if width == height:
158
- return pil_img
159
- elif width > height:
160
- result = Image.new(pil_img.mode, (width, width), background_color)
161
- result.paste(pil_img, (0, (width - height) // 2))
162
- return result
163
- else:
164
- result = Image.new(pil_img.mode, (height, height), background_color)
165
- result.paste(pil_img, ((height - width) // 2, 0))
166
- return result
167
- image = expand2square(image)
168
- elif image_process_mode in ["Default", "Crop"]:
169
- pass
170
- elif image_process_mode == "Resize":
171
- image = image.resize((336, 336))
172
- else:
173
- raise ValueError(f"Invalid image_process_mode: {image_process_mode}")
174
- max_hw, min_hw = max(image.size), min(image.size)
175
- aspect_ratio = max_hw / min_hw
176
- max_len, min_len = 800, 400
177
- shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
178
- longest_edge = int(shortest_edge * aspect_ratio)
179
- W, H = image.size
180
- if longest_edge != max(image.size):
181
- if H > W:
182
- H, W = longest_edge, shortest_edge
183
- else:
184
- H, W = shortest_edge, longest_edge
185
- image = image.resize((W, H))
186
- if return_pil:
187
- images.append(image)
188
- else:
189
- buffered = BytesIO()
190
- image.save(buffered, format="PNG")
191
- img_b64_str = base64.b64encode(buffered.getvalue()).decode()
192
- images.append(img_b64_str)
193
- return images
194
-
195
- def to_gradio_chatbot(self):
196
- ret = []
197
- for i, (role, msg) in enumerate(self.messages[self.offset:]):
198
- if i % 2 == 0:
199
- if type(msg) is tuple:
200
- import base64
201
- from io import BytesIO
202
- msg, image, image_process_mode = msg
203
- max_hw, min_hw = max(image.size), min(image.size)
204
- aspect_ratio = max_hw / min_hw
205
- max_len, min_len = 800, 400
206
- shortest_edge = int(min(max_len / aspect_ratio, min_len, min_hw))
207
- longest_edge = int(shortest_edge * aspect_ratio)
208
- W, H = image.size
209
- if H > W:
210
- H, W = longest_edge, shortest_edge
211
- else:
212
- H, W = shortest_edge, longest_edge
213
- image = image.resize((W, H))
214
- buffered = BytesIO()
215
- image.save(buffered, format="JPEG")
216
- img_b64_str = base64.b64encode(buffered.getvalue()).decode()
217
- img_str = f'<img src="data:image/png;base64,{img_b64_str}" alt="user upload image" />'
218
- msg = img_str + msg.replace('<image>', '').strip()
219
- ret.append([msg, None])
220
- else:
221
- ret.append([msg, None])
222
- else:
223
- ret[-1][-1] = msg
224
- return ret
225
-
226
- def copy(self):
227
- return Conversation(
228
- system=self.system,
229
- roles=self.roles,
230
- messages=[[x, y] for x, y in self.messages],
231
- offset=self.offset,
232
- sep_style=self.sep_style,
233
- sep=self.sep,
234
- sep2=self.sep2,
235
- version=self.version)
236
-
237
- def dict(self):
238
- if len(self.get_images()) > 0:
239
- return {
240
- "system": self.system,
241
- "roles": self.roles,
242
- "messages": [[x, y[0] if type(y) is tuple else y] for x, y in self.messages],
243
- "offset": self.offset,
244
- "sep": self.sep,
245
- "sep2": self.sep2,
246
- }
247
- return {
248
- "system": self.system,
249
- "roles": self.roles,
250
- "messages": self.messages,
251
- "offset": self.offset,
252
- "sep": self.sep,
253
- "sep2": self.sep2,
254
- }
255
-
256
-
257
- conv_vicuna_v0 = Conversation(
258
- system="A chat between a curious human and an artificial intelligence assistant. "
259
- "The assistant gives helpful, detailed, and polite answers to the human's questions.",
260
- roles=("Human", "Assistant"),
261
- messages=(
262
- ("Human", "What are the key differences between renewable and non-renewable energy sources?"),
263
- ("Assistant",
264
- "Renewable energy sources are those that can be replenished naturally in a relatively "
265
- "short amount of time, such as solar, wind, hydro, geothermal, and biomass. "
266
- "Non-renewable energy sources, on the other hand, are finite and will eventually be "
267
- "depleted, such as coal, oil, and natural gas. Here are some key differences between "
268
- "renewable and non-renewable energy sources:\n"
269
- "1. Availability: Renewable energy sources are virtually inexhaustible, while non-renewable "
270
- "energy sources are finite and will eventually run out.\n"
271
- "2. Environmental impact: Renewable energy sources have a much lower environmental impact "
272
- "than non-renewable sources, which can lead to air and water pollution, greenhouse gas emissions, "
273
- "and other negative effects.\n"
274
- "3. Cost: Renewable energy sources can be more expensive to initially set up, but they typically "
275
- "have lower operational costs than non-renewable sources.\n"
276
- "4. Reliability: Renewable energy sources are often more reliable and can be used in more remote "
277
- "locations than non-renewable sources.\n"
278
- "5. Flexibility: Renewable energy sources are often more flexible and can be adapted to different "
279
- "situations and needs, while non-renewable sources are more rigid and inflexible.\n"
280
- "6. Sustainability: Renewable energy sources are more sustainable over the long term, while "
281
- "non-renewable sources are not, and their depletion can lead to economic and social instability.\n")
282
- ),
283
- offset=2,
284
- sep_style=SeparatorStyle.SINGLE,
285
- sep="###",
286
- )
287
-
288
- conv_vicuna_v1 = Conversation(
289
- system="A chat between a curious user and an artificial intelligence assistant. "
290
- "The assistant gives helpful, detailed, and polite answers to the user's questions.",
291
- roles=("USER", "ASSISTANT"),
292
- version="v1",
293
- messages=(),
294
- offset=0,
295
- sep_style=SeparatorStyle.TWO,
296
- sep=" ",
297
- sep2="</s>",
298
- )
299
-
300
- conv_llama_2 = Conversation(
301
- system="""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.
302
-
303
- 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.""",
304
- roles=("USER", "ASSISTANT"),
305
- version="llama_v2",
306
- messages=(),
307
- offset=0,
308
- sep_style=SeparatorStyle.LLAMA_2,
309
- sep="<s>",
310
- sep2="</s>",
311
- )
312
-
313
- conv_llava_llama_2 = Conversation(
314
- system="You are a helpful language and vision assistant. "
315
- "You are able to understand the visual content that the user provides, "
316
- "and assist the user with a variety of tasks using natural language.",
317
- roles=("USER", "ASSISTANT"),
318
- version="llama_v2",
319
- messages=(),
320
- offset=0,
321
- sep_style=SeparatorStyle.LLAMA_2,
322
- sep="<s>",
323
- sep2="</s>",
324
- )
325
-
326
- conv_tiny_llava_tiny_llama = Conversation(
327
- system="You are a helpful language and vision assistant. "
328
- "You are able to understand the visual content that the user provides, "
329
- "and assist the user with a variety of tasks using natural language.",
330
- roles=("USER", "ASSISTANT"),
331
- version="tiny_llama",
332
- messages=(),
333
- offset=0,
334
- sep_style=SeparatorStyle.TINY_LLAMA,
335
- sep="<s>",
336
- sep2="</s>"
337
- )
338
-
339
-
340
- conv_mpt = Conversation(
341
- system="""<|im_start|>system
342
- A conversation between a user and an LLM-based AI assistant. The assistant gives helpful and honest answers.""",
343
- roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
344
- version="mpt",
345
- messages=(),
346
- offset=0,
347
- sep_style=SeparatorStyle.MPT,
348
- sep="<|im_end|>",
349
- )
350
-
351
- conv_llava_plain = Conversation(
352
- system="",
353
- roles=("", ""),
354
- messages=(
355
- ),
356
- version='plain',
357
- offset=0,
358
- sep_style=SeparatorStyle.PLAIN,
359
- sep="\n",
360
- )
361
-
362
- conv_llava_v0 = Conversation(
363
- system="A chat between a curious human and an artificial intelligence assistant. "
364
- "The assistant gives helpful, detailed, and polite answers to the human's questions.",
365
- roles=("Human", "Assistant"),
366
- messages=(
367
- ),
368
- offset=0,
369
- sep_style=SeparatorStyle.SINGLE,
370
- sep="###",
371
- )
372
-
373
- conv_llava_v0_mmtag = Conversation(
374
- system="A chat between a curious user and an artificial intelligence assistant. "
375
- "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
376
- "The visual content will be provided with the following format: <Image>visual content</Image>.",
377
- roles=("Human", "Assistant"),
378
- messages=(
379
- ),
380
- offset=0,
381
- sep_style=SeparatorStyle.SINGLE,
382
- sep="###",
383
- version="v0_mmtag",
384
- )
385
-
386
- conv_llava_v1 = Conversation(
387
- system="A chat between a curious human and an artificial intelligence assistant. "
388
- "The assistant gives helpful, detailed, and polite answers to the human's questions.",
389
- roles=("USER", "ASSISTANT"),
390
- version="v1",
391
- messages=(),
392
- offset=0,
393
- sep_style=SeparatorStyle.TWO,
394
- sep=" ",
395
- sep2="</s>",
396
- )
397
-
398
- conv_llava_v1_mmtag = Conversation(
399
- system="A chat between a curious user and an artificial intelligence assistant. "
400
- "The assistant is able to understand the visual content that the user provides, and assist the user with a variety of tasks using natural language."
401
- "The visual content will be provided with the following format: <Image>visual content</Image>.",
402
- roles=("USER", "ASSISTANT"),
403
- messages=(),
404
- offset=0,
405
- sep_style=SeparatorStyle.TWO,
406
- sep=" ",
407
- sep2="</s>",
408
- version="v1_mmtag",
409
- )
410
-
411
- conv_phi_v0 = Conversation(
412
- system="A chat between a curious user and an artificial intelligence assistant. "
413
- "The assistant gives helpful, detailed, and polite answers to the user's questions.",
414
- roles=("USER", "ASSISTANT"),
415
- version="phi",
416
- messages=(),
417
- offset=0,
418
- sep_style=SeparatorStyle.TWO,
419
- sep=" ",
420
- sep2="<|endoftext|>",
421
- )
422
-
423
- conv_stablelm = Conversation(
424
- system="A chat between a curious user and an artificial intelligence assistant. "
425
- "The assistant gives helpful, detailed, and polite answers to the user's questions.",
426
- roles=("USER", "ASSISTANT"),
427
- version="stablelm",
428
- messages=(),
429
- offset=0,
430
- sep_style=SeparatorStyle.TWO,
431
- sep=" ",
432
- sep2="<|endoftext|>",
433
- )
434
-
435
- conv_mistral_instruct = Conversation(
436
- system="",
437
- roles=("USER", "ASSISTANT"),
438
- version="llama_v2",
439
- messages=(),
440
- offset=0,
441
- sep_style=SeparatorStyle.LLAMA_2,
442
- sep="",
443
- sep2="</s>",
444
- )
445
-
446
- conv_chatml_direct = Conversation(
447
- system="""<|im_start|>system
448
- Answer the questions.""",
449
- roles=("<|im_start|>user\n", "<|im_start|>assistant\n"),
450
- version="mpt",
451
- messages=(),
452
- offset=0,
453
- sep_style=SeparatorStyle.MPT,
454
- sep="<|im_end|>",
455
- )
456
-
457
- conv_qwen2 = Conversation(
458
- system="<|im_start|>system\nYou are a helpful assistant",
459
- roles=("<im_start>user\n", "<im_start>assistant\n"),
460
- version="mpt",
461
- messages=(),
462
- offset=0,
463
- sep_style=SeparatorStyle.MPT,
464
- sep="<im_end>"
465
- )
466
-
467
- default_conversation = conv_phi_v0
468
- conv_templates = {
469
- "default": conv_vicuna_v0,
470
- "v0": conv_vicuna_v0,
471
- "v1": conv_vicuna_v1,
472
- "vicuna_v1": conv_vicuna_v1,
473
- "llama_2": conv_llama_2,
474
-
475
- "plain": conv_llava_plain,
476
- "v0_plain": conv_llava_plain,
477
- "llava_v0": conv_llava_v0,
478
- "v0_mmtag": conv_llava_v0_mmtag,
479
- "llava_v1": conv_llava_v1,
480
- "v1_mmtag": conv_llava_v1_mmtag,
481
- "llava_llama_2": conv_llava_llama_2,
482
-
483
- "mpt": conv_mpt,
484
-
485
- "tiny_llama": conv_tiny_llava_tiny_llama,
486
- "phi": conv_phi_v0,
487
-
488
- # added by llava-1.6
489
- "mistral_instruct": conv_mistral_instruct,
490
- "chatml_direct": conv_chatml_direct,
491
- "mistral_direct": conv_chatml_direct,
492
- }
493
-
494
-
495
- if __name__ == "__main__":
496
- print(default_conversation.get_prompt())