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-batched.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-batched.cpp` 1210 lines ยท 41298 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 18 #include 19 #include 20 #include 21 #include 22 #include 23 #include 24 #include 25 #include 26 27 #if defined(_MSC_VER) 28 #pragma warning(disable: 4244 4267) // possible loss of data 29 #endif 30 31 #define GPT2_MAX_NODES 4096 32 33 static void ggml_log_callback_default(ggml_log_level level, const char * text, void * user_data) { 34 (void) level; 35 (void) user_data; 36 fputs(text, stderr); 37 fflush(stderr); 38 } 39 40 typedef int32_t gpt2_pos; 41 typedef int32_t gpt2_seq_id; 42 43 // default hparams (GPT-2 117M) 44 struct 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 54 struct 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 77 struct gpt2_kv_cell { 78 gpt2_pos pos = -1; 79 gpt2_pos delta = 0; 80 81 std::set seq_id; 82 83 bool has_seq_id(const gpt2_seq_id & id) const { 84 return seq_id.find(id) != seq_id.end(); 85 } 86 }; 87 88 struct gpt2_kv_cache { 89 // key + value memory 90 struct ggml_tensor * k; 91 struct ggml_tensor * v; 92 // 93 94 uint32_t head = 0; 95 uint32_t size = 0; 96 97 // computed before each graph build 98 uint32_t n = 0; 99 100 std::vector cells; 101 102 ggml_backend_buffer_t buffer; 103 }; 104 105 struct gpt2_model { 106 gpt2_hparams hparams; 107 108 // normalization 109 struct ggml_tensor * ln_f_g; 110 struct ggml_tensor * ln_f_b; 111 112 struct ggml_tensor * wte; // token embedding 113 struct ggml_tensor * wpe; // position embedding 114 struct ggml_tensor * lm_head; // language model head 115 116 std::vector layers; 117 118 gpt2_kv_cache kv_cache; 119 120 struct ggml_context * ctx_w; 121 122 ggml_backend_t backend = NULL; 123 124 ggml_backend_buffer_t buffer_w; 125 126 std::map tensors; 127 }; 128 129 // Input data for gpt2_decode 130 // A gpt2_batch object can contain input about one or many sequences 131 // The provided arrays (i.e. token, embd, pos, etc.) must have size of n_tokens 132 // 133 // - token : the token ids of the input (used when embd is NULL) 134 // - embd : token embeddings (i.e. float vector of size n_embd) (used when token is NULL) 135 // - pos : the positions of the respective token in the sequence 136 // - seq_id : the sequence to which the respective token belongs 137 // - logits : if zero, the logits for the respective token will not be output 138 // 139 struct gpt2_batch { 140 int32_t n_tokens = -1; 141 142 gpt_vocab::id * token = {}; 143 float * embd = {}; 144 gpt2_pos * pos = {}; 145 gpt2_seq_id * seq_id = {}; 146 int8_t * logits = {}; 147 }; 148 149 // load the model's weights from a file 150 bool gpt2_model_load(const std::string & fname, gpt2_model & model, gpt_vocab & vocab, int n_ctx, int n_gpu_layers) { 151 printf("%s: loading model from '%s'\n", __func__, fname.c_str()); 152 153 auto fin = std::ifstream(fname, std::ios::binary); 154 if (!fin) { 155 fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str()); 156 return false; 157 } 158 159 // verify magic 160 { 161 uint32_t magic; 162 fin.read((char *) &magic, sizeof(magic)); 163 if (magic != GGML_FILE_MAGIC) { 164 fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str()); 165 return false; 166 } 167 } 168 169 // load hparams 170 { 171 auto & hparams = model.hparams; 172 173 fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab)); 174 fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx)); 175 fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd)); 176 fin.read((char *) &hparams.n_head, sizeof(hparams.n_head)); 177 fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer)); 178 fin.read((char *) &hparams.ftype, sizeof(hparams.ftype)); 179 180 const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR; 181 182 printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab); 183 printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx); 184 printf("%s: n_embd = %d\n", __func__, hparams.n_embd); 185 printf("%s: n_head = %d\n", __func__, hparams.n_head); 186 printf("%s: n_layer = %d\n", __func__, hparams.n_layer); 187 printf("%s: ftype = %d\n", __func__, hparams.ftype); 188 printf("%s: qntvr = %d\n", __func__, qntvr); 189 190 hparams.ftype %= GGML_QNT_VERSION_FACTOR; 191 } 192 193 // load vocab 194 { 195 int32_t n_vocab = 0; 196 fin.read((char *) &n_vocab, sizeof(n_vocab)); 197 198 if (n_vocab != model.hparams.n_vocab) { 199 fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n", 200 __func__, fname.c_str(), n_vocab, model.hparams.n_vocab); 201 return false; 202 } 203 204 std::string word; 205 std::vector buf(128); 206 207 for (int i = 0; i < n_vocab; i++) { 208 uint32_t len; 209 fin.read((char *) &len, sizeof(len)); 210 211 buf.resize(len); 212 fin.read((char *) buf.data(), len); 213 word.assign(buf.data(), len); 214 215 vocab.token_to_id[word] = i; 216 vocab.id_to_token[i] = word; 217 } 218 } 219 220 // for the big tensors, we have the option to store the data in 16-bit floats or quantized 221 // in order to save memory and also to speed up the computation 222 ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype)); 223 if (wtype == GGML_TYPE_COUNT) { 224 fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n", 225 __func__, fname.c_str(), model.hparams.ftype); 226 return false; 227 } 228 229 auto & ctx = model.ctx_w; 230 231 size_t buffer_size = 0; 232 233 { 234 const auto & hparams = model.hparams; 235 236 const int n_embd = hparams.n_embd; 237 const int n_layer = hparams.n_layer; 238 const int n_ctx = hparams.n_ctx; 239 const int n_vocab = hparams.n_vocab; 240 241 buffer_size += ggml_row_size(GGML_TYPE_F32, n_embd); // ln_f_g 242 buffer_size += ggml_row_size(GGML_TYPE_F32, n_embd); // ln_f_b 243 244 buffer_size += ggml_row_size(wtype, n_vocab*n_embd); // wte 245 buffer_size += ggml_row_size(GGML_TYPE_F32, n_ctx*n_embd); // wpe 246 buffer_size += ggml_row_size(wtype, n_vocab*n_embd); // lm_head 247 248 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_1_g 249 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_1_b 250 251 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_2_g 252 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // ln_2_b 253 254 buffer_size += n_layer*(ggml_row_size(wtype, 3*n_embd*n_embd)); // c_attn_attn_w 255 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, 3*n_embd)); // c_attn_attn_b 256 257 buffer_size += n_layer*(ggml_row_size(wtype, n_embd*n_embd)); // c_attn_proj_w 258 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, n_embd)); // c_attn_proj_b 259 260 buffer_size += n_layer*(ggml_row_size(wtype, 4*n_embd*n_embd)); // c_mlp_fc_w 261 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, 4*n_embd)); // c_mlp_fc_b 262 263 buffer_size += n_layer*(ggml_row_size(wtype, 4*n_embd*n_embd)); // c_mlp_proj_w 264 buffer_size += n_layer*(ggml_row_size(GGML_TYPE_F32, 4*n_embd)); // c_mlp_proj_b 265 266 buffer_size += (6 + 12*n_layer)*128; // alignment overhead 267 268 printf("%s: ggml tensor size = %d bytes\n", __func__, (int) sizeof(ggml_tensor)); 269 printf("%s: backend buffer size = %6.2f MB\n", __func__, buffer_size/(1024.0*1024.0)); 270 } 271 272 ggml_log_set(ggml_log_callback_default, nullptr); 273 274 // create the ggml context 275 { 276 size_t n_tensors = 2 + 6 + 12*model.hparams.n_layer; 277 struct ggml_init_params params = { 278 /*.mem_size =*/ ggml_tensor_overhead() * n_tensors, 279 /*.mem_buffer =*/ NULL, 280 /*.no_alloc =*/ true, 281 }; 282 283 model.ctx_w = ggml_init(params); 284 if (!model.ctx_w) { 285 fprintf(stderr, "%s: ggml_init() failed\n", __func__); 286 return false; 287 } 288 } 289 290 // initialize the backend 291 #ifdef GGML_USE_CUDA 292 if (n_gpu_layers > 0) { 293 fprintf(stderr, "%s: using CUDA backend\n", __func__); 294 model.backend = ggml_backend_cuda_init(0); 295 if (!model.backend) { 296 fprintf(stderr, "%s: ggml_backend_cuda_init() failed\n", __func__); 297 } 298 } 299 #endif 300 301 #ifdef GGML_USE_METAL 302 if (n_gpu_layers > 0) { 303 fprintf(stderr, "%s: using Metal backend\n", __func__); 304 model.backend = ggml_backend_metal_init(); 305 if (!model.backend) { 306 fprintf(stderr, "%s: ggml_backend_metal_init() failed\n", __func__); 307 } 308 } 309 #endif 310 311 if (!model.backend) { 312 // fallback to CPU backend 313 fprintf(stderr, "%s: using CPU backend\n", __func__); 314 model.backend = ggml_backend_cpu_init(); 315 } 316 317 if (!model.backend) { 318 fprintf(stderr, "%s: ggml_backend_cpu_init() failed\n", __func__); 319 return false; 320 } 321 322 // allocate weights buffer 323 model.buffer_w = ggml_backend_alloc_buffer(model.backend, buffer_size); 324 325 // prepare memory for the weights 326 { 327 const auto & hparams = model.hparams; 328 329 const int n_embd = hparams.n_embd; 330 const int n_layer = hparams.n_layer; 331 const int n_ctx = hparams.n_ctx; 332 const int n_vocab = hparams.n_vocab; 333 334 model.layers.resize(n_layer); 335 336 model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 337 model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 338 339 model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab); 340 model.wpe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ctx); 341 model.lm_head = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab); 342 343 // map by name 344 model.tensors["model/ln_f/g"] = model.ln_f_g; 345 model.tensors["model/ln_f/b"] = model.ln_f_b; 346 347 model.tensors["model/wte"] = model.wte; 348 model.tensors["model/wpe"] = model.wpe; 349 model.tensors["model/lm_head"] = model.lm_head; 350 351 for (int i = 0; i < n_layer; ++i) { 352 auto & layer = model.layers[i]; 353 354 layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 355 layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 356 357 layer.ln_2_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 358 layer.ln_2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 359 360 layer.c_attn_attn_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 3*n_embd); 361 layer.c_attn_attn_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 3*n_embd); 362 363 layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd); 364 layer.c_attn_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 365 366 layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, n_embd, 4*n_embd); 367 layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd); 368 369 layer.c_mlp_proj_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd); 370 layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd); 371 372 // map by name 373 model.tensors["model/h" + std::to_string(i) + "/ln_1/g"] = layer.ln_1_g; 374 model.tensors["model/h" + std::to_string(i) + "/ln_1/b"] = layer.ln_1_b; 375 376 model.tensors["model/h" + std::to_string(i) + "/ln_2/g"] = layer.ln_2_g; 377 model.tensors["model/h" + std::to_string(i) + "/ln_2/b"] = layer.ln_2_b; 378 379 model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/w"] = layer.c_attn_attn_w; 380 model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/b"] = layer.c_attn_attn_b; 381 382 model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/w"] = layer.c_attn_proj_w; 383 model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/b"] = layer.c_attn_proj_b; 384 385 model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/w"] = layer.c_mlp_fc_w; 386 model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/b"] = layer.c_mlp_fc_b; 387 388 model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/w"] = layer.c_mlp_proj_w; 389 model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/b"] = layer.c_mlp_proj_b; 390 } 391 } 392 393 // override the default training context with the user-provided 394 model.hparams.n_ctx = n_ctx; 395 396 // key + value memory 397 { 398 const auto & hparams = model.hparams; 399 400 const int n_embd = hparams.n_embd; 401 const int n_layer = hparams.n_layer; 402 const int n_ctx = hparams.n_ctx; 403 404 const int n_mem = n_layer*n_ctx; 405 const int n_elements = n_embd*n_mem; 406 407 model.kv_cache.k = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements); 408 model.kv_cache.v = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements); 409 410 model.kv_cache.head = 0; 411 model.kv_cache.size = n_ctx; 412 413 model.kv_cache.cells.resize(n_ctx); 414 415 const size_t memory_size = ggml_nbytes(model.kv_cache.k) + ggml_nbytes(model.kv_cache.v); 416 417 printf("%s: memory size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem); 418 419 // create a backend buffer (can be in host or device memory) 420 model.kv_cache.buffer = ggml_backend_alloc_buffer(model.backend, memory_size + 256); 421 422 // allocate the tensors into the backend buffer 423 { 424 ggml_tallocr alloc = ggml_tallocr_new(model.kv_cache.buffer); 425 426 // this updates the pointers in the tensors to point to the correct location in the buffer 427 // this is necessary since the ggml_context is .no_alloc == true 428 // note that the buffer can actually be a device buffer, depending on the backend 429 ggml_tallocr_alloc(&alloc, model.kv_cache.k); 430 ggml_tallocr_alloc(&alloc, model.kv_cache.v); 431 } 432 } 433 434 // load weights 435 { 436 ggml_tallocr alloc = ggml_tallocr_new(model.buffer_w); 437 438 size_t total_size = 0; 439 440 bool has_lm_head = false; 441 442 std::vector read_buf; 443 444 while (true) { 445 int32_t n_dims; 446 int32_t length; 447 int32_t ttype; 448 449 fin.read(reinterpret_cast(&n_dims), sizeof(n_dims)); 450 fin.read(reinterpret_cast(&length), sizeof(length)); 451 fin.read(reinterpret_cast(&ttype), sizeof(ttype)); 452 453 if (fin.eof()) { 454 break; 455 } 456 457 int32_t nelements = 1; 458 int32_t ne[2] = { 1, 1 }; 459 for (int i = 0; i < n_dims; ++i) { 460 fin.read(reinterpret_cast(&ne[i]), sizeof(ne[i])); 461 nelements *= ne[i]; 462 } 463 464 std::string name(length, 0); 465 fin.read(&name[0], length); 466 467 if (model.tensors.find(name) == model.tensors.end()) { 468 fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str()); 469 return false; 470 } 471 472 auto tensor = model.tensors[name]; 473 ggml_set_name(tensor, name.c_str()); 474 if (ggml_nelements(tensor) != nelements) { 475 fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str()); 476 return false; 477 } 478 479 if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) { 480 fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n", 481 __func__, name.c_str(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]); 482 return false; 483 } 484 485 // for debugging 486 if (0) { 487 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)); 488 } 489 490 const size_t bpe = ggml_type_size(ggml_type(ttype)); 491 492 if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) { 493 fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n", 494 __func__, name.c_str(), ggml_nbytes(tensor), nelements*bpe); 495 return false; 496 } 497 498 ggml_tallocr_alloc(&alloc, tensor); 499 500 if (ggml_backend_is_cpu (model.backend) 501 #ifdef GGML_USE_METAL 502 || ggml_backend_is_metal(model.backend) 503 #endif 504 ) { 505 // for the CPU and Metal backend, we can read directly into the tensor 506 fin.read(reinterpret_cast(tensor->data), ggml_nbytes(tensor)); 507 } else { 508 // read into a temporary buffer first, then copy to device memory 509 read_buf.resize(ggml_nbytes(tensor)); 510 fin.read(read_buf.data(), ggml_nbytes(tensor)); 511 ggml_backend_tensor_set(tensor, read_buf.data(), 0, ggml_nbytes(tensor)); 512 } 513 514 // GPT-2 models share the WTE tensor as the LM head 515 if (name == "model/wte" && has_lm_head == false) { 516 //ggml_tallocr_alloc(alloc, model.lm_head); 517 //ggml_backend_tensor_copy(tensor, model.lm_head); 518 model.lm_head = tensor; 519 } 520 521 if (name == "model/lm_head") { 522 has_lm_head = true; 523 } 524 525 total_size += ggml_nbytes(tensor); 526 } 527 528 printf("%s: model size = %8.2f MB\n", __func__, total_size/1024.0/1024.0); 529 } 530 531 fin.close(); 532 533 return true; 534 } 535 536 // build the computation graph 537 struct ggml_cgraph * gpt2_graph( 538 const gpt2_model & model, 539 const gpt2_batch & batch, 540 bool measure) { 541 const auto & hparams = model.hparams; 542 543 const int n_embd = hparams.n_embd; 544 const int n_layer = hparams.n_layer; 545 const int n_ctx = hparams.n_ctx; 546 const int n_head = hparams.n_head; 547 548 const auto & kv_cache = model.kv_cache; 549 550 const int32_t n_tokens = batch.n_tokens; 551 const int32_t n_kv = measure ? n_ctx : kv_cache.n; 552 const int32_t kv_head = measure ? n_ctx - n_tokens : kv_cache.head; 553 554 // 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 555 static size_t buf_size = ggml_tensor_overhead()*GPT2_MAX_NODES + ggml_graph_overhead_custom(GPT2_MAX_NODES, false); 556 static std::vector buf(buf_size); 557 558 struct ggml_init_params params = { 559 /*.mem_size =*/ buf_size, 560 /*.mem_buffer =*/ buf.data(), 561 /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_gallocr_alloc_graph() 562 }; 563 564 struct ggml_context * ctx = ggml_init(params); 565 566 struct ggml_cgraph * gf = ggml_new_graph_custom(ctx, GPT2_MAX_NODES, false); 567 568 struct ggml_tensor * inpL; 569 if (batch.token) { 570 struct ggml_tensor * inp_tokens = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_tokens); 571 ggml_set_name(inp_tokens, "inp_tokens"); 572 ggml_set_input(inp_tokens); 573 574 struct ggml_tensor * position = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, n_tokens); 575 ggml_set_name(position, "position"); 576 ggml_set_input(position); 577 578 // wte + wpe 579 inpL = 580 ggml_add(ctx, 581 ggml_get_rows(ctx, model.wte, inp_tokens), 582 ggml_get_rows(ctx, model.wpe, position)); 583 } else { 584 GGML_ASSERT(batch.embd); 585 586 inpL = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_tokens); 587 ggml_set_name(inpL, "embd"); 588 ggml_set_input(inpL); 589 } 590 591 // KQ_mask (mask for 1 head, it will be broadcasted to all heads) 592 struct ggml_tensor * KQ_mask = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, n_kv, n_tokens, 1); 593 ggml_set_name(KQ_mask, "KQ_mask"); 594 ggml_set_input(KQ_mask); 595 596 597 for (int il = 0; il < n_layer; ++il) { 598 struct ggml_tensor * cur; 599 600 // norm 601 { 602 // [ 768, N] 603 cur = ggml_norm(ctx, inpL, hparams.eps); 604 605 // cur = ln_1_g*cur + ln_1_b 606 // [ 768, N] 607 cur = ggml_add(ctx, 608 ggml_mul(ctx, 609 cur, 610 model.layers[il].ln_1_g), 611 model.layers[il].ln_1_b); 612 } 613 614 // attn 615 // [2304, 768] - model.layers[il].c_attn_attn_w 616 // [2304, 1] - model.layers[il].c_attn_attn_b 617 // [ 768, n_tokens] - cur (in) 618 // [2304, n_tokens] - cur (out) 619 // 620 // cur = attn_w*cur + attn_b 621 // [2304, n_tokens] 622 { 623 cur = ggml_mul_mat(ctx, 624 model.layers[il].c_attn_attn_w, 625 cur); 626 627 cur = ggml_add(ctx, 628 cur, 629 model.layers[il].c_attn_attn_b); 630 } 631 632 // self-attention 633 { 634 struct ggml_tensor * Qcur = ggml_view_2d(ctx, cur, n_embd, n_tokens, cur->nb[1], 0*sizeof(float)*n_embd); 635 struct ggml_tensor * Kcur = ggml_view_2d(ctx, cur, n_embd, n_tokens, cur->nb[1], 1*sizeof(float)*n_embd); 636 struct ggml_tensor * Vcur = ggml_view_2d(ctx, cur, n_embd, n_tokens, cur->nb[1], 2*sizeof(float)*n_embd); 637 638 // store key and value to memory 639 if (n_tokens >= 1) { 640 struct ggml_tensor * k = ggml_view_1d(ctx, model.kv_cache.k, n_tokens*n_embd, (ggml_element_size(model.kv_cache.k)*n_embd)*(il*n_ctx + kv_head)); 641 struct ggml_tensor * v = ggml_view_1d(ctx, model.kv_cache.v, n_tokens*n_embd, (ggml_element_size(model.kv_cache.v)*n_embd)*(il*n_ctx + kv_head)); 642 643 ggml_build_forward_expand(gf, ggml_cpy(ctx, Kcur, k)); 644 ggml_build_forward_expand(gf, ggml_cpy(ctx, Vcur, v)); 645 } 646 647 // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3) 648 // [64, N, 12] 649 struct ggml_tensor * Q = 650 ggml_permute(ctx, 651 ggml_cont_3d(ctx, 652 Qcur, 653 n_embd/n_head, n_head, n_tokens), 654 0, 2, 1, 3); 655 656 // K = Kmem.view(n_embd/n_head, n_head, n_kv).permute(0, 2, 1, 3) 657 // [64, n_kv, 12] 658 struct ggml_tensor * K = 659 ggml_permute(ctx, 660 ggml_reshape_3d(ctx, 661 ggml_view_1d(ctx, model.kv_cache.k, n_kv*n_embd, il*n_ctx*ggml_element_size(model.kv_cache.k)*n_embd), 662 n_embd/n_head, n_head, n_kv), 663 0, 2, 1, 3); 664 665 // GG: flash attention 666 //struct ggml_tensor * V = 667 // ggml_cpy(ctx0, 668 // ggml_permute(ctx0, 669 // ggml_reshape_3d(ctx0, 670 // ggml_view_1d(ctx0, model.kv_cache.v, n_kv*n_embd, il*n_ctx*ggml_element_size(model.kv_cache.v)*n_embd), 671 // n_embd/n_head, n_head, n_kv), 672 // 1, 2, 0, 3), 673 // ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_kv, n_embd/n_head, n_head)); 674 675 //struct ggml_tensor * KQV = ggml_flash_attn(ctx0, Q, K, V, true); 676 677 // K * Q 678 // [n_kv, n_tokens, 12] 679 struct ggml_tensor * KQ = ggml_mul_mat(ctx, K, Q); 680 681 // KQ_scaled = KQ / sqrt(n_embd/n_head) 682 // [n_kv, n_tokens, 12] 683 struct ggml_tensor * KQ_scaled = 684 ggml_scale(ctx, 685 KQ, 686 1.0f/sqrtf(float(n_embd)/n_head)); 687 688 // KQ_masked = mask_past(KQ_scaled) 689 // [n_kv, n_tokens, 12] 690 struct ggml_tensor * KQ_masked = ggml_add(ctx, KQ_scaled, KQ_mask); 691 692 // KQ = soft_max(KQ_masked) 693 // [n_kv, N, 12] 694 struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx, KQ_masked); 695 696 // V_trans = Vmem.view(n_embd/n_head, n_head, n_kv).permute(1, 2, 0, 3).contiguous() 697 // [n_kv, 64, 12] 698 struct ggml_tensor * V_trans = 699 ggml_cont_3d(ctx, 700 ggml_permute(ctx, 701 ggml_reshape_3d(ctx, 702 ggml_view_1d(ctx, model.kv_cache.v, n_kv*n_embd, il*n_ctx*ggml_element_size(model.kv_cache.v)*n_embd), 703 n_embd/n_head, n_head, n_kv), 704 1, 2, 0, 3), 705 n_kv, n_embd/n_head, n_head); 706 707 // KQV = transpose(V) * KQ_soft_max 708 // [64, n_tokens, 12] 709 struct ggml_tensor * KQV = ggml_mul_mat(ctx, V_trans, KQ_soft_max); 710 711 // KQV_merged = KQV.permute(0, 2, 1, 3) 712 // [64, 12, n_tokens] 713 struct ggml_tensor * KQV_merged = ggml_permute(ctx, KQV, 0, 2, 1, 3); 714 715 // cur = KQV_merged.contiguous().view(n_embd, N) 716 // [768, n_tokens] 717 cur = ggml_cont_2d(ctx, KQV_merged, n_embd, n_tokens); 718 } 719 720 // projection 721 // [ 768, 768] - model.layers[il].c_attn_proj_w 722 // [ 768, 1] - model.layers[il].c_attn_proj_b 723 // [ 768, N] - cur (in) 724 // [ 768, N] - cur (out) 725 // 726 // cur = proj_w*cur + proj_b 727 // [768, N] 728 { 729 cur = ggml_mul_mat(ctx, 730 model.layers[il].c_attn_proj_w, 731 cur); 732 733 cur = ggml_add(ctx, 734 cur, 735 model.layers[il].c_attn_proj_b); 736 } 737 738 // add the input 739 cur = ggml_add(ctx, cur, inpL); 740 741 struct ggml_tensor * inpFF = cur; 742 743 // feed-forward network 744 { 745 // norm 746 { 747 cur = ggml_norm(ctx, inpFF, hparams.eps); 748 749 // cur = ln_2_g*cur + ln_2_b 750 // [ 768, N] 751 cur = ggml_add(ctx, 752 ggml_mul(ctx, 753 cur, 754 model.layers[il].ln_2_g), 755 model.layers[il].ln_2_b); 756 } 757 758 // fully connected 759 // [3072, 768] - model.layers[il].c_mlp_fc_w 760 // [3072, 1] - model.layers[il].c_mlp_fc_b 761 // [ 768, N] - cur (in) 762 // [3072, N] - cur (out) 763 // 764 // cur = fc_w*cur + fc_b 765 // [3072, N] 766 cur = ggml_mul_mat(ctx, 767 model.layers[il].c_mlp_fc_w, 768 cur); 769 770 cur = ggml_add(ctx, 771 cur, 772 model.layers[il].c_mlp_fc_b); 773 774 // GELU activation 775 // [3072, N] 776 cur = ggml_gelu(ctx, cur); 777 778 // projection 779 // [ 768, 3072] - model.layers[il].c_mlp_proj_w 780 // [ 768, 1] - model.layers[il].c_mlp_proj_b 781 // [3072, N] - cur (in) 782 // [ 768, N] - cur (out) 783 // 784 // cur = proj_w*cur + proj_b 785 // [768, N] 786 cur = ggml_mul_mat(ctx, 787 model.layers[il].c_mlp_proj_w, 788 cur); 789 790 cur = ggml_add(ctx, 791 cur, 792 model.layers[il].c_mlp_proj_b); 793 } 794 795 // input for next layer 796 inpL = ggml_add(ctx, cur, inpFF); 797 } 798 799 // norm 800 { 801 // [ 768, N] 802 inpL = ggml_norm(ctx, inpL, hparams.eps); 803 804 // inpL = ln_f_g*inpL + ln_f_b 805 // [ 768, N] 806 inpL = ggml_add(ctx, 807 ggml_mul(ctx, 808 inpL, 809 model.ln_f_g), 810 model.ln_f_b); 811 } 812 813 // inpL = WTE * inpL 814 // [ 768, 50257] - model.lm_head 815 // [ 768, N] - inpL 816 inpL = ggml_mul_mat(ctx, model.lm_head, inpL); 817 818 // logits -> probs 819 //inpL = ggml_soft_max(ctx0, inpL); 820 821 ggml_build_forward_expand(gf, inpL); 822 823 ggml_free(ctx); 824 825 return gf; 826 } 827 828 static void gpt2_kv_cache_seq_cp( 829 struct gpt2_kv_cache & cache, 830 gpt2_seq_id seq_id_src, 831 gpt2_seq_id seq_id_dst, 832 gpt2_pos p0, 833 gpt2_pos p1) { 834 if (p0 < 0) p0 = 0; 835 if (p1 < 0) p1 = std::numeric_limits::max(); 836 837 for (uint32_t i = 0; i < cache.size; ++i) { 838 if (cache.cells[i].has_seq_id(seq_id_src) && cache.cells[i].pos >= p0 && cache.cells[i].pos < p1) { 839 cache.cells[i].seq_id.insert(seq_id_dst); 840 } 841 } 842 } 843 844 struct gpt2_batch gpt2_batch_init(int32_t n_tokens, int32_t embd) { 845 gpt2_batch batch; 846 847 if (embd) { 848 batch.embd = (float *) malloc(sizeof(float) * n_tokens * embd); 849 } else { 850 batch.token = (gpt_vocab::id *) malloc(sizeof(gpt_vocab::id) * n_tokens); 851 } 852 853 batch.pos = (gpt2_pos *) malloc(sizeof(gpt2_pos) * n_tokens); 854 batch.seq_id = (gpt2_seq_id *) malloc(sizeof(gpt2_seq_id) * n_tokens); 855 batch.logits = (int8_t *) malloc(sizeof(int8_t) * n_tokens); 856 857 return batch; 858 } 859 860 void gpt2_batch_free(struct gpt2_batch batch) { 861 if (batch.token) free(batch.token); 862 if (batch.embd) free(batch.embd); 863 if (batch.pos) free(batch.pos); 864 if (batch.seq_id) free(batch.seq_id); 865 if (batch.logits) free(batch.logits); 866 } 867 868 // Positive return values does not mean a fatal error, but rather a warning. 869 // 0 - success 870 // < 0 - error 871 int gpt2_decode( 872 struct gpt2_model & model, 873 ggml_gallocr_t allocr, 874 struct gpt2_batch batch, 875 int n_threads, 876 std::vector & logits) { 877 const int32_t n_tokens = batch.n_tokens; 878 const auto & hparams = model.hparams; 879 const int n_vocab = hparams.n_vocab; 880 881 if (n_tokens == 0) { 882 printf("%s: n_tokens == 0", __func__); 883 return -1; 884 } 885 886 GGML_ASSERT((!batch.token && batch.embd) || (batch.token && !batch.embd)); 887 888 auto & cache = model.kv_cache; 889 890 for (int i = 0; i < n_tokens; i++) { 891 cache.cells[cache.head + i].pos = batch.pos[i]; 892 cache.cells[cache.head + i].seq_id.insert(batch.seq_id[i]); 893 } 894 895 cache.n = cache.head + n_tokens; 896 897 struct ggml_cgraph * gf = gpt2_graph(model, batch, false); 898 899 // allocate tensors 900 ggml_gallocr_alloc_graph(allocr, gf); 901 902 // set the graph inputs 903 if (batch.token) { 904 struct ggml_tensor * inp_tokens = ggml_graph_get_tensor(gf, "inp_tokens"); 905 ggml_backend_tensor_set(inp_tokens, batch.token, 0, n_tokens*ggml_element_size(inp_tokens)); 906 907 struct ggml_tensor * position = ggml_graph_get_tensor(gf, "position"); 908 for (int i = 0; i < n_tokens; ++i) { 909 int32_t v = batch.pos[i]; 910 ggml_backend_tensor_set(position, &v, i*sizeof(int32_t), sizeof(v)); 911 } 912 } else { 913 struct ggml_tensor * embd = ggml_graph_get_tensor(gf, "embd"); 914 ggml_backend_tensor_set(embd, batch.embd, 0, n_tokens * hparams.n_embd * ggml_element_size(embd)); 915 } 916 917 { 918 struct ggml_tensor * KQ_mask = ggml_graph_get_tensor(gf, "KQ_mask"); 919 const auto & kv_cache = model.kv_cache; 920 const int32_t n_tokens = batch.n_tokens; 921 const int32_t n_kv = kv_cache.n; 922 923 std::vector data_buf(n_kv*n_tokens); 924 const float neg_inf_v = -INFINITY; 925 926 for (int h = 0; h < 1; ++h) { 927 int h_offset = h*(n_kv*n_tokens); 928 for (int j = 0; j < n_tokens; ++j) { 929 const gpt2_pos pos = batch.pos[j]; 930 const gpt2_seq_id seq_id = batch.seq_id[j]; 931 932 for (int i = 0; i < n_kv; ++i) { 933 if (!kv_cache.cells[i].has_seq_id(seq_id) || kv_cache.cells[i].pos > pos) { 934 data_buf[h_offset + j*n_kv + i] = neg_inf_v; 935 } 936 } 937 } 938 } 939 940 ggml_backend_tensor_set(KQ_mask, data_buf.data(), 0, data_buf.size() * sizeof(float)); 941 } 942 943 // run the computation 944 if (ggml_backend_is_cpu(model.backend)) { 945 ggml_backend_cpu_set_n_threads(model.backend, n_threads); 946 } 947 ggml_backend_graph_compute(model.backend, gf); 948 949 //if (n_past%100 == 0) { 950 // ggml_graph_print (&gf); 951 // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot"); 952 //} 953 954 // in this case, the output tensor is the last one in the graph 955 struct ggml_tensor * inpL = ggml_graph_node(gf, -1); 956 957 if (batch.logits) { 958 // return logits for all tokens 959 logits.resize(n_vocab*n_tokens); 960 for (int32_t i = 0; i < n_tokens; i++) { 961 if (batch.logits[i] == 0) { 962 continue; 963 } 964 ggml_backend_tensor_get(inpL, logits.data() + n_vocab*i, n_vocab*i*sizeof(float), sizeof(float)*n_vocab); 965 } 966 } else { 967 // return result just for the last token 968 logits.resize(n_vocab); 969 ggml_backend_tensor_get(inpL, logits.data(), (n_vocab*(n_tokens-1))*sizeof(float), sizeof(float)*n_vocab); 970 } 971 972 // update the kv ring buffer 973 cache.head += n_tokens; 974 975 // ensure kv cache head points to a valid index. 976 if (cache.head >= cache.size) { 977 printf("%s: cache.head >= cache.size\n", __func__); 978 return -2; 979 } 980 981 return 0; 982 } 983 984 int main(int argc, char ** argv) { 985 ggml_time_init(); 986 987 const int64_t t_main_start_us = ggml_time_us(); 988 989 gpt_params params; 990 991 if (gpt_params_parse(argc, argv, params) == false) { 992 return 1; 993 } 994 995 if (params.seed < 0) { 996 params.seed = time(NULL); 997 } 998 999 printf("%s: seed = %d\n", __func__, params.seed); 1000 1001 std::mt19937 rng(params.seed); 1002 if (params.prompt.empty()) { 1003 params.prompt = gpt_random_prompt(rng); 1004 } 1005 1006 int64_t t_load_us = 0; 1007 1008 gpt_vocab vocab; 1009 gpt2_model model; 1010 1011 // load the model 1012 { 1013 const int64_t t_start_us = ggml_time_us(); 1014 1015 if (!gpt2_model_load(params.model, model, vocab, params.n_ctx, params.n_gpu_layers)) { 1016 fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str()); 1017 return 1; 1018 } 1019 1020 t_load_us = ggml_time_us() - t_start_us; 1021 1022 test_gpt_tokenizer(vocab, params.token_test); 1023 } 1024 1025 // tokenize the prompt 1026 std::vector embd_inp = ::gpt_tokenize(vocab, params.prompt); 1027 1028 const int n_parallel = params.n_parallel; 1029 const int n_batch_max = std::max(embd_inp.size(), (size_t)n_parallel); 1030 1031 // create a gpt2_batch 1032 // we use this object to submit token data for decoding 1033 gpt2_batch batch = gpt2_batch_init(n_batch_max, 0); 1034 1035 // prepare required memory and allocate the compute buffer 1036 ggml_gallocr_t allocr = NULL; 1037 { 1038 // create an allocator to measure the memory usage 1039 allocr = ggml_gallocr_new(ggml_backend_get_default_buffer_type(model.backend)); 1040 1041 // create the worst case graph for memory usage estimation 1042 batch.n_tokens = n_batch_max; 1043 struct ggml_cgraph * gf = gpt2_graph(model, batch, true); 1044 1045 // pre-allocate the compute buffer for the worst case (optional) 1046 ggml_gallocr_reserve(allocr, gf); 1047 size_t mem_size = ggml_gallocr_get_buffer_size(allocr, 0); 1048 fprintf(stderr, "%s: compute buffer size: %.2f MB\n", __func__, mem_size/1024.0/1024.0); 1049 } 1050 1051 int64_t t_sample_us = 0; 1052 int64_t t_predict_us = 0; 1053 1054 std::vector logits; 1055 1056 // evaluate the initial prompt 1057 batch.n_tokens = embd_inp.size(); 1058 1059 for (int32_t i = 0; i < batch.n_tokens; i++) { 1060 batch.token[i] = embd_inp[i]; 1061 batch.pos[i] = i; 1062 batch.seq_id[i] = 0; 1063 batch.logits[i] = false; 1064 } 1065 1066 // gpt2_decode will output logits only for the last token of the prompt 1067 batch.logits[batch.n_tokens - 1] = true; 1068 1069 if (gpt2_decode(model, allocr, batch, params.n_threads, logits) != 0) { 1070 printf("%s: gpt2_decode() failed\n", __func__); 1071 return 1; 1072 } 1073 1074 // assign the system KV cache to all parallel sequences 1075 // this way, the parallel sequences will "reuse" the prompt tokens without having to copy them 1076 for (int32_t i = 1; i < n_parallel; ++i) { 1077 gpt2_kv_cache_seq_cp(model.kv_cache, 0, i, 0, batch.n_tokens); 1078 } 1079 1080 if (n_parallel > 1) { 1081 printf("\n\n%s: generating %d sequences ...\n", __func__, n_parallel); 1082 } 1083 1084 params.n_predict = std::min(params.n_predict, model.hparams.n_ctx - (int) embd_inp.size()); 1085 1086 printf("%s: prompt: '%s'\n", __func__, params.prompt.c_str()); 1087 printf("%s: number of tokens in prompt = %zu, first 8 tokens: ", __func__, embd_inp.size()); 1088 for (int i = 0; i < std::min(8, (int) embd_inp.size()); i++) { 1089 printf("%d ", embd_inp[i]); 1090 } 1091 printf("\n\n"); 1092 1093 std::vector streams(n_parallel); 1094 1095 // remember the batch index of the last token for each parallel sequence 1096 // we need this to determine which logits to sample from 1097 std::vector i_batch(n_parallel, batch.n_tokens - 1); 1098 1099 int n_cur = batch.n_tokens; 1100 int n_len = batch.n_tokens + params.n_predict; 1101 int n_decoded = 0; 1102 1103 const int n_vocab = model.hparams.n_vocab; 1104 const int top_k = params.top_k; 1105 const float top_p = params.top_p; 1106 const float temp = params.temp; 1107 1108 while (n_cur < n_len) { 1109 batch.n_tokens = 0; 1110 1111 for (int32_t i = 0; i < n_parallel; ++i) { 1112 if (i_batch[i] < 0) { 1113 // the stream has already finished 1114 continue; 1115 } 1116 1117 auto * logits_i = logits.data() + i_batch[i]*n_vocab; 1118 1119 gpt_vocab::id id = 0; 1120 { 1121 const int64_t t_start_sample_us = ggml_time_us(); 1122 1123 id = gpt_sample_top_k_top_p(vocab, logits_i, top_k, top_p, temp, rng); 1124 1125 t_sample_us += ggml_time_us() - t_start_sample_us; 1126 } 1127 1128 // is it an end of stream? -> mark the stream as finished 1129 if ((!params.ignore_eos && id == 50256) || n_cur == n_len - 1) { 1130 i_batch[i] = -1; 1131 printf("\n"); 1132 if (n_parallel > 1) { 1133 printf("%s: stream %d finished at n_cur = %d", __func__, i, n_cur); 1134 } 1135 1136 continue; 1137 } 1138 1139 auto& token = vocab.id_to_token[id]; 1140 if (n_parallel == 1) { 1141 printf("%s", token.c_str()); 1142 fflush(stdout); 1143 } 1144 1145 streams[i] += token; 1146 1147 // push this new token for next evaluation 1148 batch.token [batch.n_tokens] = id; 1149 batch.pos [batch.n_tokens] = n_cur; 1150 batch.seq_id[batch.n_tokens] = i; 1151 batch.logits[batch.n_tokens] = true; 1152 1153 i_batch[i] = batch.n_tokens; 1154 1155 batch.n_tokens += 1; 1156 1157 n_decoded += 1; 1158 } 1159 1160 // all streams are finished 1161 if (batch.n_tokens == 0) { 1162 break; 1163 } 1164 1165 n_cur += 1; 1166 1167 { 1168 const int64_t t_start_us = ggml_time_us(); 1169 1170 // evaluate the current batch with the transformer model 1171 int ret_code = gpt2_decode(model, allocr, batch, params.n_threads, logits); 1172 if (ret_code != 0) { 1173 fprintf(stderr, "%s : failed to eval, return code %d\n", __func__, ret_code); 1174 return 1; 1175 } 1176 1177 t_predict_us += ggml_time_us() - t_start_us; 1178 } 1179 } 1180 1181 if (n_parallel > 1) { 1182 printf("\n"); 1183 1184 for (int32_t i = 0; i < n_parallel; ++i) { 1185 printf("sequence %d:\n\n%s%s\n\n", i, params.prompt.c_str(), streams[i].c_str()); 1186 } 1187 } 1188 1189 // report timing 1190 { 1191 const int64_t t_main_end_us = ggml_time_us(); 1192 1193 printf("\n\n"); 1194 printf("%s: n_decoded = %8d\n", __func__, n_decoded); 1195 printf("%s: load time = %8.2f ms\n", __func__, t_load_us/1000.0f); 1196 printf("%s: sample time = %8.2f ms\n", __func__, t_sample_us/1000.0f); 1197 printf("%s: predict time = %8.2f ms\n", __func__, t_predict_us/1000.0f); 1198 printf("%s: total time = %8.2f ms\n", __func__, (t_main_end_us - t_main_start_us)/1000.0f); 1199 } 1200 1201 gpt2_batch_free(batch); 1202 ggml_free(model.ctx_w); 1203 1204 ggml_gallocr_free(allocr); 1205 ggml_backend_buffer_free(model.buffer_w); 1206 ggml_backend_buffer_free(model.kv_cache.buffer); 1207 ggml_backend_free(model.backend); 1208 1209 return 0; 1210 }