· By Jody in GPT Internals —

Dot product

In my mission to dissect Andrej Karpathy's microgpt I am starting with some low-hanging fruit in the form of the dot product function.

This function is both simple and used in multiple places.

A dot product takes two vectors of equal length, multiplies each corresponding component and then adds them up. Here is an example that calculates the dot product of [1, 2] and [3, 4].

dotProduct([1, 2], [3, 4]) = (1 x 3) + (2 x 4) = 3 + 8 = 11

Here is the dot product function implemented in JavaScript:

function dotProduct(vector1, vector2){
  if(vector1.length != vector2.length) throw new Error("Vectors must be of equal length");
  let out = 0;
  for(let i = 0; i < vector1.length; i++){
    out += vector1[i] * vector2[i];
  }
  return out;
}

Note: I have added a guard to make sure the vectors are of the same length.