Distributed Block Matrix Multiplication via Cannon's Algorithm
Data Structure DesignModel answerLast updated
Coordinate grid-based worker nodes to perform memory-efficient distributed matrix multiplication without deadlocks.
You are tasked with implementing a memory-conscious distributed matrix multiplication scheme over a 2D mesh of computing nodes.
Suppose matrix $A$ (size $M \times K$) and matrix $B$ (size $K \times N$) are partitioned across a cluster of $P$ total worker machines, where $P = q \times q$ forms a square processor grid. Matrix $C = A \times B$ will be accumulated across the grid, such that node $(i, j)$ computes and holds block $C_{i, j}$.
You are provided a lower-level execution abstraction comm on each node:
comm.send(target_id, data): Transmitsdatatotarget_id.comm.receive(source_id): Blocks untildataarrives fromsource_id.comm.local_matmul(block_A, block_B): Performs local matrix multiplication on two sub-blocks.
Write a function compute_distributed_block executed concurrently by each worker node. The function should calculate the local result block $C_{i,j}$ while maintaining optimal memory usage and avoiding deadlocks.
def compute_distributed_block(node_id, my_block_A, my_block_B, neighbors):
"""
node_id: int, linear index of current processor (0 to P-1)
my_block_A: initial local block A_{i, j}
my_block_B: initial local block B_{i, j}
neighbors: dict containing:
- "comm": communication abstraction instance
- "q": grid dimension side length (sqrt(P))
Returns:
The computed local matrix block C_{i, j}
"""
pass
Constraints
- $P = q^2$ where $q$ is a positive integer.
- The maximum extra memory allocated on any node during execution must scale with the block size $O(\frac{MK + KN + MN}{P})$, rather than broadcasting full matrix rows or columns to every node.
- Assume point-to-point network communication uses blocking rendezvous semantics. Your message sequence must be deadlock-free.
Hints
Hint 1
Think about how Cannon's Algorithm aligns matrix sub-blocks prior to computation using cyclic shifts.
Hint 2
To prevent deadlock when using blocking sends and receives in a cyclic ring, alternate execution order based on whether the node's position index is odd or even.
Hint 3
How many total alignment and shift operations are required for a grid of size q x q?
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Strategy & Approach
To perform distributed matrix multiplication $C = A \times B$ on a $q \times q$ processor grid without exceeding $O(\frac{1}{P})$ memory per node, we implement Cannon's Algorithm.
Why Not Row/Column Broadcasts?
A simple approach broadcasts row-strips of $A$ and column-strips of $B$. However, broadcasting requires each node to store $O(q)$ sub-blocks simultaneously, taking $O(\frac{MN + MK + KN}{\sqrt{P}})$ space. Cannon's algorithm keeps memory footprint optimal at $O(\frac{1}{P})$ per node by maintaining at most one block of $A$ and one block of $B$ in memory at any time and shifting them cyclically across the grid network.
Grid Layout (q=3):
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)
Step 1: Initial Alignment (Preskewing)
For node $(i, j)$ to compute $C_{i,j} = \sum_{k=0}^{q-1} A_{i,k} \times B_{k,j}$, the inner indices of the local $A$ and $B$ sub-matrices must match.
- Shift block $A_{i,j}$ leftward along row $i$ by $i$ positions (cyclically).
- Shift block $B_{i,j}$ upward along column $j$ by $j$ positions (cyclically).
After this alignment, node $(i, j)$ holds $A_{i, (i+j) \bmod q}$ and $B_{(i+j) \bmod q, j}$. Notice that the inner dimension index matches $((i+j) \bmod q)$.
Step 2: Shift-and-Multiply Loop ($q$ Iterations)
For step $s = 0, \dots, q-1$:
- Perform local computation: $C_{i,j} \leftarrow C_{i,j} + \text{local_matmul}(A_\text{local}, B_\text{local})$.
- Shift $A_\text{local}$ left by 1 step along row $i$.
- Shift $B_\text{local}$ up by 1 step along column $j$.
Preventing Network Deadlock
If network send() is blocking (rendezvous), every node calling send() simultaneously causes a circular dependency (deadlock).
To guarantee progress:
- Even-indexed nodes along the communication ring
send()first, thenreceive(). - Odd-indexed nodes along the communication ring
receive()first, thensend().
Python Implementation
def compute_distributed_block(node_id, my_block_A, my_block_B, neighbors):
comm = neighbors["comm"]
q = neighbors["q"]
# Map linear node_id to 2D grid coordinates (row i, col j)
i, j = divmod(node_id, q)
# Base case for single-node execution
if q == 1:
return comm.local_matmul(my_block_A, my_block_B)
# Helper function to convert grid coordinate to flat rank
def get_rank(r, c):
return (r % q) * q + (c % q)
# Determine neighbor ranks for 2D toroidal shifts
left_neighbor = get_rank(i, j - 1)
right_neighbor = get_rank(i, j + 1)
up_neighbor = get_rank(i - 1, j)
down_neighbor = get_rank(i + 1, j)
def deadlock_free_shift(block, dest, src, pos_index):
"""
Executes a point-to-point shift.
Alternates send/receive sequence based on parity to break circular waits.
"""
if pos_index % 2 == 0:
comm.send(dest, block)
received_block = comm.receive(src)
else:
received_block = comm.receive(src)
comm.send(dest, block)
return received_block
curr_A, curr_B = my_block_A, my_block_B
# Phase 1: Initial Preskewing
# Row i shifts A left by i steps
for _ in range(i):
curr_A = deadlock_free_shift(curr_A, left_neighbor, right_neighbor, j)
# Column j shifts B up by j steps
for _ in range(j):
curr_B = deadlock_free_shift(curr_B, up_neighbor, down_neighbor, i)
# Phase 2: Accumulation & Cyclic Rotation Loop
local_C = None
for step in range(q):
partial_product = comm.local_matmul(curr_A, curr_B)
if local_C is None:
local_C = partial_product
else:
local_C += partial_product
if step < q - 1:
# Rotate A left by 1 position along the row
curr_A = deadlock_free_shift(curr_A, left_neighbor, right_neighbor, j)
# Rotate B up by 1 position along the column
curr_B = deadlock_free_shift(curr_B, up_neighbor, down_neighbor, i)
return local_C
Complexity Analysis
- Time Complexity (Compute): Each node computes $q$ sub-block multiplications. Total computation per node is $O\left(\frac{M \cdot K \cdot N}{P}\right)$, giving perfect linear scaling across $P$ nodes.
- Communication Cost: A total of $O(q) = O(\sqrt{P})$ messages are sent per node. The volume of data transmitted per node is $O\left(\frac{MK + KN}{\sqrt{P}}\right)$.
- Space Complexity: $O\left(\frac{MK + KN + MN}{P}\right)$ memory per node. Each node stores only a constant number of sub-blocks at any time.
Key Takeaways & Common Edge Cases
- Non-square Grids or Non-divisible Dimensions: If $M, K, N$ are not multiples of $q$, matrix sub-blocks can be padded with zeros to the nearest multiple before distribution, or non-uniform sub-block sizes ($\lceil K/q \rceil$ vs $\lfloor K/q \rfloor$) can be used as long as block dimensions along shared inner boundaries match.
- Double Buffering: In latency-sensitive or bandwidth-limited production systems, non-blocking communications (e.g.,
MPI_Isend,MPI_Irecv) are paired with double buffering to overlap compute phase $s$ with network shifts for phase $s+1$.