I’m reading the source code of alpaca.cpp
in an attempt to understand how a large language model works. (I have a strong programming background, but almost no math, so it’s easier for me to start with code and then go backwards to the papers once I have some idea what’s going on.)
Partway down llama_eval
, it makes a call to ggml_mul_mat()
which caught my attention:
// K * Q
struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
At first I thought this was an ordinary matrix multiplication; the “Attention is all you need” paper certainly uses that for K and Q. But in this case K
and Q
appear to be 3d tensors, and my understanding is that matrix multiplication only works on 2d matrices.
So I dug into the ggml
code; ggml_mul_mat
itself is just a wrapper function, but the first thing I noticed is that it supports up to 4 dimensions, with an interleaved result:
static inline bool ggml_can_mul_mat(const struct ggml_tensor * t0, const struct ggml_tensor * t1) {
return (t0->ne[0] == t1->ne[0]) &&
(t0->ne[2] == t1->ne[2]) &&
(t0->ne[3] == t1->ne[3]);
}
const int ne[4] = { a->ne[1], b->ne[1], a->ne[2], b->ne[3] };
struct ggml_tensor * result = ggml_new_tensor(ctx, GGML_TYPE_F32, MIN(a->n_dims, b->n_dims), ne);
...which, if I'm reading this right, means that it will take an A×M×C×D tensor, and an A×N×C×D tensor, and return an M×N×C×D tensor, truncating as needed, which definitely doesn’t sound like matrix multiplication already.
The actual implementation (in ggml_compute_forward_mul_mat_*()
) has a lot of special cases, and even the simplest case I could find I’m having trouble reading without already understanding what it’s doing. But the best impression I’ve got is that it’s doing some sort of sideways matrix multiplication, piecewise along the other two dimensions.
Does this operation have a name? Is it some kind of standard operation in CNNs, or is it something that GGML and/or LLaMA have made up? Where can I read more about what’s going on here?