KatInterview

Distributed Block Matrix Multiplication via Cannon's Algorithm

Data Structure DesignModel answer
HardModel answerData Structure Designdistributed systemsmatrix multiplicationconcurrency

Last 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): Transmits data to target_id.
  • comm.receive(source_id): Blocks until data arrives from source_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?