Brunobkr/llama.cpp_AlgMor24_github
ΩFFFΣLLIa • llama.cpp • AlgMor24 ██████╗ ███████╗███████╗███████╗██╗ ██╗ ██╗ █████╗ ██╔═══██╗██╔════╝██╔════╝██╔════╝██║ ██║ ██║██╔══██╗ ██║ ██║█████╗ █████╗ █████╗ ██║ ██║ ██║███████║ ██║ ██║██╔══╝ ██╔══╝ ██╔══╝ ██║ ██║ ██║██╔══██║ ╚██████╔╝██║ ██║ ███████╗███████╗███████╗██║██║ ██║ ╚═════╝ ╚═╝ ╚═╝ ╚══════╝╚══════╝╚══════╝╚═╝╚═╝ ╚═╝ High-Performance LLM / VLM Inference & Autonomous Agentic Ecosystem… See the full description on the dataset page: https://huggingface.co/datasets/Brunobkr/llama.cpp_AlgMor24_github.
03k
1#include "models.h"2 3void llama_model_gemma4::load_arch_hparams(llama_model_loader & ml) {4 hparams.swa_type = LLAMA_SWA_TYPE_STANDARD;5 ml.get_key_or_arr(LLM_KV_ATTENTION_SLIDING_WINDOW_PATTERN, hparams.is_swa_impl, hparams.n_layer());6 7 uint32_t n_kv_shared_layers = 0;8 ml.get_key(LLM_KV_ATTENTION_SHARED_KV_LAYERS, n_kv_shared_layers, false);9 10 hparams.n_layer_kv_from_start = hparams.n_layer_all - (int32_t)n_kv_shared_layers;11 hparams.f_attention_scale = 1.0f; // Gemma4 uses self.scaling = 1.0 (no pre-attn scaling)12 13 ml.get_key(LLM_KV_ROPE_FREQ_BASE_SWA, hparams.rope_freq_base_train_swa, false);14 ml.get_key(LLM_KV_EXPERT_FEED_FORWARD_LENGTH, hparams.n_ff_exp, false);15 ml.get_key(LLM_KV_ATTENTION_SLIDING_WINDOW, hparams.n_swa);16 ml.get_key(LLM_KV_ATTENTION_LAYERNORM_RMS_EPS, hparams.f_norm_rms_eps);17 ml.get_key(LLM_KV_EMBEDDING_LENGTH_PER_LAYER, hparams.n_embd_per_layer);18 ml.get_key(LLM_KV_ATTENTION_KEY_LENGTH_SWA, hparams.n_embd_head_k_swa);19 ml.get_key(LLM_KV_ATTENTION_VALUE_LENGTH_SWA, hparams.n_embd_head_v_swa);20 ml.get_key(LLM_KV_FINAL_LOGIT_SOFTCAPPING, hparams.f_final_logit_softcapping, false);21 22 switch (hparams.n_layer()) {23 case 30: type = LLM_TYPE_26B_A4B; break;24 case 35: type = LLM_TYPE_E2B; break;25 case 42: type = LLM_TYPE_E4B; break;26 case 60: type = LLM_TYPE_31B; break;27 default: type = LLM_TYPE_UNKNOWN;28 }29}30 31void llama_model_gemma4::load_arch_tensors(llama_model_loader &) {32 LLAMA_LOAD_LOCALS;33 34 const uint32_t n_embd_per_layer = hparams.n_embd_per_layer;35 const int64_t n_ff_exp = hparams.n_ff_exp;36 37 if (n_embd_head_k != n_embd_head_v) {38 throw std::runtime_error("Gemma 4 requires n_embd_head_k == n_embd_head_v");39 }40 if (hparams.n_embd_head_k_swa != hparams.n_embd_head_v_swa) {41 throw std::runtime_error("Gemma 4 requires n_embd_head_k_swa == n_embd_head_v_swa");42 }43 44 output = create_tensor(tn(LLM_TENSOR_OUTPUT, "weight"), {n_embd, n_vocab}, TENSOR_NOT_REQUIRED);45 // if output is NULL, init from the input tok embed46 if (output == NULL) {47 output = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, TENSOR_DUPLICATED);48 }49 50 tok_embd = create_tensor(tn(LLM_TENSOR_TOKEN_EMBD, "weight"), {n_embd, n_vocab}, 0);51 52 if (n_embd_per_layer > 0) {53 per_layer_tok_embd = create_tensor(tn(LLM_TENSOR_PER_LAYER_TOKEN_EMBD, "weight"), {n_embd_per_layer * n_layer, n_vocab}, 0);54 per_layer_model_proj = create_tensor(tn(LLM_TENSOR_PER_LAYER_MODEL_PROJ, "weight", 0), {n_embd, n_embd_per_layer * n_layer}, 0);55 per_layer_proj_norm = create_tensor(tn(LLM_TENSOR_PER_LAYER_PROJ_NORM, "weight", 0), {n_embd_per_layer}, 0);56 }57 58 output_norm = create_tensor(tn(LLM_TENSOR_OUTPUT_NORM, "weight"), {n_embd}, 0);59 60 int rope_freqs_flag = 0;61 62 for (int i = 0; i < n_layer; ++i) {63 auto & layer = layers[i];64 const int64_t n_head = hparams.n_head(i);65 const int64_t n_embd_head = hparams.n_embd_head_k(i);66 const int64_t n_embd_k = hparams.n_embd_k_gqa(i);67 const int64_t n_embd_v = hparams.n_embd_v_gqa(i);68 const int kv_flags = hparams.has_kv(i) ? 0 : TENSOR_NOT_REQUIRED;69 70 layer.attn_norm = create_tensor(tn(LLM_TENSOR_ATTN_NORM, "weight", i), {n_embd}, 0);71 72 // note: use_alternative_attention (v_proj is optional, if it's not present, use k_proj)73 layer.wq = create_tensor(tn(LLM_TENSOR_ATTN_Q, "weight", i), {n_embd, n_embd_head * n_head}, 0);74 layer.wk = create_tensor(tn(LLM_TENSOR_ATTN_K, "weight", i), {n_embd, n_embd_k}, kv_flags);75 layer.wv = create_tensor(tn(LLM_TENSOR_ATTN_V, "weight", i), {n_embd, n_embd_v}, TENSOR_NOT_REQUIRED);76 layer.wo = create_tensor(tn(LLM_TENSOR_ATTN_OUT, "weight", i), {n_embd_head * n_head, n_embd}, 0);77 78 layer.attn_q_norm = create_tensor(tn(LLM_TENSOR_ATTN_Q_NORM, "weight", i), {n_embd_head}, 0);79 layer.attn_k_norm = create_tensor(tn(LLM_TENSOR_ATTN_K_NORM, "weight", i), {n_embd_head}, kv_flags);80 layer.attn_post_norm = create_tensor(tn(LLM_TENSOR_ATTN_POST_NORM, "weight", i), {n_embd}, 0);81 82 layer.out_scale = create_tensor(tn(LLM_TENSOR_LAYER_OUT_SCALE, "weight", i), {1u}, TENSOR_NOT_REQUIRED);83 84 if (!hparams.is_swa(i)) {85 // full_attention layers use rope_freqs for proportional rope86 layer.rope_freqs = create_tensor(tn(LLM_TENSOR_ROPE_FREQS, "weight", i), {n_embd_head/2}, rope_freqs_flag);87 rope_freqs_flag = TENSOR_DUPLICATED;88 }89 90 // handle use_double_wide_mlp91 int64_t n_ff_cur = hparams.n_ff(i);92 93 // for expert layers, we use normal FFN as shared expert (same as python code)94 layer.ffn_norm = create_tensor(tn(LLM_TENSOR_FFN_NORM, "weight", i), {n_embd}, 0);95 layer.ffn_gate = create_tensor(tn(LLM_TENSOR_FFN_GATE, "weight", i), {n_embd, n_ff_cur}, 0);96 layer.ffn_up = create_tensor(tn(LLM_TENSOR_FFN_UP, "weight", i), {n_embd, n_ff_cur}, 0);97 layer.ffn_down = create_tensor(tn(LLM_TENSOR_FFN_DOWN, "weight", i), {n_ff_cur, n_embd}, 0);98 layer.ffn_post_norm = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM, "weight", i), {n_embd}, 0);99 100 // MoE router101 layer.ffn_gate_inp = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "weight", i), {n_embd, n_expert}, TENSOR_NOT_REQUIRED);102 bool has_expert = layer.ffn_gate_inp != nullptr;103 104 // norm105 if (has_expert) {106 layer.ffn_gate_inp_s = create_tensor(tn(LLM_TENSOR_FFN_GATE_INP, "scale", i), {n_embd}, 0);107 108 layer.ffn_pre_norm_2 = create_tensor(tn(LLM_TENSOR_FFN_PRE_NORM_2, "weight", i), {n_embd}, 0);109 layer.ffn_post_norm_1 = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM_1, "weight", i), {n_embd}, 0);110 layer.ffn_post_norm_2 = create_tensor(tn(LLM_TENSOR_FFN_POST_NORM_2, "weight", i), {n_embd}, 0);111 112 // MoE FFN113 layer.ffn_gate_up_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_UP_EXPS, "weight", i), {n_embd, n_ff_exp * 2, n_expert}, TENSOR_NOT_REQUIRED);114 115 if (layer.ffn_gate_up_exps == nullptr) {116 layer.ffn_gate_exps = create_tensor(tn(LLM_TENSOR_FFN_GATE_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0);117 layer.ffn_up_exps = create_tensor(tn(LLM_TENSOR_FFN_UP_EXPS, "weight", i), {n_embd, n_ff_exp, n_expert}, 0);118 }119 120 layer.ffn_down_exps = create_tensor(tn(LLM_TENSOR_FFN_DOWN_EXPS, "weight", i), {n_ff_exp, n_embd, n_expert}, 0);121 122 // per-expert scale will be loaded as down_exps_s at the end of the current switch case123 }124 125 // per-layer embeddings126 if (n_embd_per_layer > 0) {127 layer.per_layer_inp_gate = create_tensor(tn(LLM_TENSOR_PER_LAYER_INP_GATE, "weight", i), {n_embd, n_embd_per_layer}, 0);128 layer.per_layer_proj = create_tensor(tn(LLM_TENSOR_PER_LAYER_PROJ, "weight", i), {n_embd_per_layer, n_embd}, 0);129 layer.per_layer_post_norm = create_tensor(tn(LLM_TENSOR_PER_LAYER_POST_NORM, "weight", i), {n_embd}, 0);130 }131 }132}133 134std::unique_ptr<llm_graph_context> llama_model_gemma4::build_arch_graph(const llm_graph_params & params) const {135 return std::make_unique<graph>(*this, params);136}137 138// get 2D slice view from a 3D tensor, the idx corresponds to the 3rd dim139static ggml_tensor * ggml_view_2d_slice(ggml_context * ctx0, ggml_tensor * x, int idx) {140 GGML_ASSERT(idx < (int) x->ne[2]);141 return ggml_view_2d(ctx0, x, x->ne[0], x->ne[1], ggml_row_size(x->type, x->ne[0]),142 idx * x->ne[0] * x->ne[1] * ggml_element_size(x));143}144 145llama_model_gemma4::graph::graph(const llama_model & model, const llm_graph_params & params) :146 llm_graph_context(params),147 model(model),148 n_embd_per_layer(model.hparams.n_embd_per_layer) {149 ggml_tensor * cur;150 ggml_tensor * inpL;151 152 inpL = build_inp_embd(model.tok_embd);153 154 // important: do not normalize weights for raw embeddings input (i.e. encoded image emdeddings)155 inpL = ggml_scale(ctx0, inpL, ubatch.token ? sqrtf(n_embd) : 1.0f);156 cb(inpL, "inp_scaled", -1);157 158 // inp_pos - contains the positions159 ggml_tensor * inp_pos = build_inp_pos();160 161 // TODO: is causal == true correct? might need some changes162 auto * inp_attn = build_attn_inp_kv_iswa();163 164 ggml_tensor * inp_out_ids = build_inp_out_ids();165 166 ggml_tensor * inp_per_layer = nullptr;167 if (model.per_layer_tok_embd) {168 inp_per_layer = build_inp_per_layer();169 ggml_build_forward_expand(gf, inp_per_layer);170 171 // inp_per_layer shape: [n_embd_per_layer, n_tokens, n_layer]172 inp_per_layer = project_per_layer_inputs(inpL, inp_per_layer);173 }174 175 for (int il = 0; il < n_layer; ++il) {176 const int64_t n_embd_head = hparams.n_embd_head_k(il);177 GGML_ASSERT(n_embd_head == hparams.n_embd_head_v(il));178 179 const int64_t n_head = hparams.n_head(il);180 const int64_t n_head_kv = hparams.n_head_kv(il);181 182 const float freq_base_l = model.get_rope_freq_base(cparams, il);183 const float freq_scale_l = model.get_rope_freq_scale(cparams, il);184 const int n_rot_l = hparams.n_rot(il);185 186 res->t_layer_inp[il] = inpL;187 188 // norm189 cur = build_norm(inpL, model.layers[il].attn_norm, nullptr, LLM_NORM_RMS, il);190 cb(cur, "attn_norm", il);191 192 ggml_tensor * freq_factors = nullptr;193 if (!hparams.is_swa(il)) {194 // full_attention layers use rope_freqs for proportional rope195 freq_factors = model.layers[il].rope_freqs;196 }197 198 // Q projection (shared for both non-KV and KV layers)199 // this is to mirror Gemma4Attention in pytorch code200 ggml_tensor * Qcur;201 {202 Qcur = build_lora_mm(model.layers[il].wq, cur, model.layers[il].wq_s);203 cb(Qcur, "Qcur", il);204 205 Qcur = ggml_reshape_3d(ctx0, Qcur, n_embd_head, n_head, n_tokens);206 207 Qcur = build_norm(Qcur, model.layers[il].attn_q_norm, nullptr, LLM_NORM_RMS, il);208 cb(Qcur, "Qcur_normed", il);209 210 Qcur = ggml_rope_ext(ctx0, Qcur, inp_pos, freq_factors, n_rot_l, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,211 ext_factor, attn_factor, beta_fast, beta_slow);212 cb(Qcur, "Qcur_pos", il);213 }214 215 // self-attention216 if (hparams.has_kv(il)) {217 ggml_tensor * Kcur = build_lora_mm(model.layers[il].wk, cur, model.layers[il].wk_s);218 cb(Kcur, "Kcur", il);219 220 ggml_tensor * Vcur = model.layers[il].wv221 ? build_lora_mm(model.layers[il].wv, cur, model.layers[il].wv_s)222 : Kcur; // if v_proj is not present, use Kcur as Vcur223 cb(Vcur, "Vcur", il);224 225 Kcur = ggml_reshape_3d(ctx0, Kcur, n_embd_head, n_head_kv, n_tokens);226 Vcur = ggml_reshape_3d(ctx0, Vcur, n_embd_head, n_head_kv, n_tokens);227 228 Kcur = build_norm(Kcur, model.layers[il].attn_k_norm, nullptr, LLM_NORM_RMS, il);229 Vcur = ggml_rms_norm(ctx0, Vcur, hparams.f_norm_rms_eps);230 231 cb(Kcur, "Kcur_normed", il);232 cb(Vcur, "Vcur_normed", il);233 234 Kcur = ggml_rope_ext(ctx0, Kcur, inp_pos, freq_factors, n_rot_l, rope_type, n_ctx_orig, freq_base_l, freq_scale_l,235 ext_factor, attn_factor, beta_fast, beta_slow);236 237 cb(Kcur, "Kcur_pos", il);238 239 cur = build_attn(inp_attn, model.layers[il].wo,240 nullptr, model.layers[il].wo_s, Qcur, Kcur, Vcur, nullptr, nullptr, nullptr,241 hparams.f_attention_scale, il);242 } else {243 // reuse KV cache of earlier layers244 cur = build_attn(inp_attn,245 model.layers[il].wo, nullptr, model.layers[il].wo_s,246 Qcur, nullptr, nullptr, nullptr, nullptr, nullptr, hparams.f_attention_scale, il);247 }248 249 // TODO @ngxson : strip unused token right after the last KV layer to speed up prompt processing250 // keep all rows when extracting unmasked nextn embeddings (MTP target needs the hidden state for every token)251 if (il == n_layer - 1 && inp_out_ids && cparams.embeddings_nextn_masked) {252 cur = ggml_get_rows(ctx0, cur, inp_out_ids);253 inpL = ggml_get_rows(ctx0, inpL, inp_out_ids);254 }255 cur = build_norm(cur,256 model.layers[il].attn_post_norm, nullptr,257 LLM_NORM_RMS, il);258 cb(cur, "attn_post_norm", il);259 260 ggml_tensor * attn_out = ggml_add(ctx0, cur, inpL);261 cb(attn_out, "attn_out", il);262 263 // feed-forward network264 const bool is_moe_layer = model.layers[il].ffn_gate_inp != nullptr;265 if (is_moe_layer) {266 // MLP (shared exp)267 ggml_tensor * cur_mlp = build_norm(attn_out,268 model.layers[il].ffn_norm, nullptr,269 LLM_NORM_RMS, il);270 cb(cur_mlp, "ffn_norm_1", il);271 272 cur_mlp = build_ffn(cur_mlp,273 model.layers[il].ffn_up, nullptr, model.layers[il].ffn_up_s,274 model.layers[il].ffn_gate, nullptr, model.layers[il].ffn_gate_s,275 model.layers[il].ffn_down, nullptr, model.layers[il].ffn_down_s,276 nullptr,277 LLM_FFN_GELU, LLM_FFN_PAR, il);278 cur_mlp = build_norm(cur_mlp,279 model.layers[il].ffn_post_norm_1, nullptr,280 LLM_NORM_RMS, il);281 cb(cur_mlp, "ffn_mlp", il);282 283 // Expert FFN284 ggml_tensor * cur_moe = build_norm(attn_out,285 model.layers[il].ffn_pre_norm_2, nullptr,286 LLM_NORM_RMS, il);287 cb(cur_moe, "ffn_norm_2", il);288 289 // custom MoE logits calculation (router operates on attn_out, not cur)290 ggml_tensor * tmp = ggml_rms_norm(ctx0, attn_out, hparams.f_norm_rms_eps);291 tmp = ggml_scale(ctx0, tmp, 1.0f / sqrtf((float) n_embd));292 tmp = ggml_mul(ctx0, tmp, model.layers[il].ffn_gate_inp_s);293 ggml_tensor * logits = build_lora_mm(model.layers[il].ffn_gate_inp, tmp); // [n_expert, n_tokens]294 cb(logits, "ffn_moe_logits", il);295 296 cur_moe = build_moe_ffn(cur_moe,297 nullptr, // gate_inp298 model.layers[il].ffn_up_exps,299 model.layers[il].ffn_gate_exps,300 model.layers[il].ffn_down_exps,301 nullptr, // exp_probs_b (not used for gemma4)302 n_expert, n_expert_used,303 LLM_FFN_GELU, true,304 1.0f,305 LLAMA_EXPERT_GATING_FUNC_TYPE_SOFTMAX,306 il, logits,307 model.layers[il].ffn_gate_up_exps,308 model.layers[il].ffn_up_exps_s,309 model.layers[il].ffn_gate_exps_s,310 model.layers[il].ffn_down_exps_s);311 cur_moe = build_norm(cur_moe,312 model.layers[il].ffn_post_norm_2, nullptr,313 LLM_NORM_RMS, il);314 cb(cur_moe, "ffn_moe", il);315 316 cur = ggml_add(ctx0, cur_mlp, cur_moe);317 cb(cur, "ffn_moe_combined", il);318 } else {319 cur = build_norm(attn_out,320 model.layers[il].ffn_norm, nullptr,321 LLM_NORM_RMS, il);322 cb(cur, "ffn_norm", il);323 324 cur = build_ffn(cur,325 model.layers[il].ffn_up, nullptr, model.layers[il].ffn_up_s,326 model.layers[il].ffn_gate, nullptr, model.layers[il].ffn_gate_s,327 model.layers[il].ffn_down, nullptr, model.layers[il].ffn_down_s,328 nullptr,329 LLM_FFN_GELU, LLM_FFN_PAR, il);330 cb(cur, "ffn_out", il);331 }332 cur = build_norm(cur,333 model.layers[il].ffn_post_norm, nullptr,334 LLM_NORM_RMS, -1);335 cb(cur, "ffn_post_norm", il);336 337 // residual connection338 cur = ggml_add(ctx0, cur, attn_out);339 340 // per-layer embedding341 if (inp_per_layer) {342 ggml_tensor * pe_in = cur;343 cb(cur, "pe_in", il);344 345 cur = build_lora_mm(model.layers[il].per_layer_inp_gate, cur); // [n_embd_per_layer, n_tokens]346 cur = ggml_gelu(ctx0, cur);347 348 ggml_tensor * inp_this_layer = ggml_view_2d_slice(ctx0, inp_per_layer, il); // [n_embd_per_layer, n_tokens]349 350 // TODO @ngxson : improve this351 if (il == n_layer - 1 && inp_out_ids && cparams.embeddings_nextn_masked) {352 inp_this_layer = ggml_get_rows(ctx0, inp_this_layer, inp_out_ids);353 }354 355 cur = ggml_mul(ctx0, cur, inp_this_layer);356 cur = build_lora_mm(model.layers[il].per_layer_proj, cur); // [n_embd, n_tokens]357 cur = build_norm(cur, model.layers[il].per_layer_post_norm, nullptr, LLM_NORM_RMS, il);358 cb(cur, "per_layer_embd_out", il);359 360 // residual connection361 cur = ggml_add(ctx0, pe_in, cur);362 }363 364 // layer_scalar365 if (model.layers[il].out_scale) {366 cur = ggml_mul(ctx0, cur, model.layers[il].out_scale);367 cb(cur, "out_scaled", il);368 }369 370 cur = build_cvec(cur, il);371 cb(cur, "l_out", il);372 373 // input for next layer374 inpL = cur;375 }376 cur = inpL;377 378 cur = build_norm(cur,379 model.output_norm, nullptr,380 LLM_NORM_RMS, -1);381 382 // Expose the post-output-norm hidden state (the LM-head input feature) so that383 // MTP draft contexts can read it via llama_get_embeddings_nextn_ith() as the384 // recurrent h input. This matches the reference (transformers/vLLM/SGLang),385 // which feeds the drafter the target's post-final-norm hidden state.386 cb(cur, "h_nextn", -1);387 res->t_h_nextn = cur;388 389 if (!cparams.embeddings_nextn_masked && inp_out_ids) {390 cur = ggml_get_rows(ctx0, cur, inp_out_ids);391 }392 393 cb(cur, "result_norm", -1);394 res->t_embd = cur;395 396 // lm_head397 cur = build_lora_mm(model.output, cur, model.output_s);398 399 if (hparams.f_final_logit_softcapping) {400 cur = ggml_scale(ctx0, cur, 1.0f / hparams.f_final_logit_softcapping);401 cur = ggml_tanh(ctx0, cur);402 cur = ggml_scale(ctx0, cur, hparams.f_final_logit_softcapping);403 }404 405 cb(cur, "result_output", -1);406 res->t_logits = cur;407 408 ggml_build_forward_expand(gf, cur);409}410 411// equivalent to get_per_layer_inputs() in python code412// output shape: [n_embd_per_layer, n_layer, n_tokens]413ggml_tensor * llama_model_gemma4::graph::build_inp_per_layer() {414 auto inp = std::make_unique<llm_graph_input_embd>(n_embd);415 416 ggml_tensor * inp_per_layer;417 float tok_embd_scale = sqrtf((float) n_embd_per_layer);418 if (ubatch.token) {419 inp->tokens = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, ubatch.n_tokens);420 ggml_set_input(inp->tokens);421 res->t_inp_tokens = inp->tokens;422 423 inp_per_layer = ggml_get_rows (ctx0, model.per_layer_tok_embd, inp->tokens);424 inp_per_layer = ggml_reshape_3d(ctx0, inp_per_layer, n_embd_per_layer, n_layer, n_tokens);425 inp_per_layer = ggml_scale (ctx0, inp_per_layer, tok_embd_scale);426 cb(inp_per_layer, "inp_per_layer_selected", -1);427 428 res->add_input(std::move(inp));429 } else {430 // Multimodal embedding path: use padding token (ID=0) embedding431 // TODO: verify if this is the correct behavior in transformers implementation432 const int64_t embd_size = model.per_layer_tok_embd->ne[0]; // n_embd_per_layer * n_layer433 434 // Extract and dequantize padding token embedding (row 0)435 ggml_tensor * padding = ggml_view_1d(ctx0, model.per_layer_tok_embd, embd_size, 0);436 inp_per_layer = ggml_cast (ctx0, padding, GGML_TYPE_F32);437 inp_per_layer = ggml_scale(ctx0, inp_per_layer, tok_embd_scale);438 439 // Reshape to [n_embd_per_layer, n_layer, 1]440 inp_per_layer = ggml_reshape_3d(ctx0, inp_per_layer, n_embd_per_layer, n_layer, 1);441 cb(inp_per_layer, "inp_per_layer_multimodal", -1);442 }443 return inp_per_layer;444}445 446// equivalent to project_per_layer_inputs() in python code447// this calculates the per-layer inputs, so the final tensor shape will have n_layer as the last dim448// inp_batch shape: [n_embd, n_tokens]449// inp_per_layer shape: [n_embd_per_layer, n_layer, n_tokens] (from build_inp_per_layer)450// output shape: [n_embd_per_layer, n_tokens, n_layer]451ggml_tensor * llama_model_gemma4::graph::project_per_layer_inputs(ggml_tensor * inp_batch, ggml_tensor * inp_per_layer) {452 const float per_layer_projection_scale = 1.0f / sqrtf((float) n_embd);453 const float per_layer_input_scale = 1.0f / sqrtf(2.0f);454 455 // note: this matrix multiplication will be performed in the input layer (i.e. on the CPU)456 ggml_tensor * per_layer_proj;457 per_layer_proj = ggml_mul_mat (ctx0, model.per_layer_model_proj, inp_batch);458 per_layer_proj = ggml_scale (ctx0, per_layer_proj, per_layer_projection_scale);459 per_layer_proj = ggml_reshape_3d(ctx0, per_layer_proj, n_embd_per_layer, n_layer, n_tokens);460 461 per_layer_proj = build_norm(per_layer_proj, model.per_layer_proj_norm, nullptr, LLM_NORM_RMS, -1);462 cb(per_layer_proj, "per_layer_proj", -1);463 464 inp_per_layer = ggml_add (ctx0, per_layer_proj, inp_per_layer);465 inp_per_layer = ggml_scale(ctx0, inp_per_layer, per_layer_input_scale);466 cb(inp_per_layer, "inp_per_layer", -1);467 468 // permute to shape: [n_embd_per_layer, n_tokens, n_layer]469 inp_per_layer = ggml_cont(ctx0, ggml_permute(ctx0, inp_per_layer, 0, 2, 1, 3));470 return inp_per_layer;471}472 