1#include "models.h"
2
3llm_build_refact::llm_build_refact(const llama_model & model, const llm_graph_params & params) : llm_graph_context(params) {
4 const int64_t n_embd_head = hparams.n_embd_head_v;
5
6 GGML_ASSERT(n_embd_head == hparams.n_embd_head_k);
7
8 ggml_tensor * cur;
9 ggml_tensor * inpL;
10
11 inpL = build_inp_embd(tok_embd: model.tok_embd);
12
13 auto * inp_attn = build_attn_inp_kv();
14
15 ggml_tensor * inp_out_ids = build_inp_out_ids();
16
17 for (int il = 0; il < n_layer; ++il) {
18 ggml_tensor * inpSA = inpL;
19
20 cur = build_norm(cur: inpL,
21 mw: model.layers[il].attn_norm, NULL,
22 type: LLM_NORM_RMS, il);
23 cb(cur, name: "attn_norm", il);
24
25 // self-attention
26 {
27 ggml_tensor * Qcur = build_lora_mm(w: model.layers[il].wq, cur);
28 cb(cur: Qcur, name: "Qcur", il);
29
30 ggml_tensor * Kcur = build_lora_mm(w: model.layers[il].wk, cur);
31 cb(cur: Kcur, name: "Kcur", il);
32
33 ggml_tensor * Vcur = build_lora_mm(w: model.layers[il].wv, cur);
34 cb(cur: Vcur, name: "Vcur", il);
35
36 Qcur = ggml_reshape_3d(ctx: ctx0, a: Qcur, ne0: n_embd_head, ne1: n_head, ne2: n_tokens);
37 Kcur = ggml_reshape_3d(ctx: ctx0, a: Kcur, ne0: n_embd_head, ne1: n_head_kv, ne2: n_tokens);
38 Vcur = ggml_reshape_3d(ctx: ctx0, a: Vcur, ne0: n_embd_head, ne1: n_head_kv, ne2: n_tokens);
39
40 cb(cur: Qcur, name: "Qcur", il);
41 cb(cur: Kcur, name: "Kcur", il);
42 cb(cur: Vcur, name: "Vcur", il);
43
44 cur = build_attn(inp: inp_attn,
45 wo: model.layers[il].wo, NULL,
46 q_cur: Qcur, k_cur: Kcur, v_cur: Vcur, kq_b: nullptr, sinks: nullptr, v_mla: nullptr, kq_scale: 1.0f/sqrtf(x: float(n_embd_head)), il);
47 }
48 if (il == n_layer - 1 && inp_out_ids) {
49 cur = ggml_get_rows(ctx: ctx0, a: cur, b: inp_out_ids);
50 inpSA = ggml_get_rows(ctx: ctx0, a: inpSA, b: inp_out_ids);
51 }
52 ggml_tensor * ffn_inp = ggml_add(ctx: ctx0, a: cur, b: inpSA);
53 cb(cur: ffn_inp, name: "ffn_inp", il);
54
55 // feed-forward network
56 {
57 cur = build_norm(cur: ffn_inp,
58 mw: model.layers[il].ffn_norm, NULL,
59 type: LLM_NORM_RMS, il);
60 cb(cur, name: "ffn_norm", il);
61
62 cur = build_ffn(cur,
63 up: model.layers[il].ffn_up, NULL, NULL,
64 gate: model.layers[il].ffn_gate, NULL, NULL,
65 down: model.layers[il].ffn_down, NULL, NULL,
66 NULL,
67 type_op: LLM_FFN_SILU, type_gate: LLM_FFN_PAR, il);
68 cb(cur, name: "ffn_out", il);
69 }
70 cur = ggml_add(ctx: ctx0, a: cur, b: ffn_inp);
71
72 cur = build_cvec(cur, il);
73 cb(cur, name: "l_out", il);
74
75 // input for next layer
76 inpL = cur;
77 }
78 cur = inpL;
79
80 cur = build_norm(cur,
81 mw: model.output_norm, NULL,
82 type: LLM_NORM_RMS, il: -1);
83
84 cb(cur, name: "result_norm", il: -1);
85 res->t_embd = cur;
86
87 // lm_head
88 cur = build_lora_mm(w: model.output, cur);
89
90 cb(cur, name: "result_output", il: -1);
91 res->t_logits = cur;
92
93 ggml_build_forward_expand(cgraph: gf, tensor: cur);
94}
95