model.py 23.5 KB
Newer Older
lvhan028's avatar
lvhan028 committed
1
# Copyright (c) OpenMMLab. All rights reserved.
Lyu Han's avatar
Lyu Han committed
2
import dataclasses
AllentDan's avatar
AllentDan committed
3
4
5
from abc import abstractmethod
from typing import List

lvhan028's avatar
lvhan028 committed
6
7
from mmengine import Registry

lvhan028's avatar
lvhan028 committed
8
MODELS = Registry('model', locations=['lmdeploy.model'])
lvhan028's avatar
lvhan028 committed
9
10


Lyu Han's avatar
Lyu Han committed
11
12
13
14
15
16
17
18
19
@dataclasses.dataclass
class SamplingParam:
    top_p: float = 0.8
    top_k: float = None
    temperature: float = 0.8
    repetition_penalty: float = 1.0


@MODELS.register_module(name='internlm')
20
@MODELS.register_module(name='llama')
Lyu Han's avatar
Lyu Han committed
21
@MODELS.register_module(name='base')
22
23
24
class BaseModel:
    """Base model."""

25
26
27
28
29
30
    def __init__(self,
                 session_len=2048,
                 top_p=0.8,
                 top_k=None,
                 temperature=0.8,
                 repetition_penalty=1.0,
Lyu Han's avatar
Lyu Han committed
31
                 capability='chat',
32
                 stop_words=None,
33
34
35
36
37
38
                 **kwargs):
        self.session_len = session_len
        self.top_p = top_p
        self.top_k = top_k
        self.temperature = temperature
        self.repetition_penalty = repetition_penalty
39
        self.stop_words = stop_words
Lyu Han's avatar
Lyu Han committed
40
        self.capability = capability
41

Lyu Han's avatar
Lyu Han committed
42
    def get_prompt(self, prompt, sequence_start=True):
43
44
45
46
47
48
49
50
51
52
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            prompt (str): user's input prompt
            sequence_start (bool): indicator for the first round chat of a
               session sequence
        Returns:
            str: the concatenated prompt
        """
Lyu Han's avatar
Lyu Han committed
53
54
55
56
57
58
59
        if self.capability == 'completion':
            return prompt
        else:
            return self.decorate_prompt(prompt, sequence_start)

    @abstractmethod
    def decorate_prompt(self, prompt, sequence_start):
Lyu Han's avatar
Lyu Han committed
60
        return prompt
61

AllentDan's avatar
AllentDan committed
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
    @staticmethod
    def _translate_messages(messages: List):
        """Translate messages into system, user speaking list, assistant
        speaking list.

        Args:
            messages (List): chat history
        Returns:
            Turple: consists of system (str), users (List[str]),
                assistants (List[str])
        """
        system = None
        users = []
        assistants = []
        assert isinstance(messages, List)
        for message in messages:
            msg_role = message['role']
            if msg_role == 'system':
                system = message['content']
            elif msg_role == 'user':
                users.append(message['content'])
            elif msg_role == 'assistant':
                assistants.append(message['content'])
            else:
                raise ValueError(f'Unknown role: {msg_role}')
        assistants.append(None)
        return system, users, assistants

    @abstractmethod
    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template. When messages arg is a string, return
        self.get_prompt(messages). When messages arg is a chat history, return
        translated prompt from chat history.

        Args:
            messages (str | List): user's input prompt
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages)
        # chat history processing in derived classes

Lyu Han's avatar
Lyu Han committed
106
107
108
109
110
111
112
    @property
    def sampling_param(self):
        return SamplingParam(top_p=self.top_p,
                             top_k=self.top_k,
                             temperature=self.temperature,
                             repetition_penalty=self.repetition_penalty)

113

lvhan028's avatar
lvhan028 committed
114
@MODELS.register_module(name='vicuna')
115
class Vicuna(BaseModel):
lvhan028's avatar
lvhan028 committed
116
    """Chat template of vicuna model."""
lvhan028's avatar
lvhan028 committed
117

118
119
120
121
122
123
124
125
126
127
    def __init__(
            self,
            system="""A chat between a curious user and an artificial intelligence assistant. The assistant gives helpful, detailed, and polite answers to the user's questions. """,  # noqa: E501
            user='USER',
            assistant='ASSISTANT',
            **kwargs):
        super().__init__(**kwargs)
        self.system = system
        self.user = user
        self.assistant = assistant
lvhan028's avatar
lvhan028 committed
128

Lyu Han's avatar
Lyu Han committed
129
    def decorate_prompt(self, prompt, sequence_start=True):
lvhan028's avatar
lvhan028 committed
130
131
132
133
134
135
136
137
138
139
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            prompt (str): user's input prompt
            sequence_start (bool): indicator for the first round chat of a
               session sequence
        Returns:
            str: the concatenated prompt
        """
Lyu Han's avatar
Lyu Han committed
140
141
        assert self.capability == 'chat', \
            f'{type(self).__name__} has no capability of {self.capability}'
lvhan028's avatar
lvhan028 committed
142
        if sequence_start:
AllentDan's avatar
AllentDan committed
143
            return f'{self.system} {self.user}: {prompt} {self.assistant}: '
lvhan028's avatar
lvhan028 committed
144
        else:
AllentDan's avatar
AllentDan committed
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
            return f'</s>{self.user}: {prompt} {self.assistant}: '

    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            messages (str | List): user's input prompt
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages, sequence_start)
        system, users, assistants = self._translate_messages(messages)
        system = self.system if not system else system
        ret = system + ' '
        for user, assistant in zip(users, assistants):
            if assistant:
                ret += f'{self.user}: {user} {self.assistant}: {assistant}</s>'
            else:
                ret += f'{self.user}: {user} {self.assistant}: '
        return ret
lvhan028's avatar
lvhan028 committed
167
168


Lyu Han's avatar
Lyu Han committed
169
@MODELS.register_module(name='internlm-chat')
170
171
@MODELS.register_module(name='internlm-chat-7b')
class InternLMChat7B(BaseModel):
lvhan028's avatar
lvhan028 committed
172
    """Chat template of InternLM model."""
lvhan028's avatar
lvhan028 committed
173

174
175
176
177
178
179
180
181
182
183
184
    def __init__(
            self,
            system='<|System|>',
            meta_instruction="""You are an AI assistant whose name is InternLM (书生·浦语).
- InternLM (书生·浦语) is a conversational language model that is developed by Shanghai AI Laboratory (上海人工智能实验室). It is designed to be helpful, honest, and harmless.
- InternLM (书生·浦语) can understand and communicate fluently in the language chosen by the user such as English and 中文.
""",  # noqa: E501
            user='<|User|>',
            eoh='',
            eoa='<eoa>',
            assistant='<|Bot|>',
185
            stop_words=['<eoa>'],
186
            **kwargs):
187
188
        super().__init__(**kwargs)
        self.system = system
189
        self.meta_instruction = meta_instruction
190
191
192
193
        self.user = user
        self.eoh = eoh
        self.eoa = eoa
        self.assistant = assistant
194
        self.stop_words = stop_words
lvhan028's avatar
lvhan028 committed
195

Lyu Han's avatar
Lyu Han committed
196
    def decorate_prompt(self, prompt, sequence_start=True):
lvhan028's avatar
lvhan028 committed
197
198
199
200
201
202
203
204
205
206
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            prompt (str): user's input prompt
            sequence_start (bool): indicator for the first round chat of a
               session sequence
        Returns:
            str: the concatenated prompt
        """
Lyu Han's avatar
Lyu Han committed
207
208
        assert self.capability == 'chat', \
            f'{type(self).__name__} has no capability of {self.capability}'
lvhan028's avatar
lvhan028 committed
209
        if sequence_start:
210
211
            return f'<BOS>{self.system}:{self.meta_instruction}\n' \
                   f'{self.user}:{prompt}{self.eoh}\n' \
lvhan028's avatar
lvhan028 committed
212
213
                   f'{self.assistant}:'
        else:
214
215
            return f'\n{self.user}:{prompt}{self.eoh}\n' \
                   f'{self.assistant}:'
lvhan028's avatar
lvhan028 committed
216

AllentDan's avatar
AllentDan committed
217
218
219
220
221
222
223
224
225
226
227
228
    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            messages (str | List): user's input prompt
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages, sequence_start)
        system, users, assistants = self._translate_messages(messages)
229
230
        system = self.meta_instruction if not system else system
        ret = f'<BOS>{self.system}:{system}\n'
AllentDan's avatar
AllentDan committed
231
232
233
        for user, assistant in zip(users, assistants):
            if assistant:
                ret += f'{self.user}:{user}{self.eoh}\n{self.assistant}:' \
Lyu Han's avatar
Lyu Han committed
234
                       f'{assistant}{self.eoa}\n'
AllentDan's avatar
AllentDan committed
235
236
237
238
            else:
                ret += f'{self.user}:{user}{self.eoh}\n{self.assistant}:'
        return ret

239

Lyu Han's avatar
Lyu Han committed
240
@MODELS.register_module(name='internlm-chat-20b')
241
242
@MODELS.register_module(name='internlm-chat-7b-8k')
class InternLMChat7B8K(InternLMChat7B):
Lyu Han's avatar
Lyu Han committed
243
244
    """Chat template and generation parameters of InternLM-Chat-7B-8K and
    InternLM-Chat-20B models."""
245

246
247
248
    def __init__(self, session_len=8192, **kwargs):
        super(InternLMChat7B8K, self).__init__(**kwargs)
        self.session_len = session_len
lvhan028's avatar
lvhan028 committed
249
250


Lyu Han's avatar
Lyu Han committed
251
252
253
254
255
256
257
258
259
260
@MODELS.register_module(name='internlm-20b')
class InternLMBaseModel20B(BaseModel):
    """Generation parameters of InternLM-20B-Base model."""

    def __init__(self, session_len=4096, capability='completion', **kwargs):
        super().__init__(session_len=session_len,
                         capability=capability,
                         **kwargs)


261
262
@MODELS.register_module(name='baichuan-7b')
class Baichuan7B(BaseModel):
Lyu Han's avatar
Lyu Han committed
263
    """Generation parameters of Baichuan-7B base model."""
264

265
266
267
268
269
    def __init__(self, repetition_penalty=1.1, **kwargs):
        super().__init__(**kwargs)
        self.repetition_penalty = repetition_penalty


Lyu Han's avatar
Lyu Han committed
270
271
@MODELS.register_module(name='baichuan2-7b')
class Baichuan2_7B(BaseModel):
Lyu Han's avatar
Lyu Han committed
272
273
    """Chat template and generation parameters of Baichuan2-7B-Base and
    Baichuan2-7B-Chat models."""
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288

    def __init__(self,
                 temperature=0.3,
                 top_k=5,
                 top_p=0.85,
                 repetition_penalty=1.05,
                 **kwargs):
        super().__init__(temperature=temperature,
                         top_k=top_k,
                         top_p=top_p,
                         repetition_penalty=repetition_penalty,
                         **kwargs)
        self.user_token = '<reserved_106>'  # id = 195
        self.assistant_token = '<reserved_107>'  # id = 196

Lyu Han's avatar
Lyu Han committed
289
    def decorate_prompt(self, prompt, sequence_start=True):
290
291
292
293
294
295
296
297
298
299
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            prompt (str): user's input prompt
            sequence_start (bool): indicator for the first round chat of a
               session sequence
        Returns:
            str: the concatenated prompt
        """
Lyu Han's avatar
Lyu Han committed
300
301
        assert self.capability == 'chat', \
            f'{type(self).__name__} has no capability of {self.capability}'
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
        return f'{self.user_token}{prompt}{self.assistant_token}'

    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            messages (str | List): user's input prompt
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages, sequence_start)
        system, users, assistants = self._translate_messages(messages)
        ret = ''
        for user, assistant in zip(users, assistants):
            ret += f'{self.user_token}{user}{self.assistant_token}'
            if assistant:
                ret += f'{assistant}'
        return ret


324
325
326
327
328
329
@MODELS.register_module(name='puyu')
class Puyu(BaseModel):
    """Chat template of puyu model.This is only for internal usage in Shanghai
    AI Laboratory."""

    def __init__(self,
liukuikun's avatar
liukuikun committed
330
                 meta_instruction='',
Lyu Han's avatar
Lyu Han committed
331
                 system='',
332
                 eosys='',
liukuikun's avatar
liukuikun committed
333
334
335
336
                 user='',
                 eoh='',
                 assistant='',
                 eoa='',
337
                 stop_words=None,
338
339
                 **kwargs):
        super().__init__(**kwargs)
liukuikun's avatar
liukuikun committed
340
341
        self.meta_instruction = meta_instruction
        self.system = system
342
343
        self.user = user
        self.assistant = assistant
344
        self.stop_words = stop_words
liukuikun's avatar
liukuikun committed
345
346
347
        self.eosys = eosys
        self.eoh = eoh
        self.eoa = eoa
348

Lyu Han's avatar
Lyu Han committed
349
350
351
    def decorate_prompt(self, prompt, sequence_start=True):
        assert self.capability == 'chat', \
            f'{type(self).__name__} has no capability of {self.capability}'
352
        if sequence_start:
liukuikun's avatar
liukuikun committed
353
354
            return f'<BOS>{self.system}{self.meta_instruction}{self.eosys}' \
                   f'{self.user}{prompt}{self.eoh}' \
355
356
                   f'{self.assistant}'
        else:
liukuikun's avatar
liukuikun committed
357
            return f'{self.eoa}{self.user}{prompt}{self.eoh}{self.assistant}'
358

359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            messages (str | List): user's input prompt
            sequence_start (bool): flag to start the sequence
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages, sequence_start)
        system, users, assistants = self._translate_messages(messages)
        system = self.system if not system else system
        ret = f'<BOS>{system}{self.meta_instruction}{self.eosys}'
        for user, assistant in zip(users, assistants):
            if assistant:
liukuikun's avatar
liukuikun committed
376
377
                ret += f'{self.user}{user}{self.eoh}{self.assistant}' \
                       f'{assistant}{self.eoa}'
378
            else:
liukuikun's avatar
liukuikun committed
379
                ret += f'{self.user}{user}{self.eoh}{self.assistant}'
380
381
        return ret

382

q.yao's avatar
q.yao committed
383
@MODELS.register_module(name='llama2')
384
class Llama2(BaseModel):
q.yao's avatar
q.yao committed
385
386
    """Chat template of LLaMA2 model."""

387
388
389
390
391
392
    def __init__(
            self,
            b_inst='[INST]',
            e_inst='[/INST]',
            b_sys='<<SYS>>\n',
            e_sys='\n<</SYS>>\n\n',
Lyu Han's avatar
Lyu Han committed
393
            system="""\
q.yao's avatar
q.yao committed
394
395
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.

396
397
398
399
400
401
402
403
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.""",  # noqa: E501
            session_len=4096,
            **kwargs):
        super().__init__(**kwargs)
        self.b_inst = b_inst
        self.e_inst = e_inst
        self.b_sys = b_sys
        self.e_sys = e_sys
Lyu Han's avatar
Lyu Han committed
404
        self.default_sys_prompt = system
405
        self.session_len = session_len
q.yao's avatar
q.yao committed
406

Lyu Han's avatar
Lyu Han committed
407
    def decorate_prompt(self, prompt, sequence_start=True):
q.yao's avatar
q.yao committed
408
409
410
411
412
413
414
415
416
417
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            prompt (str): user's input prompt
            sequence_start (bool): indicator for the first round chat of a
               session sequence
        Returns:
            str: the concatenated prompt
        """
Lyu Han's avatar
Lyu Han committed
418
419
        assert self.capability == 'chat', \
            f'{type(self).__name__} has no capability of {self.capability}'
q.yao's avatar
q.yao committed
420
421
422
423
424
425
426
        if sequence_start:
            return f'<BOS>{self.b_inst} ' \
                   f'{self.b_sys} {self.default_sys_prompt} {self.e_sys}' \
                   f'{prompt} {self.e_inst} '

        return f'{self.b_inst} {prompt} {self.e_inst} '

AllentDan's avatar
AllentDan committed
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            messages (str | List): user's input prompt
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages, sequence_start)
        system, users, assistants = self._translate_messages(messages)
        system = self.default_sys_prompt if not system else system
        ret = f'<BOS>{self.b_inst} {self.b_sys} {system} {self.e_sys}'
        for i, (user, assistant) in enumerate(zip(users, assistants)):
            if i != 0:
                ret += f'{self.b_inst} '
            if assistant:
                ret += f'{user} {self.e_inst} {assistant}'
            else:
                ret += f'{user} {self.e_inst} '
        return ret

q.yao's avatar
q.yao committed
450

Chen Xin's avatar
Chen Xin committed
451
@MODELS.register_module(name='qwen-14b')
452
453
454
455
@MODELS.register_module(name='qwen-7b')
class Qwen7BChat(BaseModel):
    """Chat template for Qwen-7B-Chat."""

456
457
458
459
460
461
462
463
    def __init__(self,
                 session_len=8192,
                 top_p=0.5,
                 top_k=40,
                 temperature=1.0,
                 im_start='<|im_start|>',
                 im_end='<|im_end|>',
                 system='You are a helpful assistant.',
464
                 stop_words=['<|im_end|>'],
465
466
467
468
469
470
471
472
473
474
                 **kwargs):
        super().__init__(**kwargs)
        self.session_len = session_len
        self.top_p = top_p
        self.top_k = top_k
        self.temperature = temperature

        self.im_start = im_start
        self.im_end = im_end
        self.system = system
475
        self.stop_words = stop_words
476

Lyu Han's avatar
Lyu Han committed
477
478
479
    def decorate_prompt(self, prompt, sequence_start=True):
        assert self.capability == 'chat', \
            f'{type(self).__name__} has no capability of {self.capability}'
480
481
482
483
484
485
486
487
        if sequence_start:
            return f'{self.im_start}system\n{self.system}{self.im_end}' \
                   f'\n{self.im_start}user\n{prompt}{self.im_end}' \
                   f'\n{self.im_start}assistant\n'

        return f'\n{self.im_start}user\n{prompt}{self.im_end}' \
               f'\n{self.im_start}assistant\n'

488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            messages (str | List): user's input prompt
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages, sequence_start)
        system, users, assistants = self._translate_messages(messages)
        system = self.system if not system else system
        ret = f'{self.im_start}system\n{system}{self.im_end}'
        for user, assistant in zip(users, assistants):
            if assistant:
                ret += f'\n{self.im_start}user\n{user}{self.im_end}' \
                       f'\n{self.im_start}assistant\n{assistant}'
            else:
                ret += f'\n{self.im_start}user\n{user}{self.im_end}' \
                       f'\n{self.im_start}assistant\n'
        return ret

511

Lyu Han's avatar
Lyu Han committed
512
513
514
515
516
517
518
@MODELS.register_module(name='codellama')
class CodeLlama(Llama2):

    def __init__(self,
                 system='',
                 session_len=4096,
                 suffix_first=False,
519
                 stop_words=None,
Lyu Han's avatar
Lyu Han committed
520
521
522
523
524
525
526
527
528
                 **kwargs):
        super().__init__(**kwargs)
        caps = ['completion', 'infilling', 'chat', 'python']
        assert self.capability in caps, \
            f'{self.capability} is not supported. ' \
            f'The supported capabilities are: {caps}'
        self.default_sys_prompt = system
        self.session_len = session_len
        self.suffix_first = suffix_first
529
        self.stop_words = stop_words
Lyu Han's avatar
Lyu Han committed
530
531
532
533
534
535
536
537
538
539
540

        # The following sampling parameters refers to https://github.com/facebookresearch/codellama # noqa: E501
        if self.capability == 'completion' or self.capability == 'python':
            self.top_p = kwargs.get('top_p', 0.9)
            self.temperature = kwargs.get('temperature', 0.2)
        if self.capability == 'chat':
            self.top_p = kwargs.get('top_p', 0.95)
            self.temperature = kwargs.get('temperature', 0.2)
        elif self.capability == 'infilling':
            self.top_p = kwargs.get('top_p', 0.9)
            self.temperature = kwargs.get('temperature', 0.0)
541
542
            if self.stop_words is None:
                self.stop_words = ['<EOT>']
Lyu Han's avatar
Lyu Han committed
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577

    def decorate_prompt(self, prompt, sequence_start=True):
        if self.capability == 'infilling':
            return self._infill_prompt(prompt)
        elif self.capability == 'chat':
            return self._get_prompt(prompt, sequence_start)
        else:  # python speicalist
            return prompt

    def _infill_prompt(self, prompt):
        prefix, suffix = prompt.split('<FILL>')
        if self.suffix_first:
            # format as "<PRE> <SUF>{suf} <MID> {pre}"
            prompt = f'<BOS><PRE> <SUF>{suffix} <MID> {prefix}'
        else:
            # format as "<PRE> {pre} <SUF>{suf} <MID>"
            prompt = f'<BOS><PRE> {prefix} <SUF>{suffix} <MID>'
        return prompt

    def _get_prompt(self, prompt, sequence_start):
        prompt = prompt.strip()
        if sequence_start:
            return f'<BOS>{self.b_inst} ' \
                   f'{self.b_sys}{self.default_sys_prompt}{self.e_sys}' \
                   f'{prompt} {self.e_inst}'

        return f'{self.b_inst} {prompt} {self.e_inst}'

    def messages2prompt(self, messages, sequence_start=True):
        assert self.capability == 'chat', \
            f'codellama message2prompt only supports chat mode ' \
            f'but got {self.cap} mode'
        return super().messages2prompt(messages, sequence_start)


AllentDan's avatar
AllentDan committed
578
579
580
581
582
583
584
585
586
587
@MODELS.register_module(name='solar')
class SOLAR(BaseModel):
    """Chat template of SOLAR model.

    `https://huggingface.co/upstage/SOLAR-0-70b-16bit`
    """

    def __init__(self,
                 b_sys='### System:\n',
                 e_sys='\n\n',
AllentDan's avatar
AllentDan committed
588
                 user='### User:\n',
AllentDan's avatar
AllentDan committed
589
                 eoh='\n\n',
AllentDan's avatar
AllentDan committed
590
                 assistant='### Assistant:\n',
AllentDan's avatar
AllentDan committed
591
592
593
594
595
596
597
                 eoa='\n\n',
                 system='',
                 session_len=2048,
                 **kwargs):
        super().__init__(**kwargs)
        self.b_sys = b_sys
        self.e_sys = e_sys
AllentDan's avatar
AllentDan committed
598
        self.user = user
AllentDan's avatar
AllentDan committed
599
        self.eoh = eoh
AllentDan's avatar
AllentDan committed
600
        self.assistant = assistant
AllentDan's avatar
AllentDan committed
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
        self.eoa = eoa
        self.system = system
        self.session_len = session_len

    def decorate_prompt(self, prompt, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            prompt (str): user's input prompt
            sequence_start (bool): indicator for the first round chat of a
               session sequence
        Returns:
            str: the concatenated prompt
        """
        assert self.capability == 'chat', \
            f'{type(self).__name__} has no capability of {self.capability}'
        if sequence_start:
            return f'{self.b_sys}{self.system}{self.e_sys}' \
AllentDan's avatar
AllentDan committed
620
                   f'{self.user}{prompt}{self.eoh}{self.assistant}'
AllentDan's avatar
AllentDan committed
621

AllentDan's avatar
AllentDan committed
622
        return f'{self.user}{prompt}{self.eoh}{self.assistant}'
AllentDan's avatar
AllentDan committed
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638

    def messages2prompt(self, messages, sequence_start=True):
        """Return the prompt that is concatenated with other elements in the
        chat template.

        Args:
            messages (str | List): user's input prompt
        Returns:
            str: the concatenated prompt
        """
        if isinstance(messages, str):
            return self.get_prompt(messages, sequence_start)
        system, users, assistants = self._translate_messages(messages)
        system = self.system if not system else system
        ret = f'{self.b_sys}{system}{self.e_sys}'
        for i, (user, assistant) in enumerate(zip(users, assistants)):
AllentDan's avatar
AllentDan committed
639
            ret += f'{self.user}{user}{self.eoh}{self.assistant}'
AllentDan's avatar
AllentDan committed
640
641
642
643
644
            if assistant:
                ret += f'{assistant}{self.eoa}'
        return ret


lvhan028's avatar
lvhan028 committed
645
646
647
648
def main(model_name: str = 'test'):
    assert model_name in MODELS.module_dict.keys(), \
        f"'{model_name}' is not supported. " \
        f'The supported models are: {MODELS.module_dict.keys()}'
649
    model = MODELS.get(model_name)()
lvhan028's avatar
lvhan028 committed
650
651
    prompt = model.get_prompt(prompt='hi')
    print(prompt)
652
    print(f'session_len: {model.session_len}')
lvhan028's avatar
lvhan028 committed
653
654
655
656


if __name__ == '__main__':
    import fire
657

lvhan028's avatar
lvhan028 committed
658
    fire.Fire(main)