Matrix Multiplication and Element-wise Operations
Problem Statement
Implement functions to perform both matrix multiplication and element-wise multiplication on tensors.
Background
PyTorch supports two types of multiplication that behave very differently:
- Matrix multiplication: follows linear algebra rules (dot products of rows and columns)
- Element-wise multiplication: multiplies corresponding elements directly
Understanding the difference is crucial for neural network operations.
Your Task
Write two functions:
- matrix_multiply(a, b) — returns the matrix product of two tensors
- elementwise_multiply(a, b) — returns the element-wise product of two tensors
Output Format
Each function should return a tensor.
Example:
a=[[1, 2], [3, 4]], b=[[5, 6], [7, 8]]
{"matmul": [[19, 22], [43, 50]], "elementwise": [[5, 12], [21, 32]]}Matrix multiplication follows linear algebra rules, element-wise multiplies corresponding elements
Constraints:
- For matrix multiplication, dimensions must be compatible
- For element-wise multiplication, tensors must have same shape
- Input tensors contain integers
1. Background Knowledge
Matrix multiplication and element-wise operations are foundational in ML/AI, powering linear layers, attention mechanisms, and convolutions in neural networks. PyTorch provides optimized implementations via dedicated operators.
Matrix Multiplication (MatMul): For matrices A∈Rm×n and B∈Rn×p, the result C=A⋅B has element cij​=\sum_{k=1}naik​bkj​. This follows linear algebra rules requiring compatible inner dimensions. PyTorch uses @ or torch.matmul(), leveraging cuBLAS/cuDNN for O(mnp) complexity on GPUs.
Element-wise Multiplication (Hadamard Product): For same-shaped tensors A,B∈Rm×n, C=A⊙B has cij​=aij​⋅bij​. PyTorch uses * or torch.mul(), with O(mn) complexity—parallelizable and memory-bound.
Key Prerequisites:
- Tensor shapes: MatMul needs (..., m, n) and (..., n, p); element-wise needs identical shapes.
- Broadcasting: PyTorch auto-broadcasts for element-wise if compatible.
- Integer inputs: No floating-point concerns here, but watch for overflow.
2. Algorithm Approach
Standard Approach: Use PyTorch primitives directly—no need to implement from scratch, as they are BLAS-optimized.
- MatMul: torch.matmul(a, b) or a @ b. Handles broadcasting and batch dims.
- Element-wise: torch.mul(a, b) or a * b.
Manual Fallback (Educational): For MatMul, nested loops over outer dims and dot product inner; for element-wise, loop over all elements. PyTorch vectorizes this via SIMD/AVX.
Output Conversion: Tests expect nested lists, not tensors: result.tolist().
3. Step-by-Step Strategy
Continue the full explanation
You're reading the free preview. Unlock the complete walkthrough, the code editor, test runner and reference solution with Premium.
Editor locked
The code editor is locked for Pro problems. It is only available for free problems. Please upgrade to gain access to the code editor for all problems.