#!/usr/bin/env python3
# Source: q3-deep-learning.html
import numpy as np

def linear_forward(X, W, b):
    out = X @ W + b
    cache = (X, W)            # keep inputs for the backward pass
    return out, cache

def linear_backward(dout, cache):
    X, W = cache
    dX = dout @ W.T           # (n,k) @ (k,d) -> (n,d)
    dW = X.T @ dout           # (d,n) @ (n,k) -> (d,k)
    db = dout.sum(axis=0)     # b was broadcast over the batch, so sum
    return dX, dW, db
