TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
TorchedUp
LearnBetaProblemsSystem DesignSoonPremium
←

221. NumPy Inner Product (Dot, Batched)

Easy

Compute the batched dot product of two arrays of vectors. This pattern shows up everywhere: per-row similarity, per-token logit, per-example loss.

Implement: def batched_dot(a, b) where a and b both have shape (B, D). Return shape (B,) — the dot product of each pair of rows.

Constraint: Do not use np.dot, np.matmul, @, or np.einsum. The point is the broadcasting pattern, not the BLAS call.

The pattern: np.sum(a * b, axis=-1). Elementwise-multiply, then reduce along the feature axis.

Why np.dot doesn't extend: np.dot was designed for 1D-vs-1D and 2D-vs-2D matmul. Calling np.dot(a, b) on two (B, D) arrays computes a @ b — a matmul, not row-by-row dot. Batched dot is the elementwise-multiply-then-sum recipe; everything else in modern numpy is built on top of this pattern.

Math

outb​=d=1∑D​ab,d​⋅bb,d​

Asked at

NumPy

import numpy as np

 

def batched_dot(...):

    pass

🔒

Premium problem

Free accounts include problems #1–20. Upgrade to unlock the editor, hidden test cases, and reference solutions for every problem.

Upgrade to PremiumBack to problems

Already premium?