Distributed Matrix Multiplication Across Multiple GPUs
Machine LearningModel answerLast updated
Design a system to compute matrix multiplication distributed across two GPUs, handling partitioning, communication, compute overlap, and aggregation.
You need to architect a distributed computation system that multiplies two large matrices across a pair of GPUs. Both input matrices are already present on each device.
Your design should address:
- Work distribution strategy: How will you divide the computation between devices?
- Communication patterns: What primitives will coordinate the GPUs (broadcast, reduce, peer-to-peer transfers, etc.)?
- Execution orchestration: How will you pipeline computation with data movement to hide latency?
- Memory management: Buffer allocation, layout choices, and reuse strategies
- Numeric considerations: Precision choices and their impact on accuracy
- Result collection: How the final output is assembled and where it resides
- System properties: Scalability characteristics and resilience approaches
Assume you're working with matrices where each dimension can reach tens of thousands of elements. The GPUs may be connected via high-bandwidth interconnect (like NVLink) or standard PCIe lanes.
Hints
Hint 1
Consider where communication volume is minimized - splitting work by output dimensions versus intermediate dimensions has different traffic patterns
Hint 2
Overlapping data transfers with computation requires careful stream management and determining the right granularity of work chunks
Hint 3
The choice of partitioning affects both how results arrive (contiguous vs scattered) and whether cross-device numeric reductions are needed
Model answer
Hard Try it yourself first — then compare your approach, complexity and edge cases.
Distributed Matrix Multiplication: Architecture and Implementation
Problem Scoping
For matrices A (M×K) and B (K×N) both replicated on two GPUs, we need to produce C = A×B. The key constraints:
Scale analysis (M = N = K = 32,768 in bfloat16):
- Each matrix occupies 2 GiB
- Total operations: 2MNK ≈ 70 trillion FLOPs
- Per-GPU compute time: ~60ms (assuming 600 TFLOPS sustained)
- Half of output C: 1 GiB
- NVLink transfer: ~2.5ms (400 GB/s effective bandwidth)
- PCIe Gen4 transfer: ~40ms (25 GB/s effective bandwidth)
With NVLink, communication is negligible. With PCIe, communication time rivals compute time, making overlap essential.
Partitioning Strategy
Since inputs are replicated, we only need to distribute output computation. Three main approaches:
| Approach | Work Per GPU | Communication Volume | Properties |
|---|---|---|---|
| Split output rows (M dimension) | A[M/2,:]×B = C[M/2,N] | MN/2 per device (gather half) | Contiguous output slices, no cross-device reduction |
| Split output columns (N dimension) | A×B[:,N/2] = C[M,N/2] | MN/2 per device | Strided in row-major layout |
| Split inner dimension (K) | A[:,:K/2]×B[:K/2,:] | MN per device (reduce full C) | Double traffic, needs fp32 accumulation buffer |
Recommended: Row-wise output partitioning for three reasons:
- Minimal communication (half the output)
- Contiguous memory access patterns in row-major layout
- Each output element computed by single GPU (deterministic, no distributed summation)
Computation and Communication Overlap
The critical optimization is hiding communication latency behind computation:
Chunked pipeline approach:
- Divide output into multiple steps (e.g., 8-16 chunks)
- Each step processes a block of rows in round-robin fashion across GPUs
- Pipeline stages:
- GPU computes its rows for chunk j directly into output buffer
- While computing chunk j+1, GPU initiates transfer for chunk j's results
- Use separate CUDA streams for compute and communication
Chunk sizing tradeoffs:
- Too coarse: Limited overlap opportunity, exposed communication tail
- Too fine: Kernel launch overhead, poor tile efficiency, increased synchronization cost
- Sweet spot: Each chunk spans thousands of rows, maintaining 90%+ peak throughput
Implementation Architecture
import torch
import torch.distributed as dist
def distributed_matmul(A: torch.Tensor, B: torch.Tensor, num_chunks: int = 8) -> torch.Tensor:
"""
Execute distributed matrix multiplication across GPU collective.
Each rank has full A(M,K) and B(K,N), returns full C(M,N).
"""
world_size = dist.get_world_size()
rank = dist.get_rank()
M, K = A.shape
_, N = B.shape
# Align dimensions for even distribution
chunk_block_size = -(-M // num_chunks) # ceiling division
rows_per_rank = -(-chunk_block_size // world_size)
aligned_M = rows_per_rank * world_size * num_chunks
if aligned_M > M:
A = torch.cat([A, torch.zeros(aligned_M - M, K,
device=A.device, dtype=A.dtype)])
# Preallocate output buffer (reused for compute and communication)
C = torch.empty(aligned_M, N, device=A.device, dtype=A.dtype)
pending_ops = []
for chunk_idx in range(num_chunks):
# Determine this chunk's row range
chunk_start = chunk_idx * world_size * rows_per_rank
chunk_end = chunk_start + world_size * rows_per_rank
chunk_buffer = C[chunk_start:chunk_end]
# This rank's portion within the chunk
rank_start = chunk_start + rank * rows_per_rank
rank_end = rank_start + rows_per_rank
my_output = C[rank_start:rank_end]
# Compute on default stream (tensor cores with fp32 accumulation)
torch.mm(A[rank_start:rank_end], B, out=my_output)
# Launch async gather on communication stream
# NCCL will wait for compute stream via implicit synchronization
op = dist.all_gather_into_tensor(chunk_buffer, my_output, async_op=True)
pending_ops.append(op)
# Barrier: ensure all transfers complete
for op in pending_ops:
op.wait()
return C[:M] # trim padding
Key design elements:
- Single output buffer serves as both computation target and communication buffer (zero-copy)
- Interleaved row assignment ensures contiguous memory access for each all-gather operation
- Async operations with explicit handles enable fine-grained dependency management
- NCCL's stream ordering automatically synchronizes compute→communication dependency
Memory Layout Optimization
Buffer organization:
- Row-major layout for C ensures all-gather receives contiguous blocks
- A's row slices are naturally contiguous
- B remains stationary, leveraging L2 cache across multiple reads
- Total memory footprint: A + B + C (no staging buffers needed)
Reuse strategy for repeated operations:
- Cache NCCL communicator across invocations
- Preallocate output buffer for known shapes
- Consider CUDA Graph capture to eliminate per-call launch overhead (10-50μs savings per kernel)
Numerical Precision
Recommended configuration:
- Input format: bfloat16 or float16 (2 bytes/element)
- Accumulation: float32 in tensor core operations
- Output format: Match downstream requirements (bf16 for storage, fp32 if needed)
Why this matters:
- Tensor cores achieve peak throughput with mixed precision
- Row partitioning maintains consistency: each element computed by one GPU with full K-dimension accumulation
- Contrast with K-dimension splitting, which requires cross-device summation in fp32 to prevent error accumulation
- TF32 mode (opt-in for fp32 inputs) trades 10-bit mantissa for throughput
Result Aggregation Strategies
The optimal approach depends on downstream consumption:
- Full output on all GPUs: Use all-gather (as implemented above)
- Full output on one GPU: Use gather or point-to-point send/recv (50% less traffic)
- Output to host memory: Each GPU streams its partition to pinned host memory via async copy, overlapped with compute (avoids inter-GPU transfer entirely)
- Sharded consumption: Return local partition only (zero communication, used in model parallelism pipelines)
Scalability Properties
Scaling to more GPUs (P devices):
- Communication per device: O(MN/P) for gather
- Compute per device: O(MNK/P)
- Efficiency maintained when MNK/P >> MN (K should be large relative to P)
- Arithmetic intensity: Θ(K), so large inner dimensions stay compute-bound
Bottleneck transitions:
- Small K: Communication-bound regardless of overlap
- PCIe interconnect: Need aggressive overlap (16+ chunks)
- NVLink: Communication negligible, focus on load balance
Fault Tolerance Approaches
Detection mechanisms:
- NCCL watchdog timers for hung collective operations
- Checksum validation for numerical errors (rare in ECC memory)
- Heartbeat monitoring for GPU health
Recovery strategies:
- Checkpoint-restart: Save input matrices, re-execute on failure (simple but loses partial work)
- Redundant computation: Mirror calculations on subset of GPUs, compare results (2× overhead)
- Algorithmic tolerance: Accept degraded result if one GPU's partition is lost (application-dependent)
In production ML systems, matrix operations are typically part of larger graphs where framework-level fault tolerance (like PyTorch FSDP's state recovery) handles GPU failures.
Common Pitfalls
- Ignoring memory alignment: Unaligned transfers hurt bandwidth by 20-40%
- Synchronous communication: Blocking collective calls eliminate all overlap opportunity
- Wrong dimension split: K-splitting doubles traffic and introduces non-determinism
- Excessive chunking: 50+ chunks add more overhead than overlap benefit
- Stream mismanagement: Incorrect dependencies cause race conditions or unnecessary stalls
The architecture described achieves near-linear speedup (95%+ efficiency) on high-bandwidth interconnects for typical deep learning matrix dimensions (K > 1024).