input embeddings with optional lora
| 1361 | |
| 1362 | // input embeddings with optional lora |
| 1363 | ggml_tensor * llm_graph_context::build_inp_embd(ggml_tensor * tok_embd) const { |
| 1364 | const int64_t n_embd_inp = hparams.n_embd_inp(); |
| 1365 | const int64_t n_embd = hparams.n_embd; |
| 1366 | |
| 1367 | assert(n_embd_inp >= n_embd); |
| 1368 | |
| 1369 | auto inp = std::make_unique<llm_graph_input_embd>(n_embd_inp); |
| 1370 | |
| 1371 | inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens); |
| 1372 | cb(inp->tokens, "inp_tokens", -1); |
| 1373 | ggml_set_input(inp->tokens); |
| 1374 | res->t_inp_tokens = inp->tokens; |
| 1375 | |
| 1376 | inp->embd = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd_inp, ubatch.n_tokens); |
| 1377 | cb(inp->embd, "inp_embd", -1); |
| 1378 | ggml_set_input(inp->embd); |
| 1379 | |
| 1380 | // select one of the 2 inputs, based on the batch contents |
| 1381 | // ref: https://github.com/ggml-org/llama.cpp/pull/18550 |
| 1382 | std::array<ggml_tensor *, 2> inps; |
| 1383 | |
| 1384 | // token embeddings path (ubatch.token != nullptr) |
| 1385 | { |
| 1386 | auto & cur = inps[0]; |
| 1387 | |
| 1388 | cur = ggml_get_rows(ctx0, tok_embd, inp->tokens); |
| 1389 | |
| 1390 | // apply lora for embedding tokens if needed |
| 1391 | for (const auto & lora : *loras) { |
| 1392 | llama_adapter_lora_weight * lw = lora.first->get_weight(tok_embd); |
| 1393 | if (lw == nullptr) { |
| 1394 | continue; |
| 1395 | } |
| 1396 | |
| 1397 | const float adapter_scale = lora.second; |
| 1398 | const float scale = lw->get_scale(lora.first->alpha, adapter_scale); |
| 1399 | |
| 1400 | ggml_tensor * inpL_delta = ggml_scale(ctx0, ggml_mul_mat( |
| 1401 | ctx0, lw->b, // non-transposed lora_b |
| 1402 | ggml_get_rows(ctx0, lw->a, inp->tokens) |
| 1403 | ), scale); |
| 1404 | |
| 1405 | cur = ggml_add(ctx0, cur, inpL_delta); |
| 1406 | } |
| 1407 | |
| 1408 | if (n_embd_inp != n_embd) { |
| 1409 | cur = ggml_pad(ctx0, cur, hparams.n_embd_inp() - n_embd, 0, 0, 0); |
| 1410 | } |
| 1411 | } |
| 1412 | |
| 1413 | // vector embeddings path (ubatch.embd != nullptr) |
| 1414 | { |
| 1415 | auto & cur = inps[1]; |
| 1416 | |
| 1417 | cur = inp->embd; |
| 1418 | } |
| 1419 | |
| 1420 | assert(ggml_are_same_shape (inps[0], inps[1])); |
nothing calls this directly
no test coverage detected