For a composition the Jacobian is a product of layer Jacobians, . It can be built column by column with Jacobian-vector products (forward mode, right to left, one per input dimension) or row by row with vector-Jacobian products (reverse mode, left to right, one per output dimension).
Each layer here is with act in {"relu", "tanh", "sigmoid", "linear"} (ReLU derivative taken as at ). Its Jacobian is .
Implement jacobian_two_ways(layers, x):
layers: list of (W, b, act) with W of shape (m_out, m_in); x: the input point, shape (n,).Return a dict with "J_fwd", "J_rev" (both ), "n_jvp", "n_vjp" (number of passes) and "macs_fwd", "macs_rev": the total multiply-adds spent in products with the weight matrices (a product with an matrix costs ; ignore the elementwise derivative scaling).