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-backend.cpp

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