// ======================================================================== // /content/posts/ml-systems/binary-coding-quantization.typ // ======================================================================== #import "@tola/source:0.0.0": tola-meta #import "@tola-modules/nasapunk:0.0.0": mi, mitex #import "@tola-modules/nasapunk:0.0.0": callout #import "/figures/binary-coding-quantization.typ" as fig #tola-meta(( title: "Binary-Coding Quantization: Weights as Sums of Signs", date: "2026-11-24", summary: "How BCQ writes a weight as a sum of signed scales, how greedy and alternating fits choose the scales, how fast its error falls with each bit, how it compares with uniform quantization, and how a kernel computes with bit planes.", tags: ("Quantization", "LLM-Inference"), weight: 10, toc-depth: 2, )) *Binary-coding quantization* (BCQ) stores a weight as a sum of terms, each a sign times a scale: #mitex(`w \approx \sum_{p=1}^{P} \alpha_p \, b_p, \qquad b_p \in \{-1, +1\}`) Each term corrects what the earlier ones left, so the first _p_ terms are a _p_-bit quantization on their own. Stored as separate bit planes, one copy of the weights can be read at 1, 2, 3 or 4 bits, and the arithmetic reduces to adding and subtracting. This post covers the format, the two ways to fit it, how fast its error falls with each bit, how it compares with uniform quantization, and how a kernel computes with it. = The Format == Signs and Scales Weights are split into groups of _g_ consecutive weights. Each weight stores _P_ sign bits #mi(`b_1, \dots, b_P`)\; each group stores _P_ scales #mi(`\alpha_1 > \alpha_2 > \dots > \alpha_P > 0`), shared by its weights. The signs of all weights for one _p_ form *bit plane p*. @fig-format shows one group with _g_ = 8 and _P_ = 3. Each column is one weight _j_; each row is one plane _p_, with its scale #mi(`\alpha_p`): #figure(fig.fig-format(), caption: [BCQ on one group, fitted with the greedy method described below. The error on the right is a share of the group's #mi(`\sum w^2 = 3.8`).]) Storage per weight is _P_ bits for the signs plus the group's share of the scales. With an FP16 α per plane and group, each plane stores 1 bit for the sign of every weight, plus one 16-bit α shared by _g_ weights, so one plane costs #mitex(`1 + \frac{16}{g} \text{ bits per weight (bpw)}`) 1.125 bpw for _g_ = 128 and 2 bpw for _g_ = 16. Small groups fit better but pay more for their scales, the same trade-off as in group-wise INT4 formats. == The Grid A group with _P_ planes can take 2#super[_P_] values, the sums #mi(`\pm\alpha_1 \pm \dots \pm \alpha_P`). We call this set the *grid*. #figure(fig.fig-grid(), caption: [The grid for four choices of α. Flipping every sign negates a value, so each grid is symmetric about 0.]) - *The grid is symmetric about 0*, because flipping every sign of a value gives its negative. It has no offset, so a group whose weights are centred away from 0 cannot shift its levels to follow them. - *Uniform quantization is a special case.* With #mi(`\alpha_{p+1} = \alpha_p / 2`), the levels are evenly spaced: #mi(`\alpha = (1, 0.5)`) gives {−1.5, −0.5, 0.5, 1.5}. Other α make the spacing uneven. = Fitting the Signs and Scales #callout(kind: "info", title: [THE PROBLEM])[ Given the _g_ weights #mi(`w_1, \dots, w_g`) of one group and the number of planes _P_, choose the signs #mi(`b_{p,j} \in \{-1, +1\}`) and the scales #mi(`\alpha_1, \dots, \alpha_P`) that minimize the squared error #mitex(`\sum_{j=1}^{g} \Big(w_j - \sum_{p=1}^{P} \alpha_p \, b_{p,j}\Big)^2`) Every group is fitted on its own. The signs and the scales depend on each other: the best signs depend on the scales, and the best scales on the signs. ] To compare fits, we measure the error relative to the size of the weights. With #mi(`\hat w_{b,j}`) the value of weight _j_ after reading _b_ planes, #mitex(`D(b) = \frac{\sum_j (w_j - \hat w_{b,j})^2}{\sum_j w_j^2}`) is the share of the weights' *energy*, their sum of squares, that is left as error. _D_ = 0 is an exact fit, and _D_(0) = 1, since with no planes every weight is 0. In @fig-format, _D_(1), _D_(2) and _D_(3) are the numbers on the right. One plane has a closed-form answer. For more planes there are two methods: greedy, which fits one plane at a time, and alternating, which fits all planes together. == One Plane With one plane, we want the α and signs that minimize #mi(`\sum_j (w_j - \alpha b_j)^2`) over a group. For any α > 0, the best sign is #mi(`b_j = \operatorname{sign}(w_j)`). Then each term is #mi(`(\lvert w_j \rvert - \alpha)^2`), and setting the derivative in α to zero gives #mitex(`\alpha = \frac{1}{g} \sum_j \lvert w_j \rvert = \operatorname{mean}\lvert w \rvert`) the scale #link("https://arxiv.org/abs/1603.05279")[XNOR-Net] derived for binary-weight networks. Substituting it back, with #mi(`m = \operatorname{mean}\lvert w \rvert`) and #mi(`\sum_j \lvert w_j \rvert = g m`), the error is #mitex(`\sum_j (\lvert w_j \rvert - m)^2 = \sum_j w_j^2 - 2m \cdot g m + g m^2 = \sum_j w_j^2 - g m^2`) Dividing by #mi(`\sum_j w_j^2 = g \operatorname{mean}(w^2)`) gives #mitex(`D(1) = 1 - \frac{(\operatorname{mean}\lvert w \rvert)^2}{\operatorname{mean}(w^2)}`) It depends only on the shape of the distribution: - *Gaussian*: #mi(`\operatorname{mean}\lvert w \rvert = \sigma\sqrt{2/\pi}`), so #mi(`D(1) = 1 - 2/\pi \approx 0.363`). - *Laplace*, with heavier tails: #mi(`\operatorname{mean}\lvert w \rvert = b`) and #mi(`\operatorname{mean}(w^2) = 2b^2`), so _D_(1) = 0.5. - *Uniform* on [−_a_, _a_]: #mi(`\operatorname{mean}\lvert w \rvert = a/2`) and #mi(`\operatorname{mean}(w^2) = a^2/3`), so _D_(1) = 0.25. == Greedy: One Plane at a Time The greedy method (#link("https://arxiv.org/abs/1706.02021")[Guo et al., 2017]) fits each plane like the single plane above, on what the earlier planes left: ```python r = w # residual: what the planes so far leave out for p in range(P): b[p] = sign(r) # one sign per weight alpha[p] = mean(abs(r)) # one scale for the group r = r - alpha[p] * b[p] # remove what plane p represents # now w = alpha[0] * b[0] + ... + alpha[P-1] * b[P-1] + r ``` With the four weights #mi(`w = (-0.3, -0.1, 0.2, 1.4)`) and _P_ = 2, each line of the loop gives one row of @tab-greedy-steps: #figure( table( columns: 6, align: (left, right, right, right, right, left), table.header([Step], [_w_#sub[1]], [_w_#sub[2]], [_w_#sub[3]], [_w_#sub[4]], [Shared by the group]), [_w_], [−0.3], [−0.1], [0.2], [1.4], [], [#mi(`b_1 = \operatorname{sign}(w)`)], [−1], [−1], [+1], [+1], [#mi(`\alpha_1 = \operatorname{mean}\lvert w \rvert = 0.5`)], [#mi(`r = w - \alpha_1 b_1`)], [0.2], [0.4], [−0.3], [0.9], [squared error 1.10], [#mi(`b_2 = \operatorname{sign}(r)`)], [+1], [+1], [−1], [+1], [#mi(`\alpha_2 = \operatorname{mean}\lvert r \rvert = 0.45`)], [#mi(`r = r - \alpha_2 b_2`)], [−0.25], [−0.05], [0.15], [0.45], [squared error 0.29], [#mi(`\hat w = \alpha_1 b_1 + \alpha_2 b_2`)], [−0.05], [−0.05], [0.05], [0.95], [], ), caption: [Greedy BCQ with _P_ = 2 on a group of four weights, one row per line of the loop. The squared error is #mi(`\sum r^2`) after each plane.], ) Each step only adds a correction, so the first _p_ planes are exactly what greedy would have built with _P_ = _p_. *Reading fewer planes gives the greedy fit at fewer bits, not a broken weight.* In @fig-format, _D_ falls from 0.304 to 0.082 to 0.034 as planes 2 and 3 are read. == Where Greedy Falls Short Each greedy α is the best scale for its own plane given the earlier ones, but it is chosen before the later planes exist. In @tab-greedy-steps, greedy ends with #mi(`\alpha = (0.5, 0.45)`), the grid {−0.95, −0.05, 0.05, 0.95} and a squared error of 0.29. With the same signs, two planes can do much better. To see where greedy's α go wrong, split each value #mi(`\alpha_1 b_1 + \alpha_2 b_2`) into a sign and a magnitude. With two planes and #mi(`\alpha_1 > \alpha_2`): - *The sign of the value is the sign of #mi(`b_1`)*, because #mi(`\alpha_2`) is too small to flip it. - *The magnitude depends on whether #mi(`b_2`) has the same sign as #mi(`b_1`):* - same sign: the two terms add, and the magnitude is #mi(`\alpha_1 + \alpha_2`), the large level; - opposite signs: the two terms partly cancel, and the magnitude is #mi(`\alpha_1 - \alpha_2`), the small level. So plane 2 splits the weights into two classes by magnitude. In @tab-greedy-steps, #mi(`b_2`) has the opposite sign of #mi(`b_1`) for _w_#sub[1], _w_#sub[2] and _w_#sub[3], the small class (|_w_| = 0.3, 0.1, 0.2), and the same sign for _w_#sub[4], the large class (|_w_| = 1.4). For a fixed split, the best level for each class is the mean |_w_| of that class, for the same reason that one plane takes #mi(`\alpha = \operatorname{mean}\lvert w \rvert`): - small class: (0.3 + 0.1 + 0.2) / 3 = 0.2; - large class: 1.4. Solving #mi(`\alpha_1 - \alpha_2 = 0.2`) and #mi(`\alpha_1 + \alpha_2 = 1.4`) gives #mi(`\alpha_1 = 0.8,\ \alpha_2 = 0.6`). Greedy instead puts the two levels at #mi(`0.5 \pm 0.45`), that is, 0.05 and 0.95, centred on mean |_w_| = 0.5 rather than on the two class means. With #mi(`\alpha = (0.8, 0.6)`) and the same signs, the grid is {−1.4, −0.2, 0.2, 1.4} and the squared error is 0.02, 14 times lower: #figure(fig.fig-fit(), caption: [The same four weights and the same signs, with greedy α (a) and with α refitted by least squares (b). Each weight's value is the tip of its orange arrow.]) *Greedy never makes this correction.* It fixes #mi(`\alpha_1`) before plane 2 exists and does not go back to it. Refitting α for fixed signs is the first step of the alternating method in the next section. *Greedy's two levels are the class means only when as many weights fall above mean |w| as below.* With half the weights in each class, of class means #mi(`m_s`) and #mi(`m_l`), mean |_w_| is #mi(`(m_s + m_l)/2`) and the mean distance from it is #mi(`(m_l - m_s)/2`), so greedy lands on #mi(`m_s`) and #mi(`m_l`) exactly. The example has 3 small weights and 1 large one. Bell-shaped weights are unbalanced in the same direction: for a Gaussian, only 42.5% of the magnitudes exceed their mean. The greedy levels then sit below both class means: #figure(fig.fig-magnitude(), caption: [Two planes on Gaussian weights, seen as a 2-level quantizer of |_w_|. (a) Greedy splits at mean |_w_| = 0.798 and puts the levels at 0.798 ± 0.483; the class means (hollow) are 0.378 and 1.365. (b) The best 2-plane fit: each level is its class mean and the split lies halfway between them. _D_(2) is the remaining share of the energy.]) == Alternating: All Planes Together #link("https://arxiv.org/abs/1802.00150")[Xu et al. (2018)] fit all planes together, alternating two steps that each cannot raise the error: + *Fix the signs, solve for α.* With the signs of a group as a _P_ × _g_ matrix _B_, the best α is the least-squares solution #mi(`\alpha = (B B^\top)^{-1} B w`), a _P_ × _P_ system per group. + *Fix α, choose the signs.* Each weight takes the nearest of the 2#super[_P_] grid values, which sets all its _P_ signs. With the grid sorted, this is a comparison against the midpoints between neighbouring values (Xu et al. use a binary search tree). On the example of the previous section: + Step 1 takes greedy's signs from @tab-greedy-steps and gives #mi(`\alpha = (0.8, 0.6)`), the fit of @fig-fit (b). + Step 2 checks each weight against the new grid {−1.4, −0.2, 0.2, 1.4}. Every weight is already nearest to its current value, so no sign changes, and the fit stops after one round. In general, new α move the grid, some weights end up nearer a different value and change their signs, and the two steps repeat until nothing changes. Starting from the greedy fit, a few rounds suffice. This is Lloyd's algorithm (_k_-means in one dimension) restricted to grids of the form #mi(`\pm\alpha_1 \pm \dots \pm \alpha_P`). *The price is the prefix property.* Alternating fits α for one _P_. In both cases below, its first plane keeps an #mi(`\alpha_1`) larger than mean |_w_|, so read alone it is a worse 1-bit fit: #figure( table( columns: 5, table.header([Fit], [Example, 1 plane], [Example, 2 planes], [Gaussian _D_, 1 plane], [Gaussian _D_, 2 planes]), [Greedy], [1.10], [0.29], [0.363], [0.130], [Alternating], [1.46], [0.02], [0.397], [0.117], ), caption: [Error after reading the first plane and both planes of a 2-plane fit. Example: squared error on #mi(`w = (-0.3, -0.1, 0.2, 1.4)`). Gaussian: remaining share of the energy on 10#super[6] samples (numpy), one α per plane for all of them.], ) #callout(kind: "info", title: [GREEDY OR ALTERNATING])[ - *Greedy* fits one plane at a time, each given the planes before it, so every prefix of _p_ planes is itself a good _p_-plane fit. Use it when a kernel reads fewer planes for some weights or at some times. - *Alternating* fits all _P_ planes together, for the error after reading all of them, and its prefixes get worse. Use it when a kernel always reads all _P_ planes. ] = How Fast the Error Falls This section follows _D_(_b_) as _b_ grows. For a uniform quantizer, one more bit halves the step between levels, and the rounding error, whose variance is proportional to the step squared, falls by 4. *Greedy BCQ falls by 4 per plane only on uniformly distributed weights.* There, the residual after a plane is again uniform, at half the width, so every plane solves the same problem at half the scale. On bell-shaped weights it falls more slowly: #figure(fig.fig-decay(), caption: [_D_ against planes read, on a log scale, simulated with numpy (4 × 10#super[5] samples per distribution, one α per plane for all of them). Blue: greedy fits on Gaussian and on Laplace weights. Teal: alternating fits on Gaussian weights, each depth fitted on its own. Grey: greedy on uniform weights, which divides _D_ by exactly 4 per plane.]) - *Gaussian, greedy*: 0.363, 0.130, 0.058, 0.033. Planes 2, 3 and 4 divide _D_ by 2.8, 2.2 and 1.8. - *Laplace, greedy*: 0.501, 0.230, 0.143, 0.096, divided by 2.2, 1.6 and 1.5. The heavier the tails, the slower the fall. - *Gaussian, alternating*: 0.363, 0.117, 0.037, 0.012, about 3× per plane. The best possible 16-level quantizer for a Gaussian (Lloyd–Max) leaves 0.0095, so at 4 bits most of greedy's shortfall comes from its fitting order, not from the grid. @fig-magnitude shows the first step of the mechanism. Inside each sign, the residual left by plane 1 is skewed: more weights sit just below #mi(`\alpha_1`) than far above it. A symmetric step of ±#mi(`\alpha_2`) fits a skewed residual poorly, and each later plane inherits a skewed residual again. = BCQ Against Uniform Quantization A uniform format with an offset, such as Q2_K, writes a weight as #mi(`w \approx d \cdot q - m`) with #mi(`q \in \{0, 1, 2, 3\}`), a scale _d_ and a min _m_ per group. Its four levels are evenly spaced but shifted to fit each group. Two BCQ planes give four levels that are unevenly spaced but centred on 0. *Both spend two parameters per group: the uniform format on a step and an offset, BCQ on two steps.* To see which parameter matters more, we fitted each 2-bit grid to Gaussian weights in groups of 16, with exact (unquantized) parameters, so only the shape of the grid differs: #figure( table( columns: 3, table.header([2-bit grid], [Parameters per group], [_D_(2)]), [BCQ, greedy], [α#sub[1], α#sub[2]], [0.114], [Even and centred on 0 (BCQ with #mi(`\alpha_2 = \alpha_1/2`))], [one scale], [0.104], [BCQ, alternating], [α#sub[1], α#sub[2]], [0.092], [Even with an offset], [scale, min], [0.072], [BCQ with an offset, alternating], [α#sub[1], α#sub[2], offset], [0.071], ), caption: [Remaining share of the energy at 2 bits per weight, on 20,000 groups of 16 Gaussian samples (numpy). Greedy BCQ as in the pseudocode above; every other grid fitted by alternating least squares, from the greedy fit or from the group's min and max.], ) - *The offset is worth more than uneven spacing.* Going from an even, centred grid to an uneven one lowers _D_ from 0.104 to 0.092; adding an offset to the even grid lowers it to 0.072. - *Small groups are where the offset pays.* The mean of 16 Gaussian samples carries 1/16 ≈ 6.3% of their energy, close to the offset grid's whole error of 7.2%. A grid centred on 0 has to cover that shift with its levels; an offset removes it first. - *BCQ with an offset matches the uniform grid*: #mi(`w \approx \sum_p \alpha_p b_p + z`) reaches 0.071, at the cost of a third parameter per group. #link("https://arxiv.org/abs/2206.09557")[LUT-GEMM] adds such an offset so that its kernel also covers uniform quantization: with #mi(`\alpha = (d, d/2)`) and #mi(`z = 1.5d - m`), the four values are exactly #mi(`d q - m`). The last point also means that the bits of a uniform integer, stored most significant bit first, are bit planes of BCQ with an offset. Reading only the top bits of such an integer is a coarser uniform quantization, so it keeps the prefix property too. = Computing with Bit Planes == The Planar Layout A kernel saves time by reading fewer planes only if each plane is stored on its own. A packed format keeps both bits of a weight in one byte; a planar layout stores plane 1 of a row, then plane 2: #figure(fig.fig-layout(), caption: [Eight 2-bit weights in two layouts. Packed, a 1-bit read still loads every byte; in planes, it loads half of them.]) == Each Plane Is an Add or a Subtract The output of a matrix-vector product with BCQ weights is #mitex(`y_j = \sum_i x_i \hat w_{ij} = \sum_p \sum_i (\alpha_{p} x_i)\, b_{p,ij}`) Suppose row _i_ of _W_ holds the weights of one input #mi(`x_i`) for every output _j_, and α is shared by 16 consecutive outputs. The kernel computes #mi(`c = \alpha_p x_i`) once per plane and group, then adds _c_ to or subtracts it from each of the 16 accumulators, as the 16 sign bits say. No weight needs a multiply. == Lookup Tables In the other layout, each output is a dot product along a row, #mi(`\sum_i x_i b_{p,ij}`) for one plane. #link("https://arxiv.org/abs/2206.09557")[LUT-GEMM] (Park et al., ICLR 2024) splits _x_ into chunks of μ inputs and computes all #mi(`2^\mu`) signed sums of each chunk once per input vector. Then every μ sign bits of a row form an index into that table: #figure(fig.fig-lut(), caption: [A table over μ = 3 inputs. Bit 1 means +1 and bit 0 means −1, so #raw("101") selects #mi(`x_1 - x_2 + x_3`). Each row looks up its value instead of adding three inputs.]) With μ = 8, a table of 256 sums replaces 8 additions by one lookup. The table is built once per chunk and input vector and is shared by every row and every plane, so its cost is spread over all of them. It needs α to be constant across the μ inputs of a chunk, so groups run along the input dimension. // ======================================================================== // /figures/binary-coding-quantization.typ // ======================================================================== // Figures for content/posts/ml-systems/binary-coding-quantization.typ, drawn // with cetz. True scale (1pt per unit, y grows upward, under ~560pt wide), // colours from the theme kit so every figure follows the day / night switch. // Small examples are computed by hand in the post; distribution numbers // (Gaussian, Laplace, uniform) come from numpy simulations. #import "@tola-modules/nasapunk:0.0.0": cetz, c, palette, txt #let paper = palette.paper #let grid-stroke = (paint: c.hair, thickness: .5pt, dash: "dotted") #let axis-stroke = .6pt + c.line #let canvas(body) = cetz.canvas(length: 1pt, body) #let lbl(body, size: 8pt, fill: c.ink, weight: 400) = txt(body, size: size, fill: fill, weight: weight) #let log10(v) = calc.log(v, base: 10) /// A number with a typographic minus sign. #let fmt(v) = str(v).replace("-", "−") #let sgn(v) = if v >= 0 { 1 } else { -1 } /// A polyline with a marker on every point. #let series(pts, color, dash: none, marker: "circle", w: 1.2pt) = { import cetz.draw: * line(..pts, stroke: (paint: color, thickness: w, dash: dash, join: "round")) for p in pts { let (x, y) = p if marker == "circle" { circle(p, radius: 2.3, fill: color, stroke: .6pt + paper) } if marker == "square" { rect((x - 2.3, y - 2.3), (x + 2.3, y + 2.3), fill: color, stroke: .6pt + paper) } if marker == "hollow" { circle(p, radius: 2.4, fill: paper, stroke: 1pt + color) } } } #let arw(..pts, color: c.line, w: .8pt, dash: none) = cetz.draw.line( ..pts, stroke: (paint: color, thickness: w, dash: dash), mark: (end: "stealth", fill: color, scale: .5), ) /// All 2^P sums of +-alpha_p, sorted. #let levels(alphas) = { let out = (0,) for a in alphas { out = out.map(v => (v - a, v + a)).flatten() } out.sorted() } // ============================================================================ // 1. The format // ============================================================================ // Eight weights, three greedy planes: one sign per weight and plane, one // alpha per plane. #let fig-format() = canvas({ import cetz.draw: * let w = (0.9, -0.4, 0.2, -1.3, 0.6, -0.1, 0.3, -0.8) let planes = ( (1, -1, 1, -1, 1, -1, 1, -1), (1, 1, -1, -1, 1, 1, -1, -1), (1, -1, -1, -1, -1, 1, 1, 1), ) let alphas = ("0.575", "0.325", "0.15") let rec = (1.05, -0.4, 0.1, -1.05, 0.75, -0.1, 0.4, -0.75) let ds = ("0.304", "0.082", "0.034") let (x0, cw, ch) = (128, 34, 18) let X(j) = x0 + j * cw let rx = X(8) + 12 let yw = 100 // The group: g = 8 weights, indexed by j. line((X(0), 132), (X(0), 136), (X(8), 136), (X(8), 132), stroke: .6pt + c.muted) content((X(4), 140), lbl([one group: _g_ = 8 weights], size: 7.5pt, weight: 600), anchor: "south") content((x0 - 10, 118), txt(size: 7.5pt)[index _j_], anchor: "east") for j in range(8) { content((X(j) + cw / 2, 118), lbl(str(j + 1), size: 7pt, fill: c.muted)) } content((x0 - 10, yw), lbl[weight _w#sub[j]_], anchor: "east") for (j, v) in w.enumerate() { content((X(j) + cw / 2, yw), lbl(fmt(v), size: 7.5pt, weight: 600)) } content((rx, yw + 6), txt(size: 7pt)[error left after], anchor: "west") content((rx, yw - 4), txt(size: 7pt)[planes 1 to _p_], anchor: "west") for (p, signs) in planes.enumerate() { let y = 86 - p * (ch + 4) content((x0 - 10, y - ch / 2), lbl([_p_ = #(p + 1) · α#sub[#(p + 1)] = #alphas.at(p)], size: 7.5pt), anchor: "east") for (j, s) in signs.enumerate() { let pos = s > 0 rect( (X(j) + 1, y), (X(j) + cw - 1, y - ch), fill: if pos { c.blue1 } else { c.orange1 }, stroke: .5pt + if pos { c.blue } else { c.orange }, ) content((X(j) + cw / 2, y - ch / 2), lbl(if pos { "+1" } else { "−1" }, size: 7.5pt)) } content((rx, y - ch / 2), lbl(ds.at(p), size: 7.5pt), anchor: "west") } // The P = 3 planes, as a bracket on the left. let (ptop, pbot) = (86, 86 - 3 * (ch + 4) + 4) line((24, ptop), (20, ptop), (20, pbot), (24, pbot), stroke: .6pt + c.muted) content((16, (ptop + pbot) / 2), align(right, lbl([_P_ = 3 \ planes], size: 7.5pt, weight: 600)), anchor: "east") let yr = 86 - 3 * (ch + 4) - 8 line((X(0), yr + 8), (X(8), yr + 8), stroke: axis-stroke) content((x0 - 10, yr), lbl[3-bit value #box[$hat(w)_j$]], anchor: "east") for (j, v) in rec.enumerate() { content((X(j) + cw / 2, yr), lbl(fmt(v), size: 7.5pt, fill: c.blue)) } content((X(4), yr - 16), txt(size: 7.5pt)[column _j_: #box[$hat(w)_j = alpha_1 b_(1,j) + alpha_2 b_(2,j) + alpha_3 b_(3,j)$]\; row _p_: bit plane _p_]) }) // The values a group can take: all 2^P signed sums of its alphas. #let fig-grid() = canvas({ import cetz.draw: * let rows = ( ([1 plane], (1,), [α = (1)]), ([2 planes], (1, 0.5), [α = (1, 0.5): even]), ([2 planes], (1, 0.3), [α = (1, 0.3): uneven]), ([3 planes], (1, 0.5, 0.25), [α = (1, 0.5, 0.25): even]), ) let (x0, sx, pitch) = (70, 80, 34) let X(v) = x0 + (v + 2) * sx let n = rows.len() for (r, (name, al, note)) in rows.enumerate() { let y = (n - 1 - r) * pitch content((x0 - 10, y), lbl(name, size: 7.5pt), anchor: "east") line((X(-2), y), (X(2), y), stroke: axis-stroke) line((X(0), y - 4), (X(0), y + 4), stroke: .8pt + c.muted) let lv = levels(al) for v in lv { circle((X(v), y), radius: 2.8, fill: c.blue, stroke: .6pt + paper) content((X(v), y - 6), lbl(fmt(calc.round(v, digits: 2)), size: 6.5pt, fill: c.muted), anchor: "north") } content((X(2) + 10, y), lbl(note, size: 7.5pt), anchor: "west") } content((X(0), (n - 1) * pitch + 14), txt(size: 7pt)[0], anchor: "south") }) // ============================================================================ // 2. Fitting the scales // ============================================================================ // The same four weights fitted two ways: greedy alpha = (0.5, 0.45) against // the best alpha for the same signs, (0.8, 0.6). #let fig-fit() = canvas({ import cetz.draw: * let ws = (-0.3, -0.1, 0.2, 1.4) let row = 24 let top = ws.len() * row let sx = 70 let panel(x0, title, a1, a2, sse, names: false) = { let X(v) = x0 + (v + 1.5) * sx for v in (-a1 - a2, -a1 + a2, a1 - a2, a1 + a2) { line((X(v), -4), (X(v), top), stroke: grid-stroke) } line((X(0), -4), (X(0), top), stroke: axis-stroke) for v in (-1, 0, 1) { content((X(v), -12), lbl(fmt(v), size: 7pt, fill: c.muted)) } content((X(-1.5), top + 12), lbl(title, weight: 600), anchor: "west") let bar(a, b, y, color) = line( (X(a), y), (X(b), y), stroke: 1.6pt + color, mark: (end: "stealth", fill: color, scale: .5), ) for (i, w) in ws.enumerate() { let y = top - (i + .5) * row if names { content((X(-1.5) - 6, y), lbl([_w_#sub[#(i + 1)] = #fmt(w)], size: 7.5pt), anchor: "east") } let v1 = sgn(w) * a1 let v2 = v1 + sgn(w - v1) * a2 bar(0, v1, y + 3, c.blue) bar(v1, v2, y - 3, c.orange) line((X(w), y - 8), (X(w), y + 8), stroke: 1.4pt + c.ink) } content((X(0.05), -28), lbl([α = (#fmt(a1), #fmt(a2)) · squared error *#sse*], size: 7.5pt)) } panel(52, [(a) greedy], 0.5, 0.45, "0.29", names: true) panel(310, [(b) α refitted for the same signs], 0.8, 0.6, "0.02") let ly = -48 let X0(v) = 52 + (v + 1.5) * sx line((X0(-1.3), ly), (X0(-1.05), ly), stroke: 1.6pt + c.blue, mark: (end: "stealth", fill: c.blue, scale: .5)) content((X0(-1.0), ly), lbl([plane 1: ±α#sub[1]], size: 7pt), anchor: "west") line((X0(0.2), ly), (X0(0.45), ly), stroke: 1.6pt + c.orange, mark: (end: "stealth", fill: c.orange, scale: .5)) content((X0(0.5), ly), lbl([plane 2: ±α#sub[2]], size: 7pt), anchor: "west") line((X0(1.8), ly - 6), (X0(1.8), ly + 6), stroke: 1.4pt + c.ink) content((X0(1.86), ly), lbl([original _w_], size: 7pt), anchor: "west") content((X0(3.2), ly), txt(size: 7pt)[dotted: the four values of the grid], anchor: "west") }) // Two planes as sign + magnitude: the density of |w| for Gaussian weights, // the split into small / large, and the two magnitude levels. #let fig-magnitude() = canvas({ import cetz.draw: * let (sx, sy, mmax) = (120, 62, 3.0) let f(m) = calc.sqrt(2 / calc.pi) * calc.exp(-m * m / 2) let ms = range(0, 61).map(k => k * 0.05) let panel(y0, title, t, lv, means, below, d) = { let X(m) = m * sx let Y(v) = y0 + v * sy content((X(0), Y(1.12)), lbl(title, weight: 600), anchor: "west") let left = ms.filter(m => m <= t) let rightm = ms.filter(m => m >= t) line((X(0), Y(0)), ..left.map(m => (X(m), Y(f(m)))), (X(t), Y(f(t))), (X(t), Y(0)), close: true, fill: c.blue1, stroke: none) line((X(t), Y(0)), (X(t), Y(f(t))), ..rightm.map(m => (X(m), Y(f(m)))), (X(mmax), Y(0)), close: true, fill: c.orange1, stroke: none) line(..ms.map(m => (X(m), Y(f(m)))), stroke: 1pt + c.ink) line((X(0), Y(0)), (X(mmax), Y(0)), stroke: axis-stroke) line((X(t), Y(0)), (X(t), Y(0.86)), stroke: (paint: c.ink, thickness: .8pt, dash: "dashed")) content((X(t) + 3, Y(0.86)), txt(size: 7pt)[split at #t], anchor: "west") content((X(t / 2), Y(0.12)), lbl([#below.at(0) small], size: 7pt, fill: c.blue, weight: 600)) content((X(2.2), Y(0.2)), lbl([#below.at(1) large], size: 7pt, fill: c.orange, weight: 600)) // Magnitude levels (filled) and the mean |w| of each class (hollow). for v in lv { line((X(v), Y(0) - 2), (X(v), Y(0) - 12), stroke: 2pt + c.blue) content((X(v), Y(0) - 14), lbl(str(v), size: 6.5pt, fill: c.blue), anchor: "north") } if means != none { for v in means { circle((X(v), Y(0) - 7), radius: 2.6, fill: paper, stroke: 1pt + c.ink) } } content((X(mmax) + 6, Y(0.4)), lbl([_D_(2) = #d], size: 7.5pt), anchor: "west") } panel(118, [(a) greedy: levels 0.798 ± 0.483], 0.798, (0.315, 1.281), (0.378, 1.365), ("57.5%", "42.5%"), "0.130") panel(0, [(b) best: levels at the class means], 0.981, (0.452, 1.510), none, ("67.3%", "32.7%"), "0.117") for m in (0, 1, 2, 3) { content((m * sx, -32), lbl(str(m), size: 7pt, fill: c.muted)) } content((1.5 * sx, -44), txt(size: 7.5pt)[magnitude |_w_| (Gaussian weights, σ = 1)]) line((300, -44), (300, -56), stroke: 2pt + c.blue) content((305, -50), txt(size: 7pt)[magnitude level], anchor: "west") circle((392, -50), radius: 2.6, fill: paper, stroke: 1pt + c.ink) content((398, -50), txt(size: 7pt)[mean |_w_| of the class], anchor: "west") }) // ============================================================================ // 3. How fast the error falls // ============================================================================ #let fig-decay() = canvas({ import cetz.draw: * let (sx, sy, x0) = (78, 54, 40) let X(p) = x0 + p * sx let Y(d) = (log10(d) + 2.6) * sy for (d, s) in ((1, "1"), (0.3, "0.3"), (0.1, "0.1"), (0.03, "0.03"), (0.01, "0.01"), (0.003, "0.003")) { line((X(0) - 4, Y(d)), (X(4) + 4, Y(d)), stroke: grid-stroke) content((X(0) - 8, Y(d)), lbl(s, size: 7pt, fill: c.muted), anchor: "east") } line((X(0) - 4, Y(0.0025)), (X(4) + 4, Y(0.0025)), stroke: axis-stroke) for p in range(5) { content((X(p), Y(0.0025) - 10), lbl(str(p), size: 7.5pt)) } content((X(2), Y(0.0025) - 24), txt[planes read]) content((X(0) - 8, Y(1) + 14), txt(size: 7.5pt)[_D_], anchor: "east") let pts(ds) = ds.enumerate().map(((p, d)) => (X(p), Y(d))) series(pts((1, 0.25, 0.0624, 0.0156, 0.0039)), c.muted, dash: "dashed", marker: "none", w: 1pt) series(pts((1, 0.501, 0.230, 0.143, 0.096)), c.blue, dash: "dashed", marker: "hollow", w: .9pt) series(pts((1, 0.363, 0.130, 0.058, 0.033)), c.blue) series(pts((1, 0.363, 0.117, 0.037, 0.0115)), c.teal) let lx = X(4) + 10 content((lx, Y(0.096)), lbl([greedy, Laplace], size: 7pt, fill: c.blue, weight: 600), anchor: "west") content((lx, Y(0.033)), lbl([greedy, Gaussian], size: 7pt, fill: c.blue, weight: 600), anchor: "west") content((lx, Y(0.0115)), lbl([alternating, Gaussian], size: 7pt, fill: c.teal, weight: 600), anchor: "west") content((lx, Y(0.0039)), lbl([greedy, uniform (÷4 per plane)], size: 7pt, fill: c.muted), anchor: "west") }) // ============================================================================ // 4. Computing with bit planes // ============================================================================ // Packed 2-bit codes against bit planes: which bytes a 1-bit read touches. #let fig-layout() = canvas({ import cetz.draw: * let bw = 15 let byte(x, y, cells, read) = { for (k, (name, hi)) in cells.enumerate() { rect( (x + k * bw, y), (x + (k + 1) * bw, y + 18), fill: if hi { c.blue1 } else { c.orange1 }, stroke: .5pt + c.line, ) content((x + k * bw + bw / 2, y + 9), lbl(name, size: 6pt)) } rect((x, y), (x + 8 * bw, y + 18), fill: none, stroke: if read { 1.6pt + c.ink } else { (paint: c.line, thickness: .6pt, dash: "dashed") }) } let x0 = 104 // Packed: each byte holds both bits of four weights. let yp = 60 content((x0 - 10, yp + 9), lbl([packed (Q2_K)], size: 7.5pt), anchor: "east") let packed(off) = { let out = () for k in range(4) { out.push((str(off + k + 1), true)) out.push((str(off + k + 1), false)) } out } byte(x0, yp, packed(0), true) byte(x0 + 8 * bw + 10, yp, packed(4), true) content((x0 + 16 * bw + 20, yp + 9), lbl([1 bit of _w_#sub[1]–_w_#sub[8]: read both bytes], size: 7.5pt), anchor: "west") // Planar: one byte per plane. let yq = 20 content((x0 - 10, yq + 9), lbl([bit planes (BCQ)], size: 7.5pt), anchor: "east") byte(x0, yq, range(8).map(k => (str(k + 1), true)), true) byte(x0 + 8 * bw + 10, yq, range(8).map(k => (str(k + 1), false)), false) content((x0 + 4 * bw, yq - 8), txt(size: 7pt)[plane 1], anchor: "north") content((x0 + 12 * bw + 10, yq - 8), txt(size: 7pt)[plane 2], anchor: "north") content((x0 + 16 * bw + 20, yq + 9), lbl([1 bit of _w_#sub[1]–_w_#sub[8]: read plane 1 only], size: 7.5pt), anchor: "west") // Legend. rect((x0, -30), (x0 + 10, -22), fill: c.blue1, stroke: .5pt + c.line) content((x0 + 14, -26), txt(size: 7pt)[first bit of weight _k_], anchor: "west") rect((x0 + 130, -30), (x0 + 140, -22), fill: c.orange1, stroke: .5pt + c.line) content((x0 + 144, -26), txt(size: 7pt)[second bit], anchor: "west") rect((x0 + 220, -30), (x0 + 240, -22), fill: none, stroke: 1.6pt + c.ink) content((x0 + 244, -26), txt(size: 7pt)[bytes read], anchor: "west") }) // A lookup table over mu = 3 inputs: 8 signed sums, then one lookup per // three sign bits of every row. #let fig-lut() = canvas({ import cetz.draw: * let xs = ("0.5", "−1", "2") // Inputs. content((20, 132), lbl([input chunk], size: 7.5pt, weight: 600)) for (k, v) in xs.enumerate() { let y = 104 - k * 24 rect((0, y), (40, y + 18), fill: c.grey1, stroke: .5pt + c.line) content((20, y + 9), lbl([_x_#sub[#(k + 1)] = #v], size: 7.5pt)) } arw((50, 82), (90, 82)) content((70, 76), align(center, txt(size: 7pt)[once per \ input]), anchor: "north") // Table: index bits b1 b2 b3 (1 = +1, 0 = -1). let vals = ("−1.5", "2.5", "−3.5", "0.5", "−0.5", "3.5", "−2.5", "1.5") let bits = ("000", "001", "010", "011", "100", "101", "110", "111") let (tx, th) = (96, 15) content((tx + 60, 132), lbl([table: all 8 signed sums], size: 7.5pt, weight: 600)) let ty(k) = 116 - (k + 1) * th for k in range(8) { let y = ty(k) rect((tx, y), (tx + 40, y + th), fill: c.grey1, stroke: .5pt + paper) content((tx + 20, y + th / 2), lbl(raw(bits.at(k)), size: 7pt)) rect((tx + 40, y), (tx + 120, y + th), fill: paper, stroke: .5pt + c.line) content((tx + 80, y + th / 2), lbl(vals.at(k), size: 7.5pt)) } content((tx + 60, ty(7) - 10), txt(size: 7pt)[#raw("101") = +_x_#sub[1] − _x_#sub[2] + _x_#sub[3] = 3.5]) // Weight rows: three sign bits each, one lookup each. let rows = (("row a", "101", 5), ("row b", "011", 3), ("row c", "110", 6)) let rx = 330 content((rx + 40, 132), lbl([sign bits of one plane], size: 7.5pt, weight: 600)) for (r, (name, b, k)) in rows.enumerate() { let y = 100 - r * 34 content((rx - 8, y + 9), lbl(name, size: 7.5pt), anchor: "east") rect((rx, y), (rx + 48, y + 18), fill: c.blue1, stroke: .5pt + c.blue) content((rx + 24, y + 9), lbl(raw(b), size: 8pt)) arw((rx - 34, y + 9), (tx + 124, ty(k) + th / 2), color: c.blue) content((rx + 56, y + 9), lbl([→ #vals.at(k)], size: 7.5pt), anchor: "west") } })