Differentiate a quadratic form when the matrix is not symmetric

Quadratic forms show up in regularisers, second-order approximations of a loss, and attention-style bilinear scores. The textbook gradient 2Ax only holds when A is symmetric, which is an easy trap.

Write quad_grad(A, b, x) for f(x) = x^T A x + b^T x. A has shape (n, n) and need not be symmetric, b and x have shape (n,). Return the gradient of f at x, shape (n,).

Signaturedef quad_grad(A, b, x)

Example

A = [[0, 1], [0, 0]], b = [0, 0], x = [1, 2] gives f = x0 * x1, so the gradient is [2.0, 1.0].

Understand the idea

A quadratic form x^T A x adds up A[i][j] x_i x_j over every pair. Each x_i appears once through its row of A and once through its column, so the gradient is (A + A^T) x. The familiar 2 A x is only right when A is symmetric. The linear term b^T x adds b. Worked example: A = [[1, 2], [0, 1]], b = [1, 0], x = [1, 1]. Then f = x0^2 + 2 x0 x1 + x1^2 + x0. By hand, df/dx0 = 2 x0 + 2 x1 + 1 = 5 and df/dx1 = 2 x0 + 2 x1 = 4. Formula: A + A^T = [[2, 2], [2, 2]], times x = [4, 4], plus b = [5, 4]. Matches. The wrong 2 A x = 2 x [3, 1] = [6, 2] plus b would give [7, 2]. Rule: grad f(x) = (A + A^T) x + b, shape (n,). Quadratic forms show up in second-order loss approximations, regularisers and bilinear attention scores.

solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks all 4.

  • Sample 1: examplequad_grad([[0, 1], [0, 0]], [0, 0], [1, 2])
  • Sample 2: random non-symmetricquad_grad(_A, _b, _x)
  • Test 3: symmetric matrixquad_grad(_Sy, _b, _x)
  • Test 4: at zero the gradient is bquad_grad(_A, _b, np.zeros(4))