MCPcopy Create free account
hub / github.com/antirez/ds4 / metal_graph_encode_decode_layer

Function metal_graph_encode_decode_layer

ds4.c:14842–16068  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

14840}
14841
14842/* Final language-model head: HC collapse, RMSNorm, and Q8_0 vocab projection. */
14843static void output_logits_one(
14844 float * logits,
14845 const ds4_model * model,
14846 const ds4_weights * weights,
14847 const float * inp_hc) {
14848 float *embd = xmalloc((size_t)DS4_N_EMBD * sizeof(embd[0]));
14849 float *norm = xmalloc((size_t)DS4_N_EMBD * sizeof(norm[0]));
14850
14851 output_hc_head_one(embd, model, weights, inp_hc);
14852 rms_norm_weight(norm, embd, tensor_data(model, weights->output_norm), DS4_N_EMBD, DS4_RMS_EPS);
14853
14854 matvec_q8_0(logits, model, weights->output, norm);
14855
14856 free(norm);
14857 free(embd);
14858}
14859
14860static void layer_glm_first_token_attention_one(
14861 float * out,
14862 const ds4_model * model,
14863 const ds4_layer_weights * layer,
14864 const float * x) {
14865 float *norm = xmalloc((size_t)DS4_N_EMBD * sizeof(norm[0]));
14866 float *kv_raw = xmalloc((size_t)layer->attn_kv_a_mqa->dim[1] * sizeof(kv_raw[0]));
14867 float *kv_norm = xmalloc((size_t)DS4_N_KV_LORA * sizeof(kv_norm[0]));
14868 float *heads = xmalloc((size_t)DS4_N_HEAD * DS4_N_VALUE_MLA * sizeof(heads[0]));
14869 const uint64_t kv_blocks = (DS4_N_KV_LORA + 31) / 32;
14870 int8_t *kvq = xmalloc((size_t)kv_blocks * 32);
14871 float *kvscale = xmalloc((size_t)kv_blocks * sizeof(kvscale[0]));
14872
14873 if (layer->attn_kv_a_mqa->dim[1] < DS4_N_KV_LORA ||
14874 layer->attn_v_b->dim[0] != DS4_N_KV_LORA ||
14875 layer->attn_v_b->dim[1] != DS4_N_VALUE_MLA ||
14876 layer->attn_v_b->dim[2] != DS4_N_HEAD ||
14877 layer->attn_output->dim[0] != (uint64_t)DS4_N_HEAD * DS4_N_VALUE_MLA ||
14878 layer->attn_output->dim[1] != DS4_N_EMBD) {
14879 ds4_die("GLM attention tensors have an unexpected layout");
14880 }
14881
14882 rms_norm_weight(norm, x, tensor_data(model, layer->attn_norm), DS4_N_EMBD, DS4_RMS_EPS);
14883 matvec_q8_0(kv_raw, model, layer->attn_kv_a_mqa, norm);
14884 rms_norm_weight(kv_norm, kv_raw, tensor_data(model, layer->attn_kv_a_norm),
14885 DS4_N_KV_LORA, DS4_RMS_EPS);
14886 quantize_q8_0_activation(kv_norm, kvq, kvscale, DS4_N_KV_LORA);
14887
14888 for (uint32_t h = 0; h < DS4_N_HEAD; h++) {
14889 matvec_q8_0_3d_slice_prequant(heads + (uint64_t)h * DS4_N_VALUE_MLA,
14890 model,
14891 layer->attn_v_b,
14892 kvq,
14893 kvscale,
14894 h);
14895 }
14896 matvec_q8_0(out, model, layer->attn_output, heads);
14897
14898 free(kvscale);
14899 free(kvq);

Tested by

no test coverage detected