| 1588 | } |
| 1589 | |
| 1590 | ggml_tensor * llm_graph_context::build_attn_mha( |
| 1591 | ggml_tensor * q, |
| 1592 | ggml_tensor * k, |
| 1593 | ggml_tensor * v, |
| 1594 | ggml_tensor * kq_b, |
| 1595 | ggml_tensor * kq_mask, |
| 1596 | ggml_tensor * sinks, |
| 1597 | ggml_tensor * v_mla, |
| 1598 | float kq_scale, |
| 1599 | int il) const { |
| 1600 | const bool v_trans = v->nb[1] > v->nb[2]; |
| 1601 | |
| 1602 | // split the batch into streams if needed |
| 1603 | const auto n_stream = k->ne[3]; |
| 1604 | |
| 1605 | q = ggml_view_4d(ctx0, q, q->ne[0], q->ne[1], q->ne[2]/n_stream, n_stream, q->nb[1], q->nb[2], q->nb[3]/n_stream, 0); |
| 1606 | |
| 1607 | q = ggml_permute(ctx0, q, 0, 2, 1, 3); |
| 1608 | k = ggml_permute(ctx0, k, 0, 2, 1, 3); |
| 1609 | v = ggml_permute(ctx0, v, 0, 2, 1, 3); |
| 1610 | |
| 1611 | ggml_tensor * cur; |
| 1612 | |
| 1613 | if (cparams.flash_attn && kq_b == nullptr) { |
| 1614 | GGML_ASSERT(kq_b == nullptr && "Flash attention does not support KQ bias yet"); |
| 1615 | |
| 1616 | if (v_trans) { |
| 1617 | v = ggml_transpose(ctx0, v); |
| 1618 | } |
| 1619 | |
| 1620 | // this can happen when KV cache is not used (e.g. an embedding model with non-causal attn) |
| 1621 | if (k->type == GGML_TYPE_F32) { |
| 1622 | k = ggml_cast(ctx0, k, GGML_TYPE_F16); |
| 1623 | } |
| 1624 | |
| 1625 | if (v->type == GGML_TYPE_F32) { |
| 1626 | v = ggml_cast(ctx0, v, GGML_TYPE_F16); |
| 1627 | } |
| 1628 | |
| 1629 | cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, hparams.f_max_alibi_bias, |
| 1630 | hparams.attn_soft_cap ? hparams.f_attn_logit_softcapping : 0.0f); |
| 1631 | cb(cur, LLAMA_TENSOR_NAME_FATTN, il); |
| 1632 | |
| 1633 | ggml_flash_attn_ext_add_sinks(cur, sinks); |
| 1634 | ggml_flash_attn_ext_set_prec (cur, GGML_PREC_F32); |
| 1635 | |
| 1636 | if (v_mla) { |
| 1637 | #if 0 |
| 1638 | // v_mla can be applied as a matrix-vector multiplication with broadcasting across dimension 3 == n_tokens. |
| 1639 | // However, the code is optimized for dimensions 0 and 1 being large, so this is ineffient. |
| 1640 | cur = ggml_reshape_4d(ctx0, cur, v_mla->ne[0], 1, n_head, n_tokens); |
| 1641 | cur = ggml_mul_mat(ctx0, v_mla, cur); |
| 1642 | #else |
| 1643 | // It's preferable to do the calculation as a matrix-matrix multiplication with n_tokens in dimension 1. |
| 1644 | // The permutations are noops and only change how the tensor data is interpreted. |
| 1645 | cur = ggml_permute(ctx0, cur, 0, 2, 1, 3); |
| 1646 | cur = ggml_mul_mat(ctx0, v_mla, cur); |
| 1647 | cb(cur, "fattn_mla", il); |
nothing calls this directly
no test coverage detected