model.py 8.44 KB
Newer Older
lvhan028's avatar
lvhan028 committed
1
2
3
# Copyright (c) OpenMMLab. All rights reserved.
from mmengine import Registry

lvhan028's avatar
lvhan028 committed
4
MODELS = Registry('model', locations=['lmdeploy.model'])
lvhan028's avatar
lvhan028 committed
5
6


7
8
9
10
@MODELS.register_module(name='llama')
class BaseModel:
    """Base model."""

11
12
13
14
15
16
17
18
19
20
21
22
    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
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43

    @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

    @property
    def stop_words(self):
        """Return the stop-words' token ids."""
        return None


lvhan028's avatar
lvhan028 committed
44
@MODELS.register_module(name='vicuna')
45
class Vicuna(BaseModel):
lvhan028's avatar
lvhan028 committed
46
    """Chat template of vicuna model."""
lvhan028's avatar
lvhan028 committed
47

48
49
50
51
52
53
54
55
56
57
    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
58
59

    def get_prompt(self, prompt, sequence_start=True):
lvhan028's avatar
lvhan028 committed
60
61
62
63
64
65
66
67
68
69
        """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
70
71
72
73
74
75
        if sequence_start:
            return f'{self.system} {self.user}: {prompt} {self.assistant}:'
        else:
            return f'</s>{self.user}: {prompt} {self.assistant}:'


76
@MODELS.register_module(name='internlm')
77
78
class InternLM(BaseModel):

79
80
    def __init__(self, **kwargs):
        super().__init__(**kwargs)
81
82
83
84


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

87
88
89
90
91
92
93
94
95
96
97
98
99
    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
100
101

    def get_prompt(self, prompt, sequence_start=True):
lvhan028's avatar
lvhan028 committed
102
103
104
105
106
107
108
109
110
111
        """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
112
        if sequence_start:
113
            return f'<BOS>{self.user}:{prompt}{self.eoh}\n' \
lvhan028's avatar
lvhan028 committed
114
115
                   f'{self.assistant}:'
        else:
116
117
            return f'\n{self.user}:{prompt}{self.eoh}\n' \
                   f'{self.assistant}:'
lvhan028's avatar
lvhan028 committed
118
119
120

    @property
    def stop_words(self):
lvhan028's avatar
lvhan028 committed
121
        """Return the stop-words' token ids."""
122
123
124
        return [103027, 103028]


125
126
@MODELS.register_module(name='internlm-chat-7b-8k')
class InternLMChat7B8K(InternLMChat7B):
127

128
129
130
    def __init__(self, session_len=8192, **kwargs):
        super(InternLMChat7B8K, self).__init__(**kwargs)
        self.session_len = session_len
lvhan028's avatar
lvhan028 committed
131
132


133
134
135
@MODELS.register_module(name='baichuan-7b')
class Baichuan7B(BaseModel):

136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    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]
174
175


q.yao's avatar
q.yao committed
176
@MODELS.register_module(name='llama2')
177
class Llama2(BaseModel):
q.yao's avatar
q.yao committed
178
179
    """Chat template of LLaMA2 model."""

180
181
182
183
184
185
186
    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
187
188
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.

189
190
191
192
193
194
195
196
197
198
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
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218

    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} '


219
220
221
222
@MODELS.register_module(name='qwen-7b')
class Qwen7BChat(BaseModel):
    """Chat template for Qwen-7B-Chat."""

223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
    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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256

    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
257
258
259
260
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()}'
261
    model = MODELS.get(model_name)()
lvhan028's avatar
lvhan028 committed
262
263
    prompt = model.get_prompt(prompt='hi')
    print(prompt)
264
    print(f'session_len: {model.session_len}')
lvhan028's avatar
lvhan028 committed
265
266
267
268
269


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