Dot Product & Matrix Multiplication (@) in PyTorch

Basics
BasicsPyTorchLinear AlgebraGoogleMetaAmazon

Problem

Given an input batch X of shape (B, D_in) and a weight matrix W of shape (D_in, D_out), implement linear_matmul(X, W) returning the matrix product X @ W of shape (B, D_out).

Why It Matters: Matrix multiplication (@ / torch.matmul) is the computational heart of neural networks—powering linear projections, Q/K/V attention projections, and MLP blocks on GPUs.

Function Signature

import torch

def linear_matmul(X: torch.Tensor, W: torch.Tensor) -> torch.Tensor:
    """Multiply batch X [B, D_in] by weights W [D_in, D_out]."""

Sample Input & Output

Example 1: Single-Row Projection (1×2 @ 2×2)

Input:

X = torch.tensor([[1., 2.]]), W = torch.tensor([[3., 4.], [5., 6.]])

Expected Output:

tensor([[13., 16.]])

Explanation: Column 0: 1*3 + 2*5 = 13; Column 1: 1*4 + 2*6 = 16. Result shape is (1, 2).

Example 2: Multi-Row Batch (2×3 @ 3×1)

Input:

X = torch.tensor([[1., 0., 2.], [-1., 3., 1.]]), W = torch.tensor([[2.], [4.], [1.]])

Expected Output:

tensor([[4.], [11.]])

Explanation: Row 0: 1*2 + 0*4 + 2*1 = 4; Row 1: -1*2 + 3*4 + 1*1 = 11. Result shape is (2, 1).

Constraints & Edge Cases

  • Return a [B, Out] tensor.
  • Inner dimensions must match: X.shape[1] == W.shape[0].
  • Do not confuse @ (matrix multiplication) with * (elementwise Hadamard product).

Constraints & Evaluation Criteria

  • Return a `[B, Out]` tensor.

Hints

Python 3
Loading Code Editor...
+1 Hidden Submit Case
Input / Scenario
[[1,2]] @ [[3],[4]]
Expected Output / Criteria
[[11.]]