MCPcopy Create free account
hub / github.com/appdevforall/CodeOnTheGo / build_attn

Method build_attn

subprojects/llama.cpp/tools/mtmd/clip.cpp:578–641  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

576}
577
578ggml_tensor * clip_graph::build_attn(
579 ggml_tensor * wo,
580 ggml_tensor * wo_b,
581 ggml_tensor * q_cur,
582 ggml_tensor * k_cur,
583 ggml_tensor * v_cur,
584 ggml_tensor * kq_mask,
585 float kq_scale,
586 int il) const {
587 // these nodes are added to the graph together so that they are not reordered
588 // by doing so, the number of splits in the graph is reduced
589 ggml_build_forward_expand(gf, q_cur);
590 ggml_build_forward_expand(gf, k_cur);
591 ggml_build_forward_expand(gf, v_cur);
592
593 ggml_tensor * q = ggml_permute(ctx0, q_cur, 0, 2, 1, 3);
594 //cb(q, "q", il);
595
596 ggml_tensor * k = ggml_permute(ctx0, k_cur, 0, 2, 1, 3);
597 //cb(k, "k", il);
598
599 ggml_tensor * cur;
600
601 if (flash_attn_type == CLIP_FLASH_ATTN_TYPE_ENABLED) {
602 ggml_tensor * v = ggml_permute(ctx0, v_cur, 0, 2, 1, 3);
603
604 k = ggml_cast(ctx0, k, GGML_TYPE_F16);
605 v = ggml_cast(ctx0, v, GGML_TYPE_F16);
606
607 cur = ggml_flash_attn_ext(ctx0, q, k, v, kq_mask, kq_scale, 0.0f, 0.0f);
608 ggml_flash_attn_ext_set_prec(cur, GGML_PREC_F32);
609
610 cur = ggml_reshape_2d(ctx0, cur, cur->ne[0]*cur->ne[1], cur->ne[2]*cur->ne[3]);
611
612 } else {
613 ggml_tensor * v = ggml_permute(ctx0, v_cur, 1, 2, 0, 3);
614 v = ggml_cont(ctx0, v);
615
616 const auto n_tokens = q->ne[1];
617 const auto n_head = q->ne[2];
618
619 ggml_tensor * kq = ggml_mul_mat(ctx0, k, q);
620 // F32 may not needed for vision encoders?
621 // ggml_mul_mat_set_prec(kq, GGML_PREC_F32);
622
623 kq = ggml_soft_max_ext(ctx0, kq, kq_mask, kq_scale, 0.0f);
624
625 ggml_tensor * kqv = ggml_mul_mat(ctx0, v, kq);
626 cur = ggml_permute(ctx0, kqv, 0, 2, 1, 3);
627 cur = ggml_cont_2d(ctx0, cur, cur->ne[0]*n_head, n_tokens);
628 }
629
630 cb(cur, "kqv_out", il);
631
632 if (wo) {
633 cur = ggml_mul_mat(ctx0, wo, cur);
634 }
635

Callers

nothing calls this directly

Calls 11

ggml_permuteFunction · 0.85
ggml_castFunction · 0.85
ggml_flash_attn_extFunction · 0.85
ggml_reshape_2dFunction · 0.85
ggml_contFunction · 0.85
ggml_mul_matFunction · 0.85
ggml_soft_max_extFunction · 0.85
ggml_cont_2dFunction · 0.85
ggml_addFunction · 0.85

Tested by

no test coverage detected