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

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