File size: 2,170 Bytes
995e752
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""Reference implementation — the CORRECTNESS SPEC for `quantized_adamw_step`.

This is correct but slow. It defines exactly what your kernel must reproduce; its speed has no
bearing on your score, which is an absolute GB/s number. GENERATED by _factory/build.py.
"""
import torch


BLOCK = 2048            # quantisation block: one fp32 absmax per 2048 consecutive parameters


def _requantise(x, qmap):
    """x -> (dequantised round trip, per-block absmax). Nearest entry of the ascending 256-point map."""
    nb = x.numel() // BLOCK
    xb = x.view(nb, BLOCK)
    absmax = xb.abs().amax(-1)                                  # the NEW scale of this block
    c = xb / absmax.clamp(min=1e-30).unsqueeze(-1)              # normalised into the map's range
    mid = (qmap[:-1] + qmap[1:]) * 0.5                          # 255 midpoints, ascending
    code = torch.bucketize(c, mid)                              # index of the nearest map entry
    return (qmap[code] * absmax.unsqueeze(-1)).reshape(-1), absmax


def quantized_adamw_step(params, grads, m_code, m_absmax, v_code, v_absmax, qmap1, qmap2, step,
                         lr=1e-3, beta1=0.9, beta2=0.999, eps=1e-8, wd=0.01):
    """8-bit blockwise AdamW, in fp32.

    Correct and simple — it is the numerical SPECIFICATION, not a performance target. Every line
    materialises another full-size fp32 temporary in HBM.
    """
    m = qmap1[m_code.long()] * m_absmax.repeat_interleave(BLOCK)     # dequantise the first moment
    v = qmap2[v_code.long()] * v_absmax.repeat_interleave(BLOCK)     # dequantise the second moment
    g = grads.float()

    m_new = beta1 * m + (1.0 - beta1) * g
    v_new = beta2 * v + (1.0 - beta2) * g * g

    bc1 = 1.0 - beta1 ** step
    bc2 = 1.0 - beta2 ** step
    denom = (v_new / bc2).sqrt() + eps
    upd = (lr / bc1) * m_new / denom
    p_out = params.float() * (1.0 - lr * wd) - upd                   # DECOUPLED weight decay

    m_out, m_absmax_out = _requantise(m_new, qmap1)                  # the state that gets stored back
    v_out, v_absmax_out = _requantise(v_new, qmap2)
    return p_out.to(torch.bfloat16), m_out, v_out, m_absmax_out, v_absmax_out