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-j/main.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-j / main.cpp` 755 lines ยท 26185 bytes Raw Blame History 1 #include "ggml.h" 2 #include "ggml-cpu.h" 3 4 #include "common.h" 5 #include "common-ggml.h" 6 7 #include 8 #include 9 #include 10 #include 11 #include 12 #include 13 #include 14 #include 15 16 #if defined(_MSC_VER) 17 #pragma warning(disable: 4244 4267) // possible loss of data 18 #endif 19 20 21 // default hparams (GPT-J 6B) 22 struct gptj_hparams { 23 int32_t n_vocab = 50400; 24 int32_t n_ctx = 2048; 25 int32_t n_embd = 4096; 26 int32_t n_head = 16; 27 int32_t n_layer = 28; 28 int32_t n_rot = 64; 29 int32_t ftype = 1; 30 float eps = 1e-5f; 31 }; 32 33 struct gptj_layer { 34 // normalization 35 struct ggml_tensor * ln_1_g; 36 struct ggml_tensor * ln_1_b; 37 38 // attention 39 struct ggml_tensor * c_attn_q_proj_w; 40 struct ggml_tensor * c_attn_k_proj_w; 41 struct ggml_tensor * c_attn_v_proj_w; 42 43 struct ggml_tensor * c_attn_proj_w; 44 45 // ff 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 gptj_model { 54 gptj_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 62 struct ggml_tensor * lmh_g; // language model head 63 struct ggml_tensor * lmh_b; // language model bias 64 65 std::vector layers; 66 67 // key + value memory 68 struct ggml_tensor * memory_k; 69 struct ggml_tensor * memory_v; 70 71 // 72 struct ggml_context * ctx; 73 std::map tensors; 74 }; 75 76 // load the model's weights from a file 77 bool gptj_model_load(const std::string & fname, gptj_model & model, gpt_vocab & vocab) { 78 printf("%s: loading model from '%s' - please wait ...\n", __func__, fname.c_str()); 79 80 auto fin = std::ifstream(fname, std::ios::binary); 81 if (!fin) { 82 fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str()); 83 return false; 84 } 85 86 // verify magic 87 { 88 uint32_t magic; 89 fin.read((char *) &magic, sizeof(magic)); 90 if (magic != GGML_FILE_MAGIC) { 91 fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str()); 92 return false; 93 } 94 } 95 96 // load hparams 97 { 98 auto & hparams = model.hparams; 99 100 fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab)); 101 fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx)); 102 fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd)); 103 fin.read((char *) &hparams.n_head, sizeof(hparams.n_head)); 104 fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer)); 105 fin.read((char *) &hparams.n_rot, sizeof(hparams.n_rot)); 106 fin.read((char *) &hparams.ftype, sizeof(hparams.ftype)); 107 108 const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR; 109 110 printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab); 111 printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx); 112 printf("%s: n_embd = %d\n", __func__, hparams.n_embd); 113 printf("%s: n_head = %d\n", __func__, hparams.n_head); 114 printf("%s: n_layer = %d\n", __func__, hparams.n_layer); 115 printf("%s: n_rot = %d\n", __func__, hparams.n_rot); 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 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; 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_embd*n_vocab); // wte 174 175 ctx_size += ggml_row_size(wtype, n_embd*n_vocab); // lmh_g 176 ctx_size += ggml_row_size(GGML_TYPE_F32, n_vocab); // lmh_b 177 178 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_1_g 179 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_1_b 180 181 ctx_size += n_layer*(ggml_row_size(wtype, n_embd*n_embd)); // c_attn_q_proj_w 182 ctx_size += n_layer*(ggml_row_size(wtype, n_embd*n_embd)); // c_attn_k_proj_w 183 ctx_size += n_layer*(ggml_row_size(wtype, n_embd*n_embd)); // c_attn_v_proj_w 184 185 ctx_size += n_layer*(ggml_row_size(wtype, n_embd*n_embd)); // c_attn_proj_w 186 187 ctx_size += n_layer*(ggml_row_size(wtype, 4*n_embd*n_embd)); // c_mlp_fc_w 188 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, 4*n_embd)); // c_mlp_fc_b 189 190 ctx_size += n_layer*(ggml_row_size(wtype, 4*n_embd*n_embd)); // c_mlp_proj_w 191 ctx_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // c_mlp_proj_b 192 193 ctx_size += n_ctx*n_layer*ggml_row_size(GGML_TYPE_F16, n_embd); // memory_k 194 ctx_size += n_ctx*n_layer*ggml_row_size(GGML_TYPE_F16, n_embd); // memory_v 195 196 ctx_size += (5 + 10*n_layer)*512; // object overhead 197 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 = ggml_init(params); 210 if (!model.ctx) { 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_vocab = hparams.n_vocab; 223 224 model.layers.resize(n_layer); 225 226 model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab); 227 228 model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 229 model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 230 231 model.lmh_g = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab); 232 model.lmh_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_vocab); 233 234 // map by name 235 model.tensors["transformer.wte.weight"] = model.wte; 236 237 model.tensors["transformer.ln_f.weight"] = model.ln_f_g; 238 model.tensors["transformer.ln_f.bias"] = model.ln_f_b; 239 240 model.tensors["lm_head.weight"] = model.lmh_g; 241 model.tensors["lm_head.bias"] = model.lmh_b; 242 243 for (int i = 0; i < n_layer; ++i) { 244 auto & layer = model.layers[i]; 245 246 layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 247 layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 248 249 layer.c_attn_q_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd); 250 layer.c_attn_k_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd); 251 layer.c_attn_v_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd); 252 253 layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd); 254 255 layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 4*n_embd); 256 layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd); 257 258 layer.c_mlp_proj_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd); 259 layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 260 261 // map by name 262 model.tensors["transformer.h." + std::to_string(i) + ".ln_1.weight"] = layer.ln_1_g; 263 model.tensors["transformer.h." + std::to_string(i) + ".ln_1.bias"] = layer.ln_1_b; 264 265 model.tensors["transformer.h." + std::to_string(i) + ".attn.q_proj.weight"] = layer.c_attn_q_proj_w; 266 model.tensors["transformer.h." + std::to_string(i) + ".attn.k_proj.weight"] = layer.c_attn_k_proj_w; 267 model.tensors["transformer.h." + std::to_string(i) + ".attn.v_proj.weight"] = layer.c_attn_v_proj_w; 268 269 model.tensors["transformer.h." + std::to_string(i) + ".attn.out_proj.weight"] = layer.c_attn_proj_w; 270 271 model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_in.weight"] = layer.c_mlp_fc_w; 272 model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_in.bias"] = layer.c_mlp_fc_b; 273 274 model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_out.weight"] = layer.c_mlp_proj_w; 275 model.tensors["transformer.h." + std::to_string(i) + ".mlp.fc_out.bias"] = layer.c_mlp_proj_b; 276 } 277 } 278 279 // key + value memory 280 { 281 const auto & hparams = model.hparams; 282 283 const int n_embd = hparams.n_embd; 284 const int n_layer = hparams.n_layer; 285 const int n_ctx = hparams.n_ctx; 286 287 const int n_mem = n_layer*n_ctx; 288 const int n_elements = n_embd*n_mem; 289 290 model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements); 291 model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F16, n_elements); 292 293 const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v); 294 295 printf("%s: memory_size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem); 296 } 297 298 // load weights 299 { 300 int n_tensors = 0; 301 size_t total_size = 0; 302 303 printf("%s: ", __func__); 304 305 while (true) { 306 int32_t n_dims; 307 int32_t length; 308 int32_t ttype; 309 310 fin.read(reinterpret_cast(&n_dims), sizeof(n_dims)); 311 fin.read(reinterpret_cast(&length), sizeof(length)); 312 fin.read(reinterpret_cast(&ttype), sizeof(ttype)); 313 314 if (fin.eof()) { 315 break; 316 } 317 318 int32_t nelements = 1; 319 int32_t ne[2] = { 1, 1 }; 320 for (int i = 0; i < n_dims; ++i) { 321 fin.read(reinterpret_cast(&ne[i]), sizeof(ne[i])); 322 nelements *= ne[i]; 323 } 324 325 std::string name(length, 0); 326 fin.read(&name[0], length); 327 328 if (model.tensors.find(name) == model.tensors.end()) { 329 fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str()); 330 return false; 331 } 332 333 auto tensor = model.tensors[name]; 334 if (ggml_nelements(tensor) != nelements) { 335 fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str()); 336 return false; 337 } 338 339 if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) { 340 fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n", 341 __func__, name.c_str(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]); 342 return false; 343 } 344 345 // for debugging 346 if (0) { 347 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)); 348 } 349 350 const size_t bpe = ggml_type_size(ggml_type(ttype)); 351 352 if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) { 353 fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n", 354 __func__, name.c_str(), ggml_nbytes(tensor), nelements*bpe); 355 return false; 356 } 357 358 fin.read(reinterpret_cast(tensor->data), ggml_nbytes(tensor)); 359 360 //printf("%42s - [%5d, %5d], type = %6s, %6.2f MB\n", name.c_str(), ne[0], ne[1], ttype == 0 ? "float" : "f16", ggml_nbytes(tensor)/1024.0/1024.0); 361 total_size += ggml_nbytes(tensor); 362 if (++n_tensors % 8 == 0) { 363 printf("."); 364 fflush(stdout); 365 } 366 } 367 368 printf(" done\n"); 369 370 printf("%s: model size = %8.2f MB / num tensors = %d\n", __func__, total_size/1024.0/1024.0, n_tensors); 371 } 372 373 fin.close(); 374 375 return true; 376 } 377 378 // evaluate the transformer 379 // 380 // - model: the model 381 // - n_threads: number of threads to use 382 // - n_past: the context size so far 383 // - embd_inp: the embeddings of the tokens in the context 384 // - embd_w: the predicted logits for the next token 385 // 386 // The GPT-J model requires about 16MB of memory per input token. 387 // 388 bool gptj_eval( 389 const gptj_model & model, 390 const int n_threads, 391 const int n_past, 392 const std::vector & embd_inp, 393 std::vector & embd_w, 394 size_t & mem_per_token) { 395 const int N = embd_inp.size(); 396 397 const auto & hparams = model.hparams; 398 399 const int n_embd = hparams.n_embd; 400 const int n_layer = hparams.n_layer; 401 const int n_ctx = hparams.n_ctx; 402 const int n_head = hparams.n_head; 403 const int n_vocab = hparams.n_vocab; 404 const int n_rot = hparams.n_rot; 405 406 static size_t buf_size = 256u*1024*1024; 407 static void * buf = malloc(buf_size); 408 409 if (mem_per_token > 0 && mem_per_token*N > buf_size) { 410 const size_t buf_size_new = 1.1*(mem_per_token*N); // add 10% to account for ggml object overhead 411 //printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new); 412 413 // reallocate 414 buf_size = buf_size_new; 415 buf = realloc(buf, buf_size); 416 if (buf == nullptr) { 417 fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size); 418 return false; 419 } 420 } 421 422 struct ggml_init_params params = { 423 /*.mem_size =*/ buf_size, 424 /*.mem_buffer =*/ buf, 425 /*.no_alloc =*/ false, 426 }; 427 428 struct ggml_context * ctx0 = ggml_init(params); 429 struct ggml_cgraph * gf = ggml_new_graph(ctx0); 430 431 // KQ_pos - contains the positions 432 struct ggml_tensor * KQ_pos = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N); 433 int * data = (int *) KQ_pos->data; 434 for (int i = 0; i < N; ++i) { 435 data[i] = n_past + i; 436 } 437 438 struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N); 439 memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd)); 440 441 // wte 442 struct ggml_tensor * inpL = ggml_get_rows(ctx0, model.wte, embd); 443 444 for (int il = 0; il < n_layer; ++il) { 445 struct ggml_tensor * cur; 446 447 // norm 448 { 449 cur = ggml_norm(ctx0, inpL, hparams.eps); 450 451 // cur = ln_1_g*cur + ln_1_b 452 cur = ggml_add(ctx0, 453 ggml_mul(ctx0, 454 ggml_repeat(ctx0, model.layers[il].ln_1_g, cur), 455 cur), 456 ggml_repeat(ctx0, model.layers[il].ln_1_b, cur)); 457 } 458 459 struct ggml_tensor * inpSA = cur; 460 461 // self-attention 462 { 463 struct ggml_tensor * Qcur = ggml_rope_inplace(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].c_attn_q_proj_w, cur), n_embd/n_head, n_head, N), KQ_pos, n_rot, 0); 464 struct ggml_tensor * Kcur = ggml_rope_inplace(ctx0, ggml_reshape_3d(ctx0, ggml_mul_mat(ctx0, model.layers[il].c_attn_k_proj_w, cur), n_embd/n_head, n_head, N), KQ_pos, n_rot, 0); 465 466 // store key and value to memory 467 { 468 struct ggml_tensor * Vcur = ggml_transpose(ctx0, ggml_mul_mat(ctx0, model.layers[il].c_attn_v_proj_w, cur)); 469 470 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)); 471 struct ggml_tensor * v = ggml_view_2d(ctx0, model.memory_v, N, n_embd, 472 ( n_ctx)*ggml_element_size(model.memory_v), 473 (il*n_ctx)*ggml_element_size(model.memory_v)*n_embd + n_past*ggml_element_size(model.memory_v)); 474 475 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Kcur, k)); 476 ggml_build_forward_expand(gf, ggml_cpy(ctx0, Vcur, v)); 477 } 478 479 // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3) 480 struct ggml_tensor * Q = 481 ggml_permute(ctx0, 482 Qcur, 483 0, 2, 1, 3); 484 485 // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3) 486 struct ggml_tensor * K = 487 ggml_permute(ctx0, 488 ggml_reshape_3d(ctx0, 489 ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd), 490 n_embd/n_head, n_head, n_past + N), 491 0, 2, 1, 3); 492 493 // K * Q 494 struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q); 495 496 // KQ_scaled = KQ / sqrt(n_embd/n_head) 497 struct ggml_tensor * KQ_scaled = 498 ggml_scale_inplace(ctx0, 499 KQ, 500 1.0f/sqrt(float(n_embd)/n_head)); 501 502 // KQ_masked = mask_past(KQ_scaled) 503 struct ggml_tensor * KQ_masked = ggml_diag_mask_inf_inplace(ctx0, KQ_scaled, n_past); 504 505 // KQ = soft_max(KQ_masked) 506 struct ggml_tensor * KQ_soft_max = ggml_soft_max_inplace(ctx0, KQ_masked); 507 508 // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous() 509 struct ggml_tensor * V = 510 ggml_view_3d(ctx0, model.memory_v, 511 n_past + N, n_embd/n_head, n_head, 512 n_ctx*ggml_element_size(model.memory_v), 513 n_ctx*ggml_element_size(model.memory_v)*n_embd/n_head, 514 il*n_ctx*ggml_element_size(model.memory_v)*n_embd); 515 516 // KQV = transpose(V) * KQ_soft_max 517 struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V, KQ_soft_max); 518 519 // KQV_merged = KQV.permute(0, 2, 1, 3) 520 struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3); 521 522 // cur = KQV_merged.contiguous().view(n_embd, N) 523 cur = ggml_cpy(ctx0, 524 KQV_merged, 525 ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N)); 526 527 // projection (no bias) 528 cur = ggml_mul_mat(ctx0, 529 model.layers[il].c_attn_proj_w, 530 cur); 531 } 532 533 struct ggml_tensor * inpFF = cur; 534 535 // feed-forward network 536 // this is independent of the self-attention result, so it could be done in parallel to the self-attention 537 { 538 // note here we pass inpSA instead of cur 539 cur = ggml_mul_mat(ctx0, 540 model.layers[il].c_mlp_fc_w, 541 inpSA); 542 543 cur = ggml_add(ctx0, 544 ggml_repeat(ctx0, model.layers[il].c_mlp_fc_b, cur), 545 cur); 546 547 // GELU activation 548 cur = ggml_gelu(ctx0, cur); 549 550 // projection 551 // cur = proj_w*cur + proj_b 552 cur = ggml_mul_mat(ctx0, 553 model.layers[il].c_mlp_proj_w, 554 cur); 555 556 cur = ggml_add(ctx0, 557 ggml_repeat(ctx0, model.layers[il].c_mlp_proj_b, cur), 558 cur); 559 } 560 561 // self-attention + FF 562 cur = ggml_add(ctx0, cur, inpFF); 563 564 // input for next layer 565 inpL = ggml_add(ctx0, cur, inpL); 566 } 567 568 // norm 569 { 570 inpL = ggml_norm(ctx0, inpL, hparams.eps); 571 572 // inpL = ln_f_g*inpL + ln_f_b 573 inpL = ggml_add(ctx0, 574 ggml_mul(ctx0, 575 ggml_repeat(ctx0, model.ln_f_g, inpL), 576 inpL), 577 ggml_repeat(ctx0, model.ln_f_b, inpL)); 578 } 579 580 // lm_head 581 { 582 inpL = ggml_mul_mat(ctx0, model.lmh_g, inpL); 583 584 inpL = ggml_add(ctx0, 585 ggml_repeat(ctx0, model.lmh_b, inpL), 586 inpL); 587 } 588 589 // logits -> probs 590 //inpL = ggml_soft_max_inplace(ctx0, inpL); 591 592 // run the computation 593 ggml_build_forward_expand(gf, inpL); 594 ggml_graph_compute_with_ctx(ctx0, gf, n_threads); 595 596 //if (n_past%100 == 0) { 597 // ggml_graph_print (&gf); 598 // ggml_graph_dump_dot(&gf, NULL, "gpt-j.dot"); 599 //} 600 601 //embd_w.resize(n_vocab*N); 602 //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N); 603 604 // return result for just the last token 605 embd_w.resize(n_vocab); 606 memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab); 607 608 if (mem_per_token == 0) { 609 mem_per_token = ggml_used_mem(ctx0)/N; 610 } 611 //printf("used_mem = %zu\n", ggml_used_mem(ctx0)); 612 613 ggml_free(ctx0); 614 615 return true; 616 } 617 618 int main(int argc, char ** argv) { 619 ggml_time_init(); 620 621 const int64_t t_main_start_us = ggml_time_us(); 622 623 gpt_params params; 624 params.model = "models/gpt-j-6B/ggml-model.bin"; 625 626 if (gpt_params_parse(argc, argv, params) == false) { 627 return 1; 628 } 629 630 if (params.seed < 0) { 631 params.seed = time(NULL); 632 } 633 634 printf("%s: seed = %d\n", __func__, params.seed); 635 636 std::mt19937 rng(params.seed); 637 if (params.prompt.empty()) { 638 params.prompt = gpt_random_prompt(rng); 639 } 640 641 int64_t t_load_us = 0; 642 643 gpt_vocab vocab; 644 gptj_model model; 645 646 // load the model 647 { 648 const int64_t t_start_us = ggml_time_us(); 649 650 if (!gptj_model_load(params.model, model, vocab)) { 651 fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str()); 652 return 1; 653 } 654 655 t_load_us = ggml_time_us() - t_start_us; 656 657 test_gpt_tokenizer(vocab, params.token_test); 658 } 659 660 int n_past = 0; 661 662 int64_t t_sample_us = 0; 663 int64_t t_predict_us = 0; 664 665 std::vector logits; 666 667 // tokenize the prompt 668 std::vector embd_inp = ::gpt_tokenize(vocab, params.prompt); 669 670 params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size()); 671 672 printf("%s: number of tokens in prompt = %zu\n", __func__, embd_inp.size()); 673 printf("\n"); 674 675 std::vector embd; 676 677 // determine the required inference memory per token: 678 size_t mem_per_token = 0; 679 gptj_eval(model, params.n_threads, 0, { 0, 1, 2, 3 }, logits, mem_per_token); 680 681 for (size_t i = embd.size(); i < embd_inp.size() + params.n_predict; i++) { 682 // predict 683 if (embd.size() > 0) { 684 const int64_t t_start_us = ggml_time_us(); 685 686 if (!gptj_eval(model, params.n_threads, n_past, embd, logits, mem_per_token)) { 687 printf("Failed to predict\n"); 688 return 1; 689 } 690 691 t_predict_us += ggml_time_us() - t_start_us; 692 } 693 694 n_past += embd.size(); 695 embd.clear(); 696 697 if (i >= embd_inp.size()) { 698 // sample next token 699 const int top_k = params.top_k; 700 const float top_p = params.top_p; 701 const float temp = params.temp; 702 703 const int n_vocab = model.hparams.n_vocab; 704 705 gpt_vocab::id id = 0; 706 707 { 708 const int64_t t_start_sample_us = ggml_time_us(); 709 710 id = gpt_sample_top_k_top_p(vocab, logits.data() + (logits.size() - n_vocab), top_k, top_p, temp, rng); 711 712 t_sample_us += ggml_time_us() - t_start_sample_us; 713 } 714 715 // add it to the context 716 embd.push_back(id); 717 } else { 718 // if here, it means we are still processing the input prompt 719 for (size_t k = i; k < embd_inp.size(); k++) { 720 embd.push_back(embd_inp[k]); 721 if (int32_t(embd.size()) > params.n_batch) { 722 break; 723 } 724 } 725 i += embd.size() - 1; 726 } 727 728 // display text 729 for (auto id : embd) { 730 printf("%s", vocab.id_to_token[id].c_str()); 731 } 732 fflush(stdout); 733 734 // end of text token 735 if (embd.back() == 50256) { 736 break; 737 } 738 } 739 740 // report timing 741 { 742 const int64_t t_main_end_us = ggml_time_us(); 743 744 printf("\n\n"); 745 printf("%s: mem per token = %8zu bytes\n", __func__, mem_per_token); 746 printf("%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f); 747 printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f); 748 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); 749 printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f); 750 } 751 752 ggml_free(model.ctx); 753 754 return 0; 755 }