interplane.Get Omega
Read in your language

ggml

[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)

Brought by drakestapleton

branch master Branches Tags History

ggml / examples / gpt-2 / main-alloc.cpp

880 lines · 30900 bytes Raw Blame History
1#include "ggml.h"
2#include "ggml-cpu.h"
3#include "ggml-alloc.h"
4#include "ggml-backend.h"
5
6#include "common.h"
7#include "common-ggml.h"
8
9#include <cassert>
10#include <cmath>
11#include <cstdio>
12#include <cstring>
13#include <fstream>
14#include <map>
15#include <string>
16#include <vector>
17
18#if defined(_MSC_VER)
19#pragma warning(disable: 4244 4267) // possible loss of data
20#endif
21
22// default hparams (GPT-2 117M)
23struct gpt2_hparams {
24 int32_t n_vocab = 50257;
25 int32_t n_ctx = 1024;
26 int32_t n_embd = 768;
27 int32_t n_head = 12;
28 int32_t n_layer = 12;
29 int32_t ftype = 1;
30 float eps = 1e-5f;
31};
32
33struct gpt2_layer {
34 // normalization
35 struct ggml_tensor * ln_1_g;
36 struct ggml_tensor * ln_1_b;
37
38 struct ggml_tensor * ln_2_g;
39 struct ggml_tensor * ln_2_b;
40
41 // attention
42 struct ggml_tensor * c_attn_attn_w;
43 struct ggml_tensor * c_attn_attn_b;
44
45 struct ggml_tensor * c_attn_proj_w;
46 struct ggml_tensor * c_attn_proj_b;
47
48 // mlp
49 struct ggml_tensor * c_mlp_fc_w;
50 struct ggml_tensor * c_mlp_fc_b;
51
52 struct ggml_tensor * c_mlp_proj_w;
53 struct ggml_tensor * c_mlp_proj_b;
54};
55
56struct gpt2_model {
57 gpt2_hparams hparams;
58
59 // normalization
60 struct ggml_tensor * ln_f_g;
61 struct ggml_tensor * ln_f_b;
62
63 struct ggml_tensor * wte; // token embedding
64 struct ggml_tensor * wpe; // position embedding
65 struct ggml_tensor * lm_head; // language model head
66
67 std::vector<gpt2_layer> layers;
68
69 // key + value memory
70 struct ggml_tensor * memory_k;
71 struct ggml_tensor * memory_v;
72
73 //
74 struct ggml_context * ctx_w;
75 std::map<std::string, struct ggml_tensor *> tensors;
76};
77
78// load the model's weights from a file
79bool gpt2_model_load(const std::string & fname, gpt2_model & model, gpt_vocab & vocab) {
80 printf("%s: loading model from '%s'\n", __func__, fname.c_str());
81
82 auto fin = std::ifstream(fname, std::ios::binary);
83 if (!fin) {
84 fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
85 return false;
86 }
87
88 // verify magic
89 {
90 uint32_t magic;
91 fin.read((char *) &magic, sizeof(magic));
92 if (magic != GGML_FILE_MAGIC) {
93 fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
94 return false;
95 }
96 }
97
98 // load hparams
99 {
100 auto & hparams = model.hparams;
101
102 fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
103 fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
104 fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
105 fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
106 fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
107 fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
108
109 const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
110
111 printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
112 printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
113 printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
114 printf("%s: n_head = %d\n", __func__, hparams.n_head);
115 printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
116 printf("%s: ftype = %d\n", __func__, hparams.ftype);
117 printf("%s: qntvr = %d\n", __func__, qntvr);
118
119 hparams.ftype %= GGML_QNT_VERSION_FACTOR;
120 }
121
122 // load vocab
123 {
124 int32_t n_vocab = 0;
125 fin.read((char *) &n_vocab, sizeof(n_vocab));
126
127 if (n_vocab != model.hparams.n_vocab) {
128 fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
129 __func__, fname.c_str(), n_vocab, model.hparams.n_vocab);
130 return false;
131 }
132
133 std::string word;
134 std::vector<char> buf(128);
135
136 for (int i = 0; i < n_vocab; i++) {
137 uint32_t len;
138 fin.read((char *) &len, sizeof(len));
139
140 buf.resize(len);
141 fin.read((char *) buf.data(), len);
142 word.assign(buf.data(), len);
143
144 vocab.token_to_id[word] = i;
145 vocab.id_to_token[i] = word;
146 }
147 }
148
149 // for the big tensors, we have the option to store the data in 16-bit floats or quantized
150 // in order to save memory and also to speed up the computation
151 ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
152 if (wtype == GGML_TYPE_COUNT) {
153 fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n",
154 __func__, fname.c_str(), model.hparams.ftype);
155 return false;
156 }
157
158 auto & ctx = model.ctx_w;
159
160 size_t ctx_size = 0;
161
162 {
163 const auto & hparams = model.hparams;
164
165 const int n_embd = hparams.n_embd;
166 const int n_layer = hparams.n_layer;
167 const int n_ctx = hparams.n_ctx;
168 const int n_vocab = hparams.n_vocab;
169
170 ctx_size += ggml_row_size(GGML_TYPE_F32, n_embd); // ln_f_g
171 ctx_size += ggml_row_size(GGML_TYPE_F32, n_embd); // ln_f_b
172
173 ctx_size += ggml_row_size(wtype, n_vocab*n_embd); // wte
174 ctx_size += ggml_row_size(GGML_TYPE_F32 , n_ctx*n_embd); // wpe
175 ctx_size += ggml_row_size(wtype, n_vocab*n_embd); // lm_head
176
177 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_1_g
178 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_1_b
179
180 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_2_g
181 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_2_b
182
183 ctx_size += n_layer*(ggml_row_size(wtype, 3*n_embd*n_embd)); // c_attn_attn_w
184 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, 3*n_embd)); // c_attn_attn_b
185
186 ctx_size += n_layer*(ggml_row_size(wtype, n_embd*n_embd)); // c_attn_proj_w
187 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // c_attn_proj_b
188
189 ctx_size += n_layer*(ggml_row_size(wtype, 4*n_embd*n_embd)); // c_mlp_fc_w
190 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, 4*n_embd)); // c_mlp_fc_b
191
192 ctx_size += n_layer*(ggml_row_size(wtype, 4*n_embd*n_embd)); // c_mlp_proj_w
193 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, 4*n_embd)); // c_mlp_proj_b
194
195 ctx_size += n_ctx*n_layer*ggml_row_size(GGML_TYPE_F32, n_embd); // memory_k
196 ctx_size += n_ctx*n_layer*ggml_row_size(GGML_TYPE_F32, n_embd); // memory_v
197
198 ctx_size += (6 + 12*n_layer)*512; // object overhead
199
200 printf("%s: ggml tensor size = %d bytes\n", __func__, (int) sizeof(ggml_tensor));
201 printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
202 }
203
204 // create the ggml context
205 {
206 struct ggml_init_params params = {
207 /*.mem_size =*/ ctx_size,
208 /*.mem_buffer =*/ NULL,
209 /*.no_alloc =*/ false,
210 };
211
212 model.ctx_w = ggml_init(params);
213 if (!model.ctx_w) {
214 fprintf(stderr, "%s: ggml_init() failed\n", __func__);
215 return false;
216 }
217 }
218
219 // prepare memory for the weights
220 {
221 const auto & hparams = model.hparams;
222
223 const int n_embd = hparams.n_embd;
224 const int n_layer = hparams.n_layer;
225 const int n_ctx = hparams.n_ctx;
226 const int n_vocab = hparams.n_vocab;
227
228 model.layers.resize(n_layer);
229
230 model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
231 model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
232
233 model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
234 model.wpe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ctx);
235 model.lm_head = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
236
237 // map by name
238 model.tensors["model/ln_f/g"] = model.ln_f_g;
239 model.tensors["model/ln_f/b"] = model.ln_f_b;
240
241 model.tensors["model/wte"] = model.wte;
242 model.tensors["model/wpe"] = model.wpe;
243 model.tensors["model/lm_head"] = model.lm_head;
244
245 for (int i = 0; i < n_layer; ++i) {
246 auto & layer = model.layers[i];
247
248 layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
249 layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
250
251 layer.ln_2_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
252 layer.ln_2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
253
254 layer.c_attn_attn_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 3*n_embd);
255 layer.c_attn_attn_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 3*n_embd);
256
257 layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
258 layer.c_attn_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
259
260 layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 4*n_embd);
261 layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd);
262
263 layer.c_mlp_proj_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd);
264 layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
265
266 // map by name
267 model.tensors["model/h" + std::to_string(i) + "/ln_1/g"] = layer.ln_1_g;
268 model.tensors["model/h" + std::to_string(i) + "/ln_1/b"] = layer.ln_1_b;
269
270 model.tensors["model/h" + std::to_string(i) + "/ln_2/g"] = layer.ln_2_g;
271 model.tensors["model/h" + std::to_string(i) + "/ln_2/b"] = layer.ln_2_b;
272
273 model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/w"] = layer.c_attn_attn_w;
274 model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/b"] = layer.c_attn_attn_b;
275
276 model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/w"] = layer.c_attn_proj_w;
277 model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/b"] = layer.c_attn_proj_b;
278
279 model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/w"] = layer.c_mlp_fc_w;
280 model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/b"] = layer.c_mlp_fc_b;
281
282 model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/w"] = layer.c_mlp_proj_w;
283 model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/b"] = layer.c_mlp_proj_b;
284 }
285 }
286
287 // key + value memory
288 {
289 const auto & hparams = model.hparams;
290
291 const int n_embd = hparams.n_embd;
292 const int n_layer = hparams.n_layer;
293 const int n_ctx = hparams.n_ctx;
294
295 const int n_mem = n_layer*n_ctx;
296 const int n_elements = n_embd*n_mem;
297
298 model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements);
299 model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements);
300
301 const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
302
303 printf("%s: memory size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
304 }
305
306 // load weights
307 {
308 size_t total_size = 0;
309
310 bool has_lm_head = false;
311
312 while (true) {
313 int32_t n_dims;
314 int32_t length;
315 int32_t ttype;
316
317 fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
318 fin.read(reinterpret_cast<char *>(&length), sizeof(length));
319 fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
320
321 if (fin.eof()) {
322 break;
323 }
324
325 int32_t nelements = 1;
326 int32_t ne[2] = { 1, 1 };
327 for (int i = 0; i < n_dims; ++i) {
328 fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
329 nelements *= ne[i];
330 }
331
332 std::string name(length, 0);
333 fin.read(&name[0], length);
334
335 if (model.tensors.find(name) == model.tensors.end()) {
336 fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str());
337 return false;
338 }
339
340 auto tensor = model.tensors[name];
341 if (ggml_nelements(tensor) != nelements) {
342 fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str());
343 return false;
344 }
345
346 if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
347 fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
348 __func__, name.c_str(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]);
349 return false;
350 }
351
352 // for debugging
353 if (0) {
354 printf("%24s - [%5d, %5d], type = %6s, %6.2f MB, %9zu bytes\n", name.c_str(), ne[0], ne[1], ggml_type_name(ggml_type(ttype)), ggml_nbytes(tensor)/1024.0/1024.0, ggml_nbytes(tensor));
355 }
356
357 const size_t bpe = ggml_type_size(ggml_type(ttype));
358
359 if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
360 fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
361 __func__, name.c_str(), ggml_nbytes(tensor), nelements*bpe);
362 return false;
363 }
364
365 fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
366
367 // GPT-2 models share the WTE tensor as the LM head
368 if (name == "model/wte" && has_lm_head == false) {
369 memcpy(model.lm_head->data, tensor->data, ggml_nbytes(tensor));
370 }
371
372 if (name == "model/lm_head") {
373 has_lm_head = true;
374 }
375
376 total_size += ggml_nbytes(tensor);
377 }
378
379 printf("%s: model size = %8.2f MB\n", __func__, total_size/1024.0/1024.0);
380 }
381
382 fin.close();
383
384 return true;
385}
386
387// build the computation graph
388struct ggml_cgraph * gpt2_graph(
389 const gpt2_model & model,
390 const int n_past,
391 const int n_tokens) {
392 const int N = n_tokens;
393
394 const auto & hparams = model.hparams;
395
396 const int n_embd = hparams.n_embd;
397 const int n_layer = hparams.n_layer;
398 const int n_ctx = hparams.n_ctx;
399 const int n_head = hparams.n_head;
400
401 // since we are using ggml-alloc, this buffer only needs enough space to hold the ggml_tensor and ggml_cgraph structs, but not the tensor data
402 static size_t buf_size = ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead();
403 static std::vector<uint8_t> buf(buf_size);
404
405 struct ggml_init_params params = {
406 /*.mem_size =*/ buf_size,
407 /*.mem_buffer =*/ buf.data(),
408 /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_gallocr_alloc_graph()
409 };
410
411 struct ggml_context * ctx = ggml_init(params);
412
413 struct ggml_cgraph * gf = ggml_new_graph(ctx);
414
415 struct ggml_tensor * embd = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N);
416 // at this point, the tensor data is not allocated yet and cannot be set
417 // we will find the tensor after the graph is allocated by its name, and set the data then
418 ggml_set_name(embd, "embd");
419 // setting a tensor as an input will ensure that it is allocated at the beginning of the graph
420 // this is important to ensure that the input tensors are not overwritten before they are used
421 ggml_set_input(embd);
422
423 struct ggml_tensor * position = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N);
424 ggml_set_name(position, "position");
425 ggml_set_input(position);
426
427 // wte + wpe
428 struct ggml_tensor * inpL =
429 ggml_add(ctx,
430 ggml_get_rows(ctx, model.wte, embd),
431 ggml_get_rows(ctx, model.wpe, position));
432
433 for (int il = 0; il < n_layer; ++il) {
434 struct ggml_tensor * cur;
435
436 // norm
437 {
438 // [ 768, N]
439 cur = ggml_norm(ctx, inpL, hparams.eps);
440
441 // cur = ln_1_g*cur + ln_1_b
442 // [ 768, N]
443 cur = ggml_add(ctx,
444 ggml_mul(ctx,
445 ggml_repeat(ctx, model.layers[il].ln_1_g, cur),
446 cur),
447 ggml_repeat(ctx, model.layers[il].ln_1_b, cur));
448 }
449
450 // attn
451 // [2304, 768] - model.layers[il].c_attn_attn_w
452 // [2304, 1] - model.layers[il].c_attn_attn_b
453 // [ 768, N] - cur (in)
454 // [2304, N] - cur (out)
455 //
456 // cur = attn_w*cur + attn_b
457 // [2304, N]
458 {
459 cur = ggml_mul_mat(ctx,
460 model.layers[il].c_attn_attn_w,
461 cur);
462
463 cur = ggml_add(ctx,
464 ggml_repeat(ctx, model.layers[il].c_attn_attn_b, cur),
465 cur);
466 }
467
468 // self-attention
469 {
470 struct ggml_tensor * Qcur = ggml_view_2d(ctx, cur, n_embd, N, cur->nb[1], 0*sizeof(float)*n_embd);
471 struct ggml_tensor * Kcur = ggml_view_2d(ctx, cur, n_embd, N, cur->nb[1], 1*sizeof(float)*n_embd);
472 struct ggml_tensor * Vcur = ggml_view_2d(ctx, cur, n_embd, N, cur->nb[1], 2*sizeof(float)*n_embd);
473
474 // store key and value to memory
475 if (N >= 1) {
476 struct ggml_tensor * k = ggml_view_1d(ctx, model.memory_k, N*n_embd, (ggml_element_size(model.memory_k)*n_embd)*(il*n_ctx + n_past));
477 struct ggml_tensor * v = ggml_view_1d(ctx, model.memory_v, N*n_embd, (ggml_element_size(model.memory_v)*n_embd)*(il*n_ctx + n_past));
478
479 ggml_build_forward_expand(gf, ggml_cpy(ctx, Kcur, k));
480 ggml_build_forward_expand(gf, ggml_cpy(ctx, Vcur, v));
481 }
482
483 // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
484 // [64, N, 12]
485 struct ggml_tensor * Q =
486 ggml_permute(ctx,
487 ggml_cont_3d(ctx, Qcur, n_embd/n_head, n_head, N),
488 0, 2, 1, 3);
489
490 // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
491 // [64, n_past + N, 12]
492 struct ggml_tensor * K =
493 ggml_permute(ctx,
494 ggml_reshape_3d(ctx,
495 ggml_view_1d(ctx, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
496 n_embd/n_head, n_head, n_past + N),
497 0, 2, 1, 3);
498
499 // GG: flash attention
500 //struct ggml_tensor * V =
501 // ggml_cpy(ctx0,
502 // ggml_permute(ctx0,
503 // ggml_reshape_3d(ctx0,
504 // ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
505 // n_embd/n_head, n_head, n_past + N),
506 // 1, 2, 0, 3),
507 // ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_past + N, n_embd/n_head, n_head));
508
509 //struct ggml_tensor * KQV = ggml_flash_attn(ctx0, Q, K, V, true);
510
511 // K * Q
512 // [n_past + N, N, 12]
513 struct ggml_tensor * KQ = ggml_mul_mat(ctx, K, Q);
514
515 // KQ_scaled = KQ / sqrt(n_embd/n_head)
516 // [n_past + N, N, 12]
517 struct ggml_tensor * KQ_scaled =
518 ggml_scale(ctx,
519 KQ,
520 1.0f/sqrtf(float(n_embd)/n_head));
521
522 // KQ_masked = mask_past(KQ_scaled)
523 // [n_past + N, N, 12]
524 struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx, KQ_scaled, n_past);
525
526 // KQ = soft_max(KQ_masked)
527 // [n_past + N, N, 12]
528 struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx, KQ_masked);
529
530 // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
531 // [n_past + N, 64, 12]
532 struct ggml_tensor * V_trans =
533 ggml_cont_3d(ctx,
534 ggml_permute(ctx,
535 ggml_reshape_3d(ctx,
536 ggml_view_1d(ctx, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
537 n_embd/n_head, n_head, n_past + N),
538 1, 2, 0, 3),
539 n_past + N, n_embd/n_head, n_head);
540
541 // KQV = transpose(V) * KQ_soft_max
542 // [64, N, 12]
543 struct ggml_tensor * KQV = ggml_mul_mat(ctx, V_trans, KQ_soft_max);
544
545 // KQV_merged = KQV.permute(0, 2, 1, 3)
546 // [64, 12, N]
547 struct ggml_tensor * KQV_merged = ggml_permute(ctx, KQV, 0, 2, 1, 3);
548
549 // cur = KQV_merged.contiguous().view(n_embd, N)
550 // [768, N]
551 cur = ggml_cont_2d(ctx, KQV_merged, n_embd, N);
552 }
553
554 // projection
555 // [ 768, 768] - model.layers[il].c_attn_proj_w
556 // [ 768, 1] - model.layers[il].c_attn_proj_b
557 // [ 768, N] - cur (in)
558 // [ 768, N] - cur (out)
559 //
560 // cur = proj_w*cur + proj_b
561 // [768, N]
562 {
563 cur = ggml_mul_mat(ctx,
564 model.layers[il].c_attn_proj_w,
565 cur);
566
567 cur = ggml_add(ctx,
568 ggml_repeat(ctx, model.layers[il].c_attn_proj_b, cur),
569 cur);
570 }
571
572 // add the input
573 cur = ggml_add(ctx, cur, inpL);
574
575 struct ggml_tensor * inpFF = cur;
576
577 // feed-forward network
578 {
579 // norm
580 {
581 cur = ggml_norm(ctx, inpFF, hparams.eps);
582
583 // cur = ln_2_g*cur + ln_2_b
584 // [ 768, N]
585 cur = ggml_add(ctx,
586 ggml_mul(ctx,
587 ggml_repeat(ctx, model.layers[il].ln_2_g, cur),
588 cur),
589 ggml_repeat(ctx, model.layers[il].ln_2_b, cur));
590 }
591
592 // fully connected
593 // [3072, 768] - model.layers[il].c_mlp_fc_w
594 // [3072, 1] - model.layers[il].c_mlp_fc_b
595 // [ 768, N] - cur (in)
596 // [3072, N] - cur (out)
597 //
598 // cur = fc_w*cur + fc_b
599 // [3072, N]
600 cur = ggml_mul_mat(ctx,
601 model.layers[il].c_mlp_fc_w,
602 cur);
603
604 cur = ggml_add(ctx,
605 ggml_repeat(ctx, model.layers[il].c_mlp_fc_b, cur),
606 cur);
607
608 // GELU activation
609 // [3072, N]
610 cur = ggml_gelu(ctx, cur);
611
612 // projection
613 // [ 768, 3072] - model.layers[il].c_mlp_proj_w
614 // [ 768, 1] - model.layers[il].c_mlp_proj_b
615 // [3072, N] - cur (in)
616 // [ 768, N] - cur (out)
617 //
618 // cur = proj_w*cur + proj_b
619 // [768, N]
620 cur = ggml_mul_mat(ctx,
621 model.layers[il].c_mlp_proj_w,
622 cur);
623
624 cur = ggml_add(ctx,
625 ggml_repeat(ctx, model.layers[il].c_mlp_proj_b, cur),
626 cur);
627 }
628
629 // input for next layer
630 inpL = ggml_add(ctx, cur, inpFF);
631 }
632
633 // norm
634 {
635 // [ 768, N]
636 inpL = ggml_norm(ctx, inpL, hparams.eps);
637
638 // inpL = ln_f_g*inpL + ln_f_b
639 // [ 768, N]
640 inpL = ggml_add(ctx,
641 ggml_mul(ctx,
642 ggml_repeat(ctx, model.ln_f_g, inpL),
643 inpL),
644 ggml_repeat(ctx, model.ln_f_b, inpL));
645 }
646
647 // inpL = WTE * inpL
648 // [ 768, 50257] - model.lm_head
649 // [ 768, N] - inpL
650 inpL = ggml_mul_mat(ctx, model.lm_head, inpL);
651 ggml_set_name(inpL, "logits");
652 // setting a tensor as the output will ensure that it is not overwritten by subsequent operations
653 ggml_set_output(inpL);
654
655 // logits -> probs
656 //inpL = ggml_soft_max(ctx0, inpL);
657
658 ggml_build_forward_expand(gf, inpL);
659
660 ggml_free(ctx);
661
662 return gf;
663}
664
665// evaluate the transformer
666//
667// - model: the model
668// - allocr: ggml_gallocr to use to allocate the compute buffer
669// - n_threads: number of threads to use
670// - n_past: the context size so far
671// - embd_inp: the embeddings of the tokens in the context
672// - embd_w: the predicted logits for the next token
673//
674bool gpt2_eval(
675 const gpt2_model & model,
676 ggml_gallocr_t allocr,
677 const int n_threads,
678 const int n_past,
679 const std::vector<gpt_vocab::id> & embd_inp,
680 std::vector<float> & embd_w) {
681 const int N = embd_inp.size();
682
683 const auto & hparams = model.hparams;
684
685 const int n_vocab = hparams.n_vocab;
686
687 struct ggml_cgraph * gf = gpt2_graph(model, n_past, embd_inp.size());
688
689 // allocate the graph tensors
690 ggml_gallocr_alloc_graph(allocr, gf);
691
692 // set the graph inputs
693 struct ggml_tensor * embd = ggml_graph_get_tensor(gf, "embd");
694 memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
695
696 struct ggml_tensor * position = ggml_graph_get_tensor(gf, "position");
697 for (int i = 0; i < N; ++i) {
698 ((int32_t *) position->data)[i] = n_past + i;
699 }
700
701 // run the computation
702 struct ggml_cplan plan = ggml_graph_plan(gf, n_threads, nullptr);
703 static std::vector<uint8_t> work_buffer;
704 work_buffer.resize(plan.work_size);
705 plan.work_data = work_buffer.data();
706 ggml_graph_compute(gf, &plan);
707
708 //if (n_past%100 == 0) {
709 // ggml_graph_print (&gf);
710 // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
711 //}
712
713 // get the graph outputs
714 struct ggml_tensor * logits = ggml_graph_get_tensor(gf, "logits");
715
716 //embd_w.resize(n_vocab*N);
717 //memcpy(embd_w.data(), ggml_get_data(logits), sizeof(float)*n_vocab*N);
718
719 // return result just for the last token
720 embd_w.resize(n_vocab);
721 memcpy(embd_w.data(), (float *) ggml_get_data(logits) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
722
723 return true;
724}
725
726int main(int argc, char ** argv) {
727 ggml_time_init();
728
729 const int64_t t_main_start_us = ggml_time_us();
730
731 gpt_params params;
732 params.model = "models/gpt-2-117M/ggml-model.bin";
733
734 if (gpt_params_parse(argc, argv, params) == false) {
735 return 1;
736 }
737
738 if (params.seed < 0) {
739 params.seed = time(NULL);
740 }
741
742 printf("%s: seed = %d\n", __func__, params.seed);
743
744 std::mt19937 rng(params.seed);
745 if (params.prompt.empty()) {
746 params.prompt = gpt_random_prompt(rng);
747 }
748
749 int64_t t_load_us = 0;
750
751 gpt_vocab vocab;
752 gpt2_model model;
753
754 // load the model
755 {
756 const int64_t t_start_us = ggml_time_us();
757
758 if (!gpt2_model_load(params.model, model, vocab)) {
759 fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
760 return 1;
761 }
762
763 t_load_us = ggml_time_us() - t_start_us;
764
765 test_gpt_tokenizer(vocab, params.token_test);
766 }
767
768 ggml_gallocr_t allocr = NULL;
769 // allocate the compute buffer
770 {
771 allocr = ggml_gallocr_new(ggml_backend_cpu_buffer_type());
772
773 // create the worst case graph for memory usage estimation
774 int n_tokens = std::min(model.hparams.n_ctx, params.n_batch);
775 int n_past = model.hparams.n_ctx - n_tokens;
776 struct ggml_cgraph * gf = gpt2_graph(model, n_past, n_tokens);
777
778 // pre-allocate the compute buffer for the worst case (optional)
779 ggml_gallocr_reserve(allocr, gf);
780 size_t mem_size = ggml_gallocr_get_buffer_size(allocr, 0);
781 fprintf(stderr, "%s: compute buffer size: %.2f MB\n", __func__, mem_size/1024.0/1024.0);
782 }
783
784 int n_past = 0;
785
786 int64_t t_sample_us = 0;
787 int64_t t_predict_us = 0;
788
789 std::vector<float> logits;
790
791 // tokenize the prompt
792 std::vector<gpt_vocab::id> embd_inp = ::gpt_tokenize(vocab, params.prompt);
793
794 params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size());
795
796 printf("%s: prompt: '%s'\n", __func__, params.prompt.c_str());
797 printf("%s: number of tokens in prompt = %zu, first 8 tokens: ", __func__, embd_inp.size());
798 for (int i = 0; i < std::min(8, (int) embd_inp.size()); i++) {
799 printf("%d ", embd_inp[i]);
800 }
801 printf("\n\n");
802
803 // submit the input prompt token-by-token
804 // this reduces the memory usage during inference, at the cost of a bit of speed at the beginning
805 std::vector<gpt_vocab::id> embd;
806
807 for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) {
808 // predict
809 if (embd.size() > 0) {
810 const int64_t t_start_us = ggml_time_us();
811
812 if (!gpt2_eval(model, allocr, params.n_threads, n_past, embd, logits)) {
813 printf("Failed to predict\n");
814 return 1;
815 }
816
817 t_predict_us += ggml_time_us() - t_start_us;
818 }
819
820 n_past += embd.size();
821 embd.clear();
822
823 if (i >= embd_inp.size()) {
824 // sample next token
825 const int top_k = params.top_k;
826 const float top_p = params.top_p;
827 const float temp = params.temp;
828
829 const int n_vocab = model.hparams.n_vocab;
830
831 gpt_vocab::id id = 0;
832
833 {
834 const int64_t t_start_sample_us = ggml_time_us();
835
836 id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p, temp, rng);
837
838 t_sample_us += ggml_time_us() - t_start_sample_us;
839 }
840
841 // add it to the context
842 embd.push_back(id);
843 } else {
844 // if here, it means we are still processing the input prompt
845 for (size_t k = i; k < embd_inp.size(); k++) {
846 embd.push_back(embd_inp[k]);
847 if (int32_t(embd.size()) >= params.n_batch) {
848 break;
849 }
850 }
851 i += embd.size() - 1;
852 }
853
854 // display text
855 for (auto id : embd) {
856 printf("%s", vocab.id_to_token[id].c_str());
857 }
858 fflush(stdout);
859
860 // end of text token
861 if (embd.back() == 50256) {
862 break;
863 }
864 }
865
866 // report timing
867 {
868 const int64_t t_main_end_us = ggml_time_us();
869
870 printf("\n\n");
871 printf("%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f);
872 printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f);
873 printf("%s: predict time = %8.2f ms / %.2f ms per token\n", __func__, t_predict_us/1000.0f, t_predict_us/1000.0f/n_past);
874 printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f);
875 }
876
877 ggml_free(model.ctx_w);
878
879 return 0;
880}