A Ruler for Every Row

Deep Learning in the Real WorldMedium+20 XP+20

A Ruler for Every Row

Quantizing rounds every weight onto a coarser grid. The simplest version uses one grid for a whole weight matrix, and it has a weak spot: a single unusually large weight forces the grid to stretch far enough to reach it, and the grid's levels spread out to match. Every small weight elsewhere in the matrix then lands on the same few levels near zero.

The standard fix gives each row of the weight matrix its own grid. Each row produces one output of the layer, so this is known as per-channel quantization. Use symmetric INT8: whole-number codes from −127-127−127 to 127127127, where code 000 means exactly 000.

For each row:

  1. Find the row's largest absolute weight, mmm. The row's step size is scale=m/127\text{scale} = m / 127scale=m/127.
  2. Each weight's code is w/scalew / \text{scale}w/scale rounded to the nearest whole number. (No test value lands exactly halfway between two whole numbers.)
  3. Each weight's restored value is code×scale\text{code} \times \text{scale}code×scale. This is the number the quantized model actually computes with.

If a row is all zeros, its codes are all 000 and its restored values are all 0.00.00.0.

Task: write quantize_rows(W), where W is a list of rows of weights. Return a tuple (codes, restored):

  • codes: a list of rows of Python ints,
  • restored: a list of rows of restored values, each rounded to 4 decimal places.

Examples

W = [[0.42, -0.17, 0.05], [6.35, 0.12, -0.31]]
returns ([[127, -51, 15], [127, 2, -6]], [[0.42, -0.1687, 0.0496], [6.35, 0.1, -0.3]])
W = [[0.9, 0.3, 0.6, 0.15], [-0.08, 0.02, 0.05, -0.03]]
returns ([[127, 42, 85, 21], [-127, 32, 79, -48]], [[0.9, 0.2976, 0.6024, 0.1488], [-0.08, 0.0202, 0.0498, -0.0302]])

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run