This question tests your understanding of distributed systems intuition and NumPy fundamentals. You are given starter code with a Communicator class that simulates inter-device communication using Queues. Your task is to implement two parallel matrix multiplication strategies:
import threading
import numpy as np
from queue import Queue
class Communicator:
"""Simulates inter-device communication using Queues."""
def __init__(self, num_devices: int):
self.num_devices = num_devices
self.inboxes = [Queue() for _ in range(num_devices)]
def send(self, src: int, dst: int, data: np.ndarray) -> None:
self.inboxes[dst].put((src, data))
def recv(self, dst: int) -> tuple:
return self.inboxes[dst].get()
def compute_fn(comm, rank, a_chunk, b, result):
"""
TODO: Per-device compute function for Data Parallel strategy.
Each device computes a_chunk @ b, then sends result to rank 0.
"""
# YOUR CODE HERE
pass
def dp_mat_mul(a: np.ndarray, b: np.ndarray, num_devices: int) -> np.ndarray:
"""
Data Parallel Matrix Multiplication.
Split A row-wise; each device computes partial result; gather to rank 0.
"""
comm = Communicator(num_devices)
result = [None]
a_chunks = np.array_split(a, num_devices, axis=0)
threads = []
for rank in range(num_devices):
t = threading.Thread(
target=compute_fn,
args=(comm, rank, a_chunks[rank], b, result)
)
threads.append(t)
t.start()
for t in threads:
t.join()
return result[0]
def fsdp_mat_mul(a: np.ndarray, b: np.ndarray, num_devices: int) -> np.ndarray:
"""
Fully Sharded Data Parallel Matrix Multiplication.
TODO: Implement from scratch.
Both A (row-wise) and B (column-wise) are sharded across devices.
Use all-gather: rotate B shards, each device accumulates partial results.
"""
# YOUR CODE HERE
pass
if __name__ == "__main__":
np.random.seed(42)
M, K, N, num_devices = 8, 6, 4, 2
a = np.random.randn(M, K)
b = np.random.randn(K, N)
expected = a @ b
result_dp = dp_mat_mul(a, b, num_devices)
assert np.allclose(result_dp, expected), "DP result mismatch!"
print("DP passed!")
result_fsdp = fsdp_mat_mul(a, b, num_devices)
assert np.allclose(result_fsdp, expected), "FSDP result mismatch!"
print("FSDP passed!")
Communicator class for all inter-device communicationa @ b (verified via np.allclose)num_devices that evenly divides both M and N# Test 1: Basic 2-device DP
np.random.seed(42)
a = np.random.randn(8, 6)
b = np.random.randn(6, 4)
assert np.allclose(dp_mat_mul(a, b, 2), a @ b)
# Test 2: Basic 2-device FSDP
assert np.allclose(fsdp_mat_mul(a, b, 2), a @ b)
# Test 3: 4-device DP
a = np.random.randn(16, 8)
b = np.random.randn(8, 12)
assert np.allclose(dp_mat_mul(a, b, 4), a @ b)
# Test 4: 4-device FSDP
assert np.allclose(fsdp_mat_mul(a, b, 4), a @ b)
# Test 5: Single device (degenerate case)
a = np.random.randn(4, 3)
b = np.random.randn(3, 5)
assert np.allclose(dp_mat_mul(a, b, 1), a @ b)
assert np.allclose(fsdp_mat_mul(a, b, 1), a @ b)
Data Parallel (DP):
a_chunk @ bFully Sharded Data Parallel (FSDP):
a_chunk @ b_shard only produces a partial column blocka_chunk @ b_shard_j and places them in the correct column positionsdef compute_fn(comm, rank, a_chunk, b, result):
"""
Per-device compute function for Data Parallel strategy.
Each device computes a_chunk @ b, then sends result to rank 0.
"""
local_result = a_chunk @ b
if rank == 0:
# Rank 0 collects all partial results
parts = [None] * comm.num_devices
parts[0] = local_result
for _ in range(1, comm.num_devices):
src, data = comm.recv(0)
parts[src] = data
# Concatenate row-wise in rank order
result[0] = np.concatenate(parts, axis=0)
else:
# Other ranks send their results to rank 0
comm.send(rank, 0, local_result)
How it works:
a_chunk @ b — a partial block of rows of the final resultWhy parts[src] = data? Messages may arrive out of order. By storing each result at index src, we guarantee correct row ordering regardless of arrival order.
def fsdp_mat_mul(a: np.ndarray, b: np.ndarray, num_devices: int) -> np.ndarray:
"""
Fully Sharded Data Parallel Matrix Multiplication.
Both A (row-wise) and B (column-wise) are sharded across devices.
"""
comm = Communicator(num_devices)
results = [None] * num_devices
a_chunks = np.array_split(a, num_devices, axis=0) # Row-wise split
b_chunks = np.array_split(b, num_devices, axis=1) # Column-wise split
def fsdp_worker(rank, a_chunk, b_shard):
N = b.shape[1]
local_result = np.zeros((a_chunk.shape[0], N))
# Determine column ranges for each shard
col_sizes = [np.array_split(b, num_devices, axis=1)[i].shape[1]
for i in range(num_devices)]
col_offsets = [sum(col_sizes[:i]) for i in range(num_devices)]
# Compute with initial local shard
current_shard = b_shard
current_owner = rank
for step in range(num_devices):
# Compute partial result and place in correct columns
partial = a_chunk @ current_shard
col_start = col_offsets[current_owner]
col_end = col_start + col_sizes[current_owner]
local_result[:, col_start:col_end] = partial
if step < num_devices - 1:
# Ring rotation: send current shard to next, receive from previous
next_rank = (rank + 1) % num_devices
prev_rank = (rank - 1) % num_devices
comm.send(rank, next_rank, (current_owner, current_shard))
src, (shard_owner, received_shard) = comm.recv(rank)
current_shard = received_shard
current_owner = shard_owner
results[rank] = local_result
threads = []
rank (num_devices):
t = threading.Thread(
target=fsdp_worker,
args=(rank, a_chunks[rank], b_chunks[rank])
)
threads.append(t)
t.start()
t threads:
t.join()
np.concatenate(results, axis=)
How it works:
a_chunk @ b_shardnum_devices steps, every device has computed all column blocks of its row rangeWhy track current_owner? As B shards rotate through the ring, we need to know which column range each shard corresponds to. The owner index maps to the original column offset.
Communication pattern:
Step 0: Device i computes with B_shard[i] (local, no communication)
Step 1: Device i receives B_shard[i-1] from ring (one send + one recv)
Step 2: Device i receives B_shard[i-2] from ring (one send + one recv)
...
Step D-1: Final rotation, all shards seen
| Strategy | Computation per device | Communication per device | Memory per device |
|---|---|---|---|
| DP | O(M/D × K × N) | O(M/D × N) — one gather | O(K × N) for full B |
| FSDP | O(M/D × K × N) total | O((D-1) × K × N/D) — ring rotations | O(K × N/D) for B shard |
Key tradeoff: DP uses less communication but requires each device to store the full B matrix. FSDP reduces per-device memory at the cost of more communication rounds.
In real-world LLM training, model parameters can be hundreds of billions. DP replicates the full model on every device, which is infeasible when a single GPU has 80GB memory but the model requires 400GB. FSDP shards both parameters and optimizer states, reducing per-device memory from O(Model) to O(Model/D).
| Pattern | Used By | Description |
|---|---|---|
| All-Reduce | DP gradient sync | Sum gradients across all devices |
| All-Gather | FSDP forward pass | Reconstruct full parameters from shards |
| Reduce-Scatter | FSDP backward pass | Reduce gradients + scatter to shard owners |
| Ring topology | NCCL backend | Bandwidth-optimal for large tensors |
| Tree topology | Small messages | Latency-optimal for small tensors |
Training Grok-scale models uses multiple parallelism strategies simultaneously: