-
Notifications
You must be signed in to change notification settings - Fork 19
/
internlm.cpp
330 lines (280 loc) · 12 KB
/
internlm.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
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
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
template<bool bias> class GenericConditionalGeneration : public BaseModelForConditionalGeneration<
Model<BaseConfig, Embedding, RMSNorm, InternLMBlock<bias>, int, int, int, int, int>>
{
public:
typedef BaseModelForConditionalGeneration<
Model<BaseConfig, Embedding, RMSNorm, InternLMBlock<bias>, int, int, int, int, int>> Base;
GenericConditionalGeneration() = default;
GenericConditionalGeneration(const BaseConfig &config, ModelType type)
: GenericConditionalGeneration(config, type, config.num_attention_heads, 10000, 1.0)
{}
GenericConditionalGeneration(const BaseConfig &config, ModelType type, int num_key_value_heads, float rope_theta, float rope_scaling)
: Base(type, config, MEM_SIZE, SCRATCH_SIZE), config(config)
{
constexpr size_t tensor_ovhd = GGML_TENSOR_SIZE + GGML_OBJECT_SIZE;
const size_t num_tensors = 3 + config.num_hidden_layers * (bias ? 16 : 12);
const size_t ctx_size = num_tensors * tensor_ovhd;
w_ctx_.gctx = GGMLContext({.mem_size = ctx_size, .mem_buffer = nullptr, .no_alloc = true});
w_ctx_.dtype = config.dtype;
Base::transformer = new Model<BaseConfig, Embedding, RMSNorm, InternLMBlock<bias>, int, int, int, int, int>(&w_ctx_, config, false,
config.hidden_size, config.num_attention_heads,
config.intermediate_size, num_key_value_heads, config.max_length);
for (int i = 0; i < config.num_hidden_layers; i++)
{
auto &attention = Base::transformer->layers[i].attention;
attention.freq_base = rope_theta;
attention.freq_scale = 1 / rope_scaling;
}
}
void load(ModelLoader &loader) override
{
loader.read_tensor("model.embed_tokens.weight", Base::transformer->word_embeddings.weight);
for (int i = 0; i < config.num_hidden_layers; i++)
{
std::string layer_prefix = "model.layers." + std::to_string(Base::layer_ids[i]) + '.';
if (true)
loader.read_tensor(layer_prefix + "self_attn.q_proj.weight", Base::transformer->layers[i].attention.q_proj.weight);
if (bias)
loader.read_tensor(layer_prefix + "self_attn.q_proj.bias", Base::transformer->layers[i].attention.q_proj.bias);
if (true)
loader.read_tensor(layer_prefix + "self_attn.k_proj.weight", Base::transformer->layers[i].attention.k_proj.weight);
if (bias)
loader.read_tensor(layer_prefix + "self_attn.k_proj.bias", Base::transformer->layers[i].attention.k_proj.bias);
if (true)
loader.read_tensor(layer_prefix + "self_attn.v_proj.weight", Base::transformer->layers[i].attention.v_proj.weight);
if (bias)
loader.read_tensor(layer_prefix + "self_attn.v_proj.bias", Base::transformer->layers[i].attention.v_proj.bias);
if (true)
loader.read_tensor(layer_prefix + "self_attn.o_proj.weight", Base::transformer->layers[i].attention.o_proj.weight);
if (bias)
loader.read_tensor(layer_prefix + "self_attn.o_proj.bias", Base::transformer->layers[i].attention.o_proj.bias);
loader.read_tensor(layer_prefix + "mlp.gate_proj.weight", Base::transformer->layers[i].mlp.gate_proj.weight);
loader.read_tensor(layer_prefix + "mlp.down_proj.weight", Base::transformer->layers[i].mlp.down_proj.weight);
loader.read_tensor(layer_prefix + "mlp.up_proj.weight", Base::transformer->layers[i].mlp.up_proj.weight);
loader.read_tensor(layer_prefix + "input_layernorm.weight", Base::transformer->layers[i].input_layernorm.weight);
loader.read_tensor(layer_prefix + "post_attention_layernorm.weight", Base::transformer->layers[i].post_attention_layernorm.weight);
}
loader.read_tensor("model.norm.weight", Base::transformer->final_layernorm.weight);
loader.read_tensor("lm_head.weight", dynamic_cast<Linear *>(Base::transformer->lm_head)->weight);
CHATLLM_CHECK(ggml_used_mem(w_ctx_.gctx.get()) == ggml_get_mem_size(w_ctx_.gctx.get()))
<< "corrupted model weights";
}
public:
static constexpr size_t MEM_SIZE = 1512ull * 1024 * 1024;
static constexpr size_t SCRATCH_SIZE = 244ull * 1024 * 1024;
BaseConfig config;
private:
// hold ggml_context & kv_cache
InitContext w_ctx_; // weight context
};
class InternLMTokenizer : public BaseTokenizer
{
public:
InternLMTokenizer(const BaseConfig &config, BaseHistoryEncoder *chat_encoder) : BaseTokenizer::BaseTokenizer(config, chat_encoder)
{
}
size_t load(const char *buffer, int n_vocab) override
{
tp = new tokenizer::BPEProcessor1();
size_t size = tp->Load(buffer, n_vocab);
eoa_token_id = tp->PieceToId("<eoa>");
terminate_ids.insert(eoa_token_id);
return size;
}
bool is_special_id(int id) const override
{
return (id == eoa_token_id) || (id == bos_token_id) || (id == eos_token_id);
}
public:
int eoa_token_id;
};
class ChatHistoryEncoder : public BaseHistoryEncoder
{
public:
ChatHistoryEncoder(bool insert_eoh) : insert_eoh(insert_eoh) {}
void append_pair(int round_idx, const std::string &user, const std::string &ai, std::vector<int> &ids) const override
{
std::ostringstream oss_prompt;
append_user(round_idx, user, ids);
oss_prompt << ai << "<eoa>\n";
auto text = oss_prompt.str();
tokenizer->encode(text, ids);
}
void append_sys_prompt(std::vector<int> &ids) const override
{
std::ostringstream oss_prompt;
oss_prompt << "<s>";
if (tokenizer->get_system_prompt().size() > 0)
{
oss_prompt << "<|System|>:"
<< tokenizer->get_system_prompt()
<< "\n";
}
auto text = oss_prompt.str();
tokenizer->encode(text, ids);
}
void do_append_user(int round_idx, const std::string &user, std::vector<int> &ids) const override
{
std::ostringstream oss_prompt;
oss_prompt << "<s><|User|>:" << user;
if (insert_eoh) oss_prompt << "<eoh>";
oss_prompt << "\n<|Bot|>:";
auto text = oss_prompt.str();
tokenizer->encode(text, ids);
}
public:
bool insert_eoh;
};
namespace v2
{
struct Config : public BaseConfig
{
int num_key_value_heads;
float rope_theta;
float rope_scaling;
};
static ChatHistoryEncoder _chat_encoder(false);
class Tokenizer : public InternLMTokenizer
{
public:
Tokenizer(const Config &config) : InternLMTokenizer::InternLMTokenizer(config, &_chat_encoder)
{
sys_prompt = R""(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 中文.)"";
}
};
class ConditionalGeneration: public GenericConditionalGeneration<false>
{
public:
ConditionalGeneration(const Config &config)
: GenericConditionalGeneration(config, MODEL_TYPE_INTERNLM2, config.num_key_value_heads, config.rope_theta, config.rope_scaling)
{
// ready for 20B
GRAPH_SIZE = 4096;
}
};
}
namespace v1
{
struct Config : public BaseConfig
{
};
static ChatHistoryEncoder _chat_encoder(true);
class Tokenizer : public InternLMTokenizer
{
public:
Tokenizer(const Config &config) : InternLMTokenizer::InternLMTokenizer(config, &_chat_encoder)
{
}
};
class ConditionalGeneration: public GenericConditionalGeneration<true>
{
public:
ConditionalGeneration(const Config &config)
: GenericConditionalGeneration(config, MODEL_TYPE_INTERNLM)
{
}
};
}
namespace v3
{
struct Config : public v2::Config
{
};
class ChatHistoryEncoder : public BaseHistoryEncoder
{
public:
ChatHistoryEncoder() {}
void append_pair(int round_idx, const std::string &user, const std::string &ai, std::vector<int> &ids) const override;
void do_append_user(int round_idx, const std::string &user, std::vector<int> &ids) const override;
};
static ChatHistoryEncoder _chat_encoder;
class Tokenizer : public BaseTokenizer
{
public:
Tokenizer(const Config &config)
: BaseTokenizer::BaseTokenizer(config, &_chat_encoder)
{
sys_prompt = R""(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 中文.)"";
}
size_t load(const char *buffer, int n_vocab) override
{
tp = new tokenizer::BPEProcessor1();
size_t size = tp->Load(buffer, n_vocab);
int id = n_vocab;
im_start_token_id = --id;
im_end_token_id = --id;
action_start_token_id = --id;
action_end_token_id = --id;
interpreter_token_id = --id;
plugin_token_id = --id;
newline_token_id = tp->PieceToId("\n");
terminate_ids.insert(im_end_token_id);
return size;
}
bool is_special_id(int id) const override
{
return (id == bos_token_id) || (id == eos_token_id) || ((plugin_token_id <= id) && (id <= im_start_token_id));
}
void encode(const std::string &text, std::vector<int> &ids, bool add_im_start, bool add_im_end)
{
if (add_im_start)
ids.push_back(im_start_token_id);
BaseTokenizer::encode(text, ids);
if (add_im_end)
{
ids.push_back(im_end_token_id);
ids.push_back(newline_token_id);
}
}
public:
int im_start_token_id;
int im_end_token_id;
int action_start_token_id;
int action_end_token_id;
int interpreter_token_id;
int plugin_token_id;
int newline_token_id;
};
class ConditionalGeneration: public GenericConditionalGeneration<false>
{
public:
ConditionalGeneration(const Config &config)
: GenericConditionalGeneration(config, MODEL_TYPE_INTERNLM3, config.num_key_value_heads, config.rope_theta, config.rope_scaling)
{
// ready for 20B
GRAPH_SIZE = 4096;
}
};
void ChatHistoryEncoder::append_pair(int round_idx, const std::string &user, const std::string &ai, std::vector<int> &ids) const
{
Tokenizer *tok = dynamic_cast<Tokenizer *>(tokenizer);
append_user(round_idx, user, ids);
tok->encode(ai, ids, false, true);
}
void ChatHistoryEncoder::do_append_user(int round_idx, const std::string &user, std::vector<int> &ids) const
{
Tokenizer *tok = dynamic_cast<Tokenizer *>(tokenizer);
std::ostringstream oss_prompt;
if (round_idx == 0)
{
ids.push_back(tok->bos_token_id);
if (tok->get_system_prompt().size() > 0)
{
oss_prompt << "system\n"
<< tok->get_system_prompt();
tok->encode(oss_prompt.str(), ids, true, true);
}
}
oss_prompt.str("");
oss_prompt << "user\n"
<< user;
tok->encode(oss_prompt.str(), ids, true, true);
oss_prompt.str("");
oss_prompt << "assistant\n";
tok->encode(oss_prompt.str(), ids, true, false);
}
}