Quantise a weight row GPTQ-style with error feedback

Why it matters GPTQ produced most of the int4 Llama checkpoints people run locally.

GPTQ quantises one column at a time and pushes each column's rounding error onto the columns not yet quantised, using the inverse Hessian.

Write gptq_row(w, Hinv, scale). w is (d,) one output row of weights, Hinv is a (d, d) upper-triangular matrix (the Cholesky factor of the inverse Hessian, as GPTQ uses), scale is the quantisation step. For i in order: q_i = round(w_i / scale) * scale; err = (w_i - q_i) / Hinv[i, i]; for j > i, w_j -= err * Hinv[i, j]. Return the array of q.

Signaturedef gptq_row(w, Hinv, scale)

Example

with Hinv = identity, there is no error feedback, so the result is plain rounding: gptq_row([0.26, 0.74], I, 0.5) is [0.5, 0.5].

Understand the idea

Plain rounding quantises each weight on its own and lets the errors pile up. GPTQ quantises one column at a time and immediately nudges the not-yet-quantised weights to cancel the rounding error, using the inverse Hessian to know how much each later weight should move. Worked example: w = [0.3, 0.7], Hinv = [[1, 0.5], [0, 1]], scale 0.5. Step 0: q_0 = round(0.3 / 0.5) * 0.5 = round(0.6) * 0.5 = 0.5. err = (0.3 - 0.5) / 1 = -0.2. Update w_1 = 0.7 - (-0.2) * 0.5 = 0.8. Step 1: q_1 = round(0.8 / 0.5) * 0.5 = round(1.6) * 0.5 = 1.0. Result [0.5, 1.0]. Plain rounding would give [0.5, 0.5], since 0.7 / 0.5 = 1.4 rounds to 1. The first weight was rounded up, so the second is pushed up to compensate. Rule: for i in order: q_i = round(w_i / scale) * scale; err = (w_i - q_i) / Hinv[i, i]; for every j > i, w_j = w_j - err * Hinv[i, j]. Work on a copy of w. Subtract the error term; adding it makes things worse. Used in: GPTQ 4-bit quantisation of LLM weights.

Shapes and data flow

w (d,), Hinv upper factor U (d, d)
for i: q_i, err_i -> w[i+1:] -= err_i * U[i, i+1:]
solution.pyPython idle
Ctrl/Cmd + Enter runs sample tests

Run checks the first 2 tests. Submit checks the hidden tests with Pro.

  • Sample 1: examplegptq_row([0.26, 0.74], np.eye(2), 0.5)
  • Sample 2: feedbackgptq_row([0.3, 0.3, 0.3], np.triu(np.full((3, 3), 0.5)) + np.eye(3) * 0.5, 0.25)