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