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

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

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


10
11
12
13
@MODELS.register_module(name='llama')
class BaseModel:
    """Base model."""

14
15
16
17
18
19
20
21
22
23
24
25
    def __init__(self,
                 session_len=2048,
                 top_p=0.8,
                 top_k=None,
                 temperature=0.8,
                 repetition_penalty=1.0,
                 **kwargs):
        self.session_len = session_len
        self.top_p = top_p
        self.top_k = top_k
        self.temperature = temperature
        self.repetition_penalty = repetition_penalty
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40

    @staticmethod
    def get_prompt(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
        """
        return prompt

AllentDan's avatar
AllentDan committed
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
    @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

85
86
87
88
89
90
    @property
    def stop_words(self):
        """Return the stop-words' token ids."""
        return None


lvhan028's avatar
lvhan028 committed
91
@MODELS.register_module(name='vicuna')
92
class Vicuna(BaseModel):
lvhan028's avatar
lvhan028 committed
93
    """Chat template of vicuna model."""
lvhan028's avatar
lvhan028 committed
94

95
96
97
98
99
100
101
102
103
104
    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
105
106

    def get_prompt(self, prompt, sequence_start=True):
lvhan028's avatar
lvhan028 committed
107
108
109
110
111
112
113
114
115
116
        """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
        """
lvhan028's avatar
lvhan028 committed
117
        if sequence_start:
AllentDan's avatar
AllentDan committed
118
            return f'{self.system} {self.user}: {prompt} {self.assistant}: '
lvhan028's avatar
lvhan028 committed
119
        else:
AllentDan's avatar
AllentDan committed
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
            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
142
143


144
@MODELS.register_module(name='internlm')
145
146
class InternLM(BaseModel):

147
148
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
149
150
151
152


@MODELS.register_module(name='internlm-chat-7b')
class InternLMChat7B(BaseModel):
lvhan028's avatar
lvhan028 committed
153
    """Chat template of InternLM model."""
lvhan028's avatar
lvhan028 committed
154

155
156
157
158
159
160
161
162
163
164
165
166
167
    def __init__(self,
                 system='',
                 user='<|User|>',
                 eoh='<eoh>',
                 eoa='<eoa>',
                 assistant='<|Bot|>',
                 **kwargs):
        super().__init__(**kwargs)
        self.system = system
        self.user = user
        self.eoh = eoh
        self.eoa = eoa
        self.assistant = assistant
lvhan028's avatar
lvhan028 committed
168
169

    def get_prompt(self, prompt, sequence_start=True):
lvhan028's avatar
lvhan028 committed
170
171
172
173
174
175
176
177
178
179
        """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
        """
lvhan028's avatar
lvhan028 committed
180
        if sequence_start:
181
            return f'<BOS>{self.user}:{prompt}{self.eoh}\n' \
lvhan028's avatar
lvhan028 committed
182
183
                   f'{self.assistant}:'
        else:
184
185
            return f'\n{self.user}:{prompt}{self.eoh}\n' \
                   f'{self.assistant}:'
lvhan028's avatar
lvhan028 committed
186

AllentDan's avatar
AllentDan committed
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
    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 = '<BOS>'
        for user, assistant in zip(users, assistants):
            if assistant:
                ret += f'{self.user}:{user}{self.eoh}\n{self.assistant}:' \
                       f'{assistant}{self.eoa}'
            else:
                ret += f'{self.user}:{user}{self.eoh}\n{self.assistant}:'
        return ret

lvhan028's avatar
lvhan028 committed
208
209
    @property
    def stop_words(self):
lvhan028's avatar
lvhan028 committed
210
        """Return the stop-words' token ids."""
211
212
213
        return [103027, 103028]


214
215
@MODELS.register_module(name='internlm-chat-7b-8k')
class InternLMChat7B8K(InternLMChat7B):
216

217
218
219
    def __init__(self, session_len=8192, **kwargs):
        super(InternLMChat7B8K, self).__init__(**kwargs)
        self.session_len = session_len
lvhan028's avatar
lvhan028 committed
220
221


222
223
224
@MODELS.register_module(name='baichuan-7b')
class Baichuan7B(BaseModel):

225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    def __init__(self, repetition_penalty=1.1, **kwargs):
        super().__init__(**kwargs)
        self.repetition_penalty = repetition_penalty


@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,
                 meta_instruction='',
                 user='<|Human|>: ',
                 eoh='',
                 eosys='',
                 assistant='<|Assistant|>: ',
                 system='<|System|>: ',
                 **kwargs):
        super().__init__(**kwargs)
        self.meta_instruction = meta_instruction
        self.user = user
        self.eoh = eoh
        self.eosys = eosys
        self.assistant = assistant
        self.system = system

    def get_prompt(self, prompt, sequence_start=True):
        if sequence_start:
            return f'<BOS>{self.system}{self.meta_instruction}{self.eosys}\n' \
                   f'{self.user}{prompt}{self.eoh}\n' \
                   f'{self.assistant}'
        else:
            return f'\n{self.user}{prompt}{self.eoh}\n{self.assistant}'

    @property
    def stop_words(self):
        """Return the stop-words' token ids."""
        return [45623]
263
264


q.yao's avatar
q.yao committed
265
@MODELS.register_module(name='llama2')
266
class Llama2(BaseModel):
q.yao's avatar
q.yao committed
267
268
    """Chat template of LLaMA2 model."""

269
270
271
272
273
274
275
    def __init__(
            self,
            b_inst='[INST]',
            e_inst='[/INST]',
            b_sys='<<SYS>>\n',
            e_sys='\n<</SYS>>\n\n',
            default_sys_prompt="""\
q.yao's avatar
q.yao committed
276
277
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.

278
279
280
281
282
283
284
285
286
287
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
        self.default_sys_prompt = default_sys_prompt
        self.session_len = session_len
q.yao's avatar
q.yao committed
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306

    def get_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
        """
        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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
    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
330

331
332
333
334
@MODELS.register_module(name='qwen-7b')
class Qwen7BChat(BaseModel):
    """Chat template for Qwen-7B-Chat."""

335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
    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.',
                 **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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368

    def get_prompt(self, prompt, sequence_start=True):
        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'

    @property
    def stop_words(self):
        """Return the stop-words' token ids."""
        return [151645]  # <|im_end|>


lvhan028's avatar
lvhan028 committed
369
370
371
372
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()}'
373
    model = MODELS.get(model_name)()
lvhan028's avatar
lvhan028 committed
374
375
    prompt = model.get_prompt(prompt='hi')
    print(prompt)
376
    print(f'session_len: {model.session_len}')
lvhan028's avatar
lvhan028 committed
377
378
379
380
381


if __name__ == '__main__':
    import fire
    fire.Fire(main)