liveBook · Manning

Matrix-matrix multiplication

As explained in Inside Deep Learning: Math, Algorithms, Models

The binary operation that multiplies two matrices to produce a new matrix, written with the @ operator in Python and used here for performance comparison.

Matrix-matrix multiplication combines X with shape n×m and Y with shape m×p to produce C with shape n×p. In PyTorch, the @ operator performs the multiplication. Matching the inner dimensions and tracking tensor shapes prevents common implementation bugs. section 1.2.1

import timeit 
x = torch.rand(2**11, 2**11) 
time_cpu = timeit.timeit("x@x", globals=globals(), number=100)

Benchmark repeated matrix multiplication on a large PyTorch tensor with timeit. section 1.2.1

GPU comparisons depend on both workload size and device placement:

  • Small calculations may run slower on a GPU because data transfer and coordination costs can exceed the computation time. section 1.2.1
  • Move the tensors involved in the operation to the same device; mixing CUDA and CPU tensors raises a device-mismatch error. section 1.2.1
  • Benchmark repeated operations rather than a single small multiplication to make performance differences measurable. section 1.2.1

How Inside Deep Learning: Math, Algorithms, Models covers it

How deep it goes
Defines the shape rule and demonstrates timing and device placement, but does not derive the scalar multiplication formula.
Examples
Uses 2¹¹×2¹¹ tensors, repeated x@x timings, CUDA transfers, and a mixed-device error example.
What you can do after
Apply matrix multiplication with PyTorch's @ operator and timeit, then diagnose shape, workload-size, and device-placement problems.
How it connects
Connects matrix multiplication with tensors, neural networks, GPU acceleration, tensor shapes, and device placement.

Also explained in

Compare how 8 books explain matrix-matrix multiplication →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Inside Deep Learning: Math, Algorithms, Models. The section links point to the parts of the book it draws on.