build the computation graph
| 386 | |
| 387 | // build the computation graph |
| 388 | struct ggml_cgraph * gpt2_graph( |
| 389 | const gpt2_model & model, |
| 390 | const int n_past, |
| 391 | const int n_tokens) { |
| 392 | const int N = n_tokens; |
| 393 | |
| 394 | const auto & hparams = model.hparams; |
| 395 | |
| 396 | const int n_embd = hparams.n_embd; |
| 397 | const int n_layer = hparams.n_layer; |
| 398 | const int n_ctx = hparams.n_ctx; |
| 399 | const int n_head = hparams.n_head; |
| 400 | |
| 401 | // 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 |
| 402 | static size_t buf_size = ggml_tensor_overhead()*GGML_DEFAULT_GRAPH_SIZE + ggml_graph_overhead(); |
| 403 | static std::vector<uint8_t> buf(buf_size); |
| 404 | |
| 405 | struct ggml_init_params params = { |
| 406 | /*.mem_size =*/ buf_size, |
| 407 | /*.mem_buffer =*/ buf.data(), |
| 408 | /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_gallocr_alloc_graph() |
| 409 | }; |
| 410 | |
| 411 | struct ggml_context * ctx = ggml_init(params); |
| 412 | |
| 413 | struct ggml_cgraph * gf = ggml_new_graph(ctx); |
| 414 | |
| 415 | struct ggml_tensor * embd = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N); |
| 416 | // at this point, the tensor data is not allocated yet and cannot be set |
| 417 | // we will find the tensor after the graph is allocated by its name, and set the data then |
| 418 | ggml_set_name(embd, "embd"); |
| 419 | // setting a tensor as an input will ensure that it is allocated at the beginning of the graph |
| 420 | // this is important to ensure that the input tensors are not overwritten before they are used |
| 421 | ggml_set_input(embd); |
| 422 | |
| 423 | struct ggml_tensor * position = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, N); |
| 424 | ggml_set_name(position, "position"); |
| 425 | ggml_set_input(position); |
| 426 | |
| 427 | // wte + wpe |
| 428 | struct ggml_tensor * inpL = |
| 429 | ggml_add(ctx, |
| 430 | ggml_get_rows(ctx, model.wte, embd), |
| 431 | ggml_get_rows(ctx, model.wpe, position)); |
| 432 | |
| 433 | for (int il = 0; il < n_layer; ++il) { |
| 434 | struct ggml_tensor * cur; |
| 435 | |
| 436 | // norm |
| 437 | { |
| 438 | // [ 768, N] |
| 439 | cur = ggml_norm(ctx, inpL, hparams.eps); |
| 440 | |
| 441 | // cur = ln_1_g*cur + ln_1_b |
| 442 | // [ 768, N] |
| 443 | cur = ggml_add(ctx, |
| 444 | ggml_mul(ctx, |
| 445 | ggml_repeat(ctx, model.layers[il].ln_1_g, cur), |
no test coverage detected