{"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":"shapes-broadcasting-and-batches","title":"Shapes, batches, and the broadcasting rules","url":"https://addaly.com/learn/maths-you-need/shapes-broadcasting-and-batches","position":12,"of":76,"minutes":9,"answer":"Broadcasting silently stretches a dimension of size one to match its neighbour, which makes concise code possible and makes a whole family of bugs run without complaint.","keyIdea":"Broadcasting silently stretches a dimension of size one to match its neighbour, which makes concise code possible and makes a whole family of bugs run without complaint."},"body":{"format":"markdown","text":"## The batch dimension is a convenience, not a concept\n\nReal code never multiplies one vector at a time. It stacks 32 or 256 examples into a batch and processes them together, because a GPU is a machine for doing the same arithmetic to many things at once. So every tensor grows a leading dimension, and the shapes you read look like `(32, 128, 768)`: 32 examples, 128 token positions each, 768 features each.\n\nThe rule that keeps this simple is that matrix multiplication in NumPy and PyTorch acts on the **last two dimensions** and treats everything in front as batch. So `(32, 128, 768) @ (768, 3072)` gives `(32, 128, 3072)`: the same 768 × 3072 weight matrix applied to each of the 32 × 128 = 4,096 individual vectors, with no loop written anywhere.\n\n## Broadcasting, in three rules\n\nBroadcasting is what lets you write `x + b` where `x` is `(32, 128, 3072)` and `b` is just `(3072,)`. The rules, applied right to left:\n\n1. Line the shapes up from the right, padding the shorter one with 1s on the left.\n2. Two dimensions are compatible if they are equal, or if one of them is 1.\n3. A dimension of size 1 is stretched, conceptually repeated, to match the other.\n\nWorked:\n\n```\nx   (32, 128, 3072)\nb               (3072,)   ->  (1, 1, 3072) after padding\n                              every axis compatible\nresult (32, 128, 3072)\n```\n\nThe bias vector is added to every position of every example. No memory is actually copied; the library reads the same 3,072 numbers repeatedly. That is why broadcasting is fast as well as short.\n\n## The bug that costs a week\n\nNow the failure. Broadcasting is *too* accommodating: it will happily produce a valid result from shapes you did not intend to combine.\n\n```python\nimport numpy as np\npredictions = np.array([1.0, 2.0, 3.0, 4.0])       # shape (4,)\ntargets     = np.array([[1.1], [2.1], [2.9], [4.2]])  # shape (4, 1)\nerror = predictions - targets\nprint(error.shape)     # (4, 4)  -- not (4,)\nprint(error.mean())    # a number, and completely meaningless\n```\n\nYou wanted four errors. You got sixteen, because `(4,)` padded to `(1, 4)` and `(4, 1)` broadcast against each other into a full 4×4 grid of every prediction against every target. The mean is a real number. The loss decreases during training. The model learns something, slowly and wrongly, and nothing raises an exception.\n\nThis is the single most common silent bug in hand-written training code, and it comes from a column vector where a flat vector was expected: most often straight out of a pandas column or a `reshape(-1, 1)` somebody added to satisfy a different function.\n\nThe defence is one line:\n\n```python\nassert predictions.shape == targets.shape, (predictions.shape, targets.shape)\n```\n\nPut it before every loss computation. It costs nothing and it catches this class of bug entirely.\n\n## The shape operations, and what each does\n\nFour operations show up constantly, and confusing them causes the rest of the shape bugs.\n\n- **`reshape`** reinterprets the same numbers in the same memory order under a new shape. `(2, 6)` to `(3, 4)` is legal because both hold 12 numbers. It never moves data between positions in the flat ordering.\n- **`transpose`** reorders axes. `(32, 128, 768)` transposed to `(32, 768, 128)` puts different numbers in different places. Reshape and transpose are not interchangeable, and swapping them is the classic bug when splitting attention heads.\n- **`squeeze`** removes dimensions of size 1; **`unsqueeze`** (or `None` indexing) inserts one. These exist mainly to make broadcasting do what you meant.\n- **`view` versus `copy`.** Reshape usually returns a view sharing memory with the original, so writing to one changes the other. Transpose does too. This is fast and occasionally surprising.\n\n## Getting the head split right\n\nThe place this all comes together is multi-head attention. A tensor of shape `(batch, seq, d_model)` with `d_model = 768` and 12 heads has to become `(batch, heads, seq, d_head)` with `d_head = 64`. The correct sequence is reshape then transpose:\n\n```python\nx = x.reshape(batch, seq, 12, 64)      # split the feature axis\nx = x.transpose(0, 2, 1, 3)            # (batch, heads, seq, d_head)\n```\n\nReshaping straight to `(batch, 12, seq, 64)` is legal arithmetic and gives the wrong answer: it slices the sequence across heads instead of slicing the features. The model still trains. It just learns a worse function, and you have no error to chase.\n\n## The rule to keep\n\nEvery dimension of size 1 is an invitation for the library to stretch it. That is a feature when you meant it and a silent bug when you did not, so assert the shapes you expect rather than trusting that a result which computed is a result which is correct."},"check":{"question":"Training loss decreases smoothly but final accuracy is far worse than a baseline. Inspecting the code shows `loss = ((pred - y) ** 2).mean()` where `pred` has shape `(64,)` and `y` has shape `(64, 1)`. What is happening?","options":[{"text":"The squared error is being computed on unnormalised targets, so the loss scale is wrong but the gradients still point the right way.","correct":false,"tempting":"Scale alone would not damage accuracy this badly, and it is not what these shapes cause."},{"text":"Broadcasting produces a 64x64 grid of every prediction against every target, so the loss averages 4,096 mostly irrelevant pairs and the gradient is dominated by comparisons that should not exist.","correct":true},{"text":"The mean is taken over the wrong axis, so only the first row contributes to the loss.","correct":false,"tempting":"`.mean()` with no axis averages everything, so no row is excluded; the problem is that too many entries exist, not too few."},{"text":"`(64,)` and `(64, 1)` are incompatible, so the operation silently returns zeros and the model learns nothing.","correct":false,"tempting":"They are compatible under the broadcasting rules, which is exactly why no error appears and the result is not zero."}]},"prev":{"slug":"matrices-as-transformations","title":"A matrix is a stack of questions","url":"https://addaly.com/learn/maths-you-need/matrices-as-transformations"},"next":{"slug":"identity-inverse-and-solving","title":"Undoing a matrix, and why you rarely should","url":"https://addaly.com/learn/maths-you-need/identity-inverse-and-solving"},"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) 'Shapes, batches, and the broadcasting rules', in The Maths You Actually Need. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/maths-you-need/shapes-broadcasting-and-batches (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":"Shapes, batches, and the broadcasting rules","courseTitle":"The Maths You Actually Need","module":{"index":2,"slug":"matrices-and-layers","title":"Matrices, and what a layer really does"},"answer":null,"keyIdea":"Broadcasting silently stretches a dimension of size one to match its neighbour, which makes concise code possible and makes a whole family of bugs run without complaint.","hero":{"kind":"plate","image":"https://addaly.com/art/modules/maths-you-need/matrices-and-layers.webp","alt":"Three blocks of cells joined by arrows: a narrow column, a large square grid and a single tall bar.","caption":"A column of values entering a grid of weights and leaving as a shorter column, in that order: the shape change is what a layer does, and the grid’s rank decides whether two small matrices could stand in for it."},"blocks":[{"t":"h2","id":"the-batch-dimension-is-a-convenience-not-a-concept","runs":[{"text":"The batch dimension is a convenience, not a concept"}]},{"t":"p","runs":[{"text":"Real code never multiplies one vector at a time. It stacks 32 or 256 examples into a batch and processes them together, because a GPU is a machine for doing the same arithmetic to many things at once. So every tensor grows a leading dimension, and the shapes you read look like "},{"text":"(32, 128, 768)","code":true},{"text":": 32 examples, 128 token positions each, 768 features each."}]},{"t":"p","runs":[{"text":"The rule that keeps this simple is that matrix multiplication in NumPy and PyTorch acts on the "},{"text":"last two dimensions","b":true},{"text":" and treats everything in front as batch. So "},{"text":"(32, 128, 768) @ (768, 3072)","code":true},{"text":" gives "},{"text":"(32, 128, 3072)","code":true},{"text":": the same 768 × 3072 weight matrix applied to each of the 32 × 128 = 4,096 individual vectors, with no loop written anywhere."}]},{"t":"h2","id":"broadcasting-in-three-rules","runs":[{"text":"Broadcasting, in three rules"}]},{"t":"p","runs":[{"text":"Broadcasting is what lets you write "},{"text":"x + b","code":true},{"text":" where "},{"text":"x","code":true},{"text":" is "},{"text":"(32, 128, 3072)","code":true},{"text":" and "},{"text":"b","code":true},{"text":" is just "},{"text":"(3072,)","code":true},{"text":". The rules, applied right to left:"}]},{"t":"ol","start":1,"items":[[{"text":"Line the shapes up from the right, padding the shorter one with 1s on the left."}],[{"text":"Two dimensions are compatible if they are equal, or if one of them is 1."}],[{"text":"A dimension of size 1 is stretched, conceptually repeated, to match the other."}]]},{"t":"p","runs":[{"text":"Worked:"}]},{"t":"code","lang":"","label":"Text","text":"x   (32, 128, 3072)\nb               (3072,)   ->  (1, 1, 3072) after padding\n                              every axis compatible\nresult (32, 128, 3072)"},{"t":"p","runs":[{"text":"The bias vector is added to every position of every example. No memory is actually copied; the library reads the same 3,072 numbers repeatedly. That is why broadcasting is fast as well as short."}]},{"t":"h2","id":"the-bug-that-costs-a-week","runs":[{"text":"The bug that costs a week"}]},{"t":"p","runs":[{"text":"Now the failure. Broadcasting is "},{"text":"too","i":true},{"text":" accommodating: it will happily produce a valid result from shapes you did not intend to combine."}]},{"t":"code","lang":"python","label":"Python","text":"import numpy as np\npredictions = np.array([1.0, 2.0, 3.0, 4.0])       # shape (4,)\ntargets     = np.array([[1.1], [2.1], [2.9], [4.2]])  # shape (4, 1)\nerror = predictions - targets\nprint(error.shape)     # (4, 4)  -- not (4,)\nprint(error.mean())    # a number, and completely meaningless"},{"t":"p","runs":[{"text":"You wanted four errors. You got sixteen, because "},{"text":"(4,)","code":true},{"text":" padded to "},{"text":"(1, 4)","code":true},{"text":" and "},{"text":"(4, 1)","code":true},{"text":" broadcast against each other into a full 4×4 grid of every prediction against every target. The mean is a real number. The loss decreases during training. The model learns something, slowly and wrongly, and nothing raises an exception."}]},{"t":"p","runs":[{"text":"This is the single most common silent bug in hand-written training code, and it comes from a column vector where a flat vector was expected: most often straight out of a pandas column or a "},{"text":"reshape(-1, 1)","code":true},{"text":" somebody added to satisfy a different function."}]},{"t":"p","runs":[{"text":"The defence is one line:"}]},{"t":"code","lang":"python","label":"Python","text":"assert predictions.shape == targets.shape, (predictions.shape, targets.shape)"},{"t":"p","runs":[{"text":"Put it before every loss computation. It costs nothing and it catches this class of bug entirely."}]},{"t":"h2","id":"the-shape-operations-and-what-each-does","runs":[{"text":"The shape operations, and what each does"}]},{"t":"p","runs":[{"text":"Four operations show up constantly, and confusing them causes the rest of the shape bugs."}]},{"t":"ul","items":[[{"text":"reshape","b":true,"code":true},{"text":" reinterprets the same numbers in the same memory order under a new shape. "},{"text":"(2, 6)","code":true},{"text":" to "},{"text":"(3, 4)","code":true},{"text":" is legal because both hold 12 numbers. It never moves data between positions in the flat ordering."}],[{"text":"transpose","b":true,"code":true},{"text":" reorders axes. "},{"text":"(32, 128, 768)","code":true},{"text":" transposed to "},{"text":"(32, 768, 128)","code":true},{"text":" puts different numbers in different places. Reshape and transpose are not interchangeable, and swapping them is the classic bug when splitting attention heads."}],[{"text":"squeeze","b":true,"code":true},{"text":" removes dimensions of size 1; "},{"text":"unsqueeze","b":true,"code":true},{"text":" (or "},{"text":"None","code":true},{"text":" indexing) inserts one. These exist mainly to make broadcasting do what you meant."}],[{"text":"view","b":true,"code":true},{"text":" versus ","b":true},{"text":"copy","b":true,"code":true},{"text":".","b":true},{"text":" Reshape usually returns a view sharing memory with the original, so writing to one changes the other. Transpose does too. This is fast and occasionally surprising."}]]},{"t":"h2","id":"getting-the-head-split-right","runs":[{"text":"Getting the head split right"}]},{"t":"p","runs":[{"text":"The place this all comes together is multi-head attention. A tensor of shape "},{"text":"(batch, seq, d_model)","code":true},{"text":" with "},{"text":"d_model = 768","code":true},{"text":" and 12 heads has to become "},{"text":"(batch, heads, seq, d_head)","code":true},{"text":" with "},{"text":"d_head = 64","code":true},{"text":". The correct sequence is reshape then transpose:"}]},{"t":"code","lang":"python","label":"Python","text":"x = x.reshape(batch, seq, 12, 64)      # split the feature axis\nx = x.transpose(0, 2, 1, 3)            # (batch, heads, seq, d_head)"},{"t":"p","runs":[{"text":"Reshaping straight to "},{"text":"(batch, 12, seq, 64)","code":true},{"text":" is legal arithmetic and gives the wrong answer: it slices the sequence across heads instead of slicing the features. The model still trains. It just learns a worse function, and you have no error to chase."}]},{"t":"h2","id":"the-rule-to-keep","runs":[{"text":"The rule to keep"}]},{"t":"p","runs":[{"text":"Every dimension of size 1 is an invitation for the library to stretch it. That is a feature when you meant it and a silent bug when you did not, so assert the shapes you expect rather than trusting that a result which computed is a result which is correct."}]}],"check":{"question":[{"text":"Training loss decreases smoothly but final accuracy is far worse than a baseline. Inspecting the code shows "},{"text":"loss = ((pred - y) ** 2).mean()","code":true},{"text":" where "},{"text":"pred","code":true},{"text":" has shape "},{"text":"(64,)","code":true},{"text":" and "},{"text":"y","code":true},{"text":" has shape "},{"text":"(64, 1)","code":true},{"text":". What is happening?"}],"options":[{"text":[{"text":"The squared error is being computed on unnormalised targets, so the loss scale is wrong but the gradients still point the right way."}],"correct":false,"tempting":[{"text":"Scale alone would not damage accuracy this badly, and it is not what these shapes cause."}]},{"text":[{"text":"Broadcasting produces a 64x64 grid of every prediction against every target, so the loss averages 4,096 mostly irrelevant pairs and the gradient is dominated by comparisons that should not exist."}],"correct":true,"tempting":null},{"text":[{"text":"The mean is taken over the wrong axis, so only the first row contributes to the loss."}],"correct":false,"tempting":[{"text":".mean()","code":true},{"text":" with no axis averages everything, so no row is excluded; the problem is that too many entries exist, not too few."}]},{"text":[{"text":"(64,)","code":true},{"text":" and "},{"text":"(64, 1)","code":true},{"text":" are incompatible, so the operation silently returns zeros and the model learns nothing."}],"correct":false,"tempting":[{"text":"They are compatible under the broadcasting rules, which is exactly why no error appears and the result is not zero."}]}],"order":[0,3,1,2],"why":null},"prev":{"slug":"matrices-as-transformations","title":"A matrix is a stack of questions","minutes":8},"next":{"slug":"identity-inverse-and-solving","title":"Undoing a matrix, and why you rarely should","minutes":9}}}