{"course":{"slug":"maths-you-need","title":"The Maths You Actually Need","url":"https://addaly.com/learn/maths-you-need","level":"intermediate","track":"deep"},"lesson":{"slug":"matrix-multiplication-by-hand","title":"Doing a matrix multiplication yourself, once","url":"https://addaly.com/learn/maths-you-need/matrix-multiplication-by-hand","position":10,"of":76,"minutes":8,"answer":"Every entry of a matrix product is one dot product between a row of the left matrix and a column of the right.","keyIdea":"Every entry of a matrix product is one dot product between a row of the left matrix and a column of the right, which is why the inner dimensions must match and why order cannot be swapped."},"body":{"format":"markdown","text":"## Do it once and you never fear it again\n\nMatrix multiplication looks like a rule to memorise. It is one sentence: **entry (i, j) of the answer is the dot product of row i of the left matrix with column j of the right matrix.** Everything else follows from that, including the shape rule and the fact that order matters.\n\nHere is a full worked example. Take\n\n```\nA = [ 1  2  3 ]        B = [ 7   8 ]\n    [ 4  5  6 ]            [ 9  10 ]\n                           [ 11 12 ]\n```\n\nA is 2×3, B is 3×2. Work out each of the four answer entries.\n\n```\n(1,1): row 1 of A . column 1 of B = 1*7 + 2*9 + 3*11 = 7 + 18 + 33  = 58\n(1,2): row 1 of A . column 2 of B = 1*8 + 2*10 + 3*12 = 8 + 20 + 36 = 64\n(2,1): row 2 of A . column 1 of B = 4*7 + 5*9 + 6*11 = 28 + 45 + 66 = 139\n(2,2): row 2 of A . column 2 of B = 4*8 + 5*10 + 6*12 = 32 + 50 + 72 = 154\n```\n\nSo\n\n```\nAB = [ 58   64 ]\n     [ 139 154 ]\n```\n\nDo that once, slowly, with a pen. It takes four minutes and it converts a rule into a thing you understand.\n\n> Figure: Every entry of AB is one dot product. A two by two grid, rows Row 1 of A: 1 2 3 and Row 2 of A: 4 5 6, columns Col 1 of B: 7 9 11 and Col 2 of B: 8 10 12: Row 1 of A: 1 2 3 and Col 1 of B: 7 9 11: 58; Row 1 of A: 1 2 3 and Col 2 of B: 8 10 12: 64; Row 2 of A: 4 5 6 and Col 1 of B: 7 9 11: 139; Row 2 of A: 4 5 6 and Col 2 of B: 8 10 12: 154. Four entries, four dot products of length three. The inner dimension has to be 3 on both sides because a dot product needs two lists of equal length, and that is the whole explanation for the shape error you will meet most often in your first month.\n\n## The shape rule, and why it is what it is\n\nAn (m × n) matrix times an (n × p) matrix gives an (m × p) matrix. Write the shapes next to each other:\n\n```\n(2 x 3) (3 x 2)  ->  (2 x 2)\n     ^---^  the inner numbers must match; they vanish\n   ^---------^     the outer numbers survive\n```\n\nThe inner numbers must match because each answer entry is a dot product, and a dot product needs two lists of equal length. Row i of A has n entries; column j of B has n entries. If they differ, there is nothing to compute. That is the whole explanation for the error message you will see most often in your first month.\n\n## Order matters, and it is not a technicality\n\n`AB` and `BA` are different operations, and frequently only one of them is even legal. With the A and B above, `BA` is (3×2)(2×3) = 3×3: a different size of answer entirely. Even when both are square and both legal, the results usually differ:\n\n```\n[1 1] [1 0]   =  [1 0]        [1 0] [1 1]   =  [1 1]\n[0 1] [1 1]      [1 1]        [1 1] [0 1]      [1 2]\n```\n\nTwo legal products, two different answers. This matters in practice because it is why a stack of layers is a sequence, not a set: `W3 W2 W1 x` applies W1 first. Swapping two layers changes the function.\n\n## Reading it as columns instead of dots\n\nThere is a second reading, and it is the one that makes deep learning make sense. Instead of \"dot products\", think of a matrix times a vector as **a weighted sum of the matrix's columns**:\n\n```\n[ 1  2 ] [ 3 ]  =  3 * [1]  +  4 * [2]  =  [ 3 + 8  ]  =  [ 11 ]\n[ 4  5 ] [ 4 ]         [4]         [5]     [ 12 + 20]     [ 32 ]\n```\n\nEvery output of a linear layer is a mixture of the columns of the weight matrix, with the input supplying the mixing amounts. The set of everything reachable this way is called the column space, and it is exactly what the layer can produce. Anything outside it is unreachable at any input, which is a limitation you will meet again under the word *rank*.\n\n## Cost, in operations you can count\n\nMultiplying an (m × n) by an (n × p) matrix requires `m * n * p` multiply-add operations, because there are `m * p` output entries and each costs `n` multiply-adds. Put numbers in it: a single 4096 × 4096 weight matrix applied to one 4096-vector costs\n\n```\n4096 * 4096 * 1 = 16.7 million multiply-adds\n```\n\nwhich is why people count a matrix multiplication as roughly `2 * m * n * p` floating-point operations: one multiply and one add each. A transformer layer does several of these per token, and a model has dozens of layers. That arithmetic, and nothing more mysterious, is where the electricity goes.\n\n## The two habits worth forming\n\n**Write the shapes.** Before writing any model code, write the shape of every tensor as a comment: `(batch, seq, d_model)`. Most bugs in a first model are shape bugs, and most shape bugs are visible in the comments before the code runs.\n\n**Verify small.** When you are unsure what an operation does, run it on a 2×3 and a 3×2 you can check by hand. In free NumPy:\n\n```python\nimport numpy as np\nA = np.array([[1, 2, 3], [4, 5, 6]])\nB = np.array([[7, 8], [9, 10], [11, 12]])\nprint(A @ B)          # the 58 / 64 / 139 / 154 above\nprint((A @ B).shape)  # (2, 2)\n```\n\nThree lines, no GPU, no account. Any claim in this module can be checked the same way, and checking it yourself is the difference between knowing the rule and believing it."},"check":{"question":"A model has a weight matrix of shape (768, 3072) and an input batch of shape (32, 128, 768) meaning batch, sequence position, features. What is the output shape, and which dimension does the matrix consume?","options":[{"text":"(32, 128, 3072); the matrix consumes the 768 feature dimension, since that is the inner dimension that must match.","correct":true},{"text":"(32, 768, 3072); the matrix consumes the 128 sequence dimension, since matrix multiplication acts on the second-to-last axis.","correct":false,"tempting":"Picks the wrong axis: the rule is that the last axis of the input must match the first axis of the weight, not the second-to-last."},{"text":"(32, 128, 768); the matrix maps features to features and preserves the shape.","correct":false,"tempting":"Only true for a square matrix; this one is 768 in and 3072 out, so the width changes."},{"text":"(3072, 128, 32); the output is the transpose of the input with the new feature count first.","correct":false,"tempting":"Nothing here transposes the batch and sequence axes; they pass through untouched."}]},"prev":{"slug":"sparse-dense-and-one-hot","title":"Sparse and dense, and the memory each costs","url":"https://addaly.com/learn/maths-you-need/sparse-dense-and-one-hot"},"next":{"slug":"matrices-as-transformations","title":"A matrix is a stack of questions","url":"https://addaly.com/learn/maths-you-need/matrices-as-transformations"},"authorship":"Founder and series editor: Dr Mustafa Mun. Written by AI models to a written standard. Source and assessment review continues. Academic review invited.","review":{"status":"Draft, open for academic review"},"cite":"Addaly (2026) 'Doing a matrix multiplication yourself, once', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/matrix-multiplication-by-hand (Accessed: 29 November 2026).","licence":{"name":"CC BY-NC-SA 4.0","url":"https://creativecommons.org/licenses/by-nc-sa/4.0/"},"reader":{"schema":1,"title":"Doing a matrix multiplication yourself, once","courseTitle":"The Maths You Actually Need","module":{"index":2,"slug":"matrices-and-layers","title":"Matrices, and what a layer really does"},"answer":null,"keyIdea":"Every entry of a matrix product is one dot product between a row of the left matrix and a column of the right, which is why the inner dimensions must match and why order cannot be swapped.","hero":{"kind":"figure","figure":{"t":"figure","label":"Figure 2.1","figure":{"caption":"Four entries, four dot products of length three. The inner dimension has to be 3 on both sides because a dot product needs two lists of equal length, and that is the whole explanation for the shape error you will meet most often in your first month.","cellLabels":[["7 + 18 + 33","8 + 20 + 36"],["28 + 45 + 66","32 + 50 + 72"]],"cells":[["58","64"],["139","154"]],"cols":["Col 1 of B: 7 9 11","Col 2 of B: 8 10 12"],"rows":["Row 1 of A: 1 2 3","Row 2 of A: 4 5 6"],"title":"Every entry of AB is one dot product","type":"matrix"},"alt":"Figure: Every entry of AB is one dot product. A two by two grid, rows Row 1 of A: 1 2 3 and Row 2 of A: 4 5 6, columns Col 1 of B: 7 9 11 and Col 2 of B: 8 10 12: Row 1 of A: 1 2 3 and Col 1 of B: 7 9 11: 58; Row 1 of A: 1 2 3 and Col 2 of B: 8 10 12: 64; Row 2 of A: 4 5 6 and Col 1 of B: 7 9 11: 139; Row 2 of A: 4 5 6 and Col 2 of B: 8 10 12: 154. Four entries, four dot products of length three. The inner dimension has to be 3 on both sides because a dot product needs two lists of equal length, and that is the whole explanation for the shape error you will meet most often in your first month."}},"blocks":[{"t":"h2","id":"do-it-once-and-you-never-fear-it-again","runs":[{"text":"Do it once and you never fear it again"}]},{"t":"p","runs":[{"text":"Matrix multiplication looks like a rule to memorise. It is one sentence: "},{"text":"entry (i, j) of the answer is the dot product of row i of the left matrix with column j of the right matrix.","b":true},{"text":" Everything else follows from that, including the shape rule and the fact that order matters."}]},{"t":"p","runs":[{"text":"Here is a full worked example. Take"}]},{"t":"code","lang":"","label":"Text","text":"A = [ 1  2  3 ]        B = [ 7   8 ]\n    [ 4  5  6 ]            [ 9  10 ]\n                           [ 11 12 ]"},{"t":"p","runs":[{"text":"A is 2×3, B is 3×2. Work out each of the four answer entries."}]},{"t":"code","lang":"","label":"Text","text":"(1,1): row 1 of A . column 1 of B = 1*7 + 2*9 + 3*11 = 7 + 18 + 33  = 58\n(1,2): row 1 of A . column 2 of B = 1*8 + 2*10 + 3*12 = 8 + 20 + 36 = 64\n(2,1): row 2 of A . column 1 of B = 4*7 + 5*9 + 6*11 = 28 + 45 + 66 = 139\n(2,2): row 2 of A . column 2 of B = 4*8 + 5*10 + 6*12 = 32 + 50 + 72 = 154"},{"t":"p","runs":[{"text":"So"}]},{"t":"code","lang":"","label":"Text","text":"AB = [ 58   64 ]\n     [ 139 154 ]"},{"t":"p","runs":[{"text":"Do that once, slowly, with a pen. It takes four minutes and it converts a rule into a thing you understand."}]},{"t":"h2","id":"the-shape-rule-and-why-it-is-what-it-is","runs":[{"text":"The shape rule, and why it is what it is"}]},{"t":"p","runs":[{"text":"An (m × n) matrix times an (n × p) matrix gives an (m × p) matrix. Write the shapes next to each other:"}]},{"t":"code","lang":"","label":"Text","text":"(2 x 3) (3 x 2)  ->  (2 x 2)\n     ^---^  the inner numbers must match; they vanish\n   ^---------^     the outer numbers survive"},{"t":"p","runs":[{"text":"The inner numbers must match because each answer entry is a dot product, and a dot product needs two lists of equal length. Row i of A has n entries; column j of B has n entries. If they differ, there is nothing to compute. That is the whole explanation for the error message you will see most often in your first month."}]},{"t":"h2","id":"order-matters-and-it-is-not-a-technicality","runs":[{"text":"Order matters, and it is not a technicality"}]},{"t":"p","runs":[{"text":"AB","code":true},{"text":" and "},{"text":"BA","code":true},{"text":" are different operations, and frequently only one of them is even legal. With the A and B above, "},{"text":"BA","code":true},{"text":" is (3×2)(2×3) = 3×3: a different size of answer entirely. Even when both are square and both legal, the results usually differ:"}]},{"t":"code","lang":"","label":"Text","text":"[1 1] [1 0]   =  [1 0]        [1 0] [1 1]   =  [1 1]\n[0 1] [1 1]      [1 1]        [1 1] [0 1]      [1 2]"},{"t":"p","runs":[{"text":"Two legal products, two different answers. This matters in practice because it is why a stack of layers is a sequence, not a set: "},{"text":"W3 W2 W1 x","code":true},{"text":" applies W1 first. Swapping two layers changes the function."}]},{"t":"h2","id":"reading-it-as-columns-instead-of-dots","runs":[{"text":"Reading it as columns instead of dots"}]},{"t":"p","runs":[{"text":"There is a second reading, and it is the one that makes deep learning make sense. Instead of “dot products”, think of a matrix times a vector as "},{"text":"a weighted sum of the matrix’s columns","b":true},{"text":":"}]},{"t":"code","lang":"","label":"Text","text":"[ 1  2 ] [ 3 ]  =  3 * [1]  +  4 * [2]  =  [ 3 + 8  ]  =  [ 11 ]\n[ 4  5 ] [ 4 ]         [4]         [5]     [ 12 + 20]     [ 32 ]"},{"t":"p","runs":[{"text":"Every output of a linear layer is a mixture of the columns of the weight matrix, with the input supplying the mixing amounts. The set of everything reachable this way is called the column space, and it is exactly what the layer can produce. Anything outside it is unreachable at any input, which is a limitation you will meet again under the word "},{"text":"rank","i":true},{"text":"."}]},{"t":"h2","id":"cost-in-operations-you-can-count","runs":[{"text":"Cost, in operations you can count"}]},{"t":"p","runs":[{"text":"Multiplying an (m × n) by an (n × p) matrix requires "},{"text":"m * n * p","code":true},{"text":" multiply-add operations, because there are "},{"text":"m * p","code":true},{"text":" output entries and each costs "},{"text":"n","code":true},{"text":" multiply-adds. Put numbers in it: a single 4096 × 4096 weight matrix applied to one 4096-vector costs"}]},{"t":"code","lang":"","label":"Text","text":"4096 * 4096 * 1 = 16.7 million multiply-adds"},{"t":"p","runs":[{"text":"which is why people count a matrix multiplication as roughly "},{"text":"2 * m * n * p","code":true},{"text":" floating-point operations: one multiply and one add each. A transformer layer does several of these per token, and a model has dozens of layers. That arithmetic, and nothing more mysterious, is where the electricity goes."}]},{"t":"h2","id":"the-two-habits-worth-forming","runs":[{"text":"The two habits worth forming"}]},{"t":"p","runs":[{"text":"Write the shapes.","b":true},{"text":" Before writing any model code, write the shape of every tensor as a comment: "},{"text":"(batch, seq, d_model)","code":true},{"text":". Most bugs in a first model are shape bugs, and most shape bugs are visible in the comments before the code runs."}]},{"t":"p","runs":[{"text":"Verify small.","b":true},{"text":" When you are unsure what an operation does, run it on a 2×3 and a 3×2 you can check by hand. In free NumPy:"}]},{"t":"code","lang":"python","label":"Python","text":"import numpy as np\nA = np.array([[1, 2, 3], [4, 5, 6]])\nB = np.array([[7, 8], [9, 10], [11, 12]])\nprint(A @ B)          # the 58 / 64 / 139 / 154 above\nprint((A @ B).shape)  # (2, 2)"},{"t":"p","runs":[{"text":"Three lines, no GPU, no account. Any claim in this module can be checked the same way, and checking it yourself is the difference between knowing the rule and believing it."}]}],"check":{"question":[{"text":"A model has a weight matrix of shape (768, 3072) and an input batch of shape (32, 128, 768) meaning batch, sequence position, features. What is the output shape, and which dimension does the matrix consume?"}],"options":[{"text":[{"text":"(32, 128, 3072); the matrix consumes the 768 feature dimension, since that is the inner dimension that must match."}],"correct":true,"tempting":null},{"text":[{"text":"(32, 768, 3072); the matrix consumes the 128 sequence dimension, since matrix multiplication acts on the second-to-last axis."}],"correct":false,"tempting":[{"text":"Picks the wrong axis: the rule is that the last axis of the input must match the first axis of the weight, not the second-to-last."}]},{"text":[{"text":"(32, 128, 768); the matrix maps features to features and preserves the shape."}],"correct":false,"tempting":[{"text":"Only true for a square matrix; this one is 768 in and 3072 out, so the width changes."}]},{"text":[{"text":"(3072, 128, 32); the output is the transpose of the input with the new feature count first."}],"correct":false,"tempting":[{"text":"Nothing here transposes the batch and sequence axes; they pass through untouched."}]}],"order":[1,2,3,0],"why":null},"prev":{"slug":"sparse-dense-and-one-hot","title":"Sparse and dense, and the memory each costs","minutes":9},"next":{"slug":"matrices-as-transformations","title":"A matrix is a stack of questions","minutes":8}}}