File size: 16,977 Bytes
6b665d1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
"""Post-training 4-bit quantization check for the deploy models.

The last sim-side unknown: everything trained so far is fp32, but the chip stores
weights in 4-bit. Does PLE's +9.3% edge survive naive group-wise PTQ, or does it
need QAT? We quantize -> dequantize every large weight (group-wise symmetric int4,
the GGUF-Q4 style you'd actually flash) and re-measure val loss.

Crucially this quantizes the 25M-param TABLE too -- the thing we're betting the
flash budget on. If the table is the fragile part under 4-bit, we need to know.

Norms stay fp32 (tiny, and quantizing them is never worth it).
"""

import argparse
import glob
import json
import math
import os

import numpy as np
import torch
import torch.nn as nn

from model import Config, TinyLM

HERE = os.path.dirname(os.path.abspath(__file__))
DATA = os.path.join(HERE, "..", "data")
RUNS = os.path.join(HERE, "..", "runs")


# This is a deployment-format oracle as well as a training primitive. Inductor
# may fuse away the explicit fp16 scale round-trip (and one observed Triton
# fusion generated invalid code), so QAT must cross an eager graph boundary.
@torch.compiler.disable
def quantize_groupwise(w, bits=4, group=64, fp16_scales=False):
    """Symmetric group-wise quant along the last dim; returns dequantized fp32.

    Simulates storage in `bits` with one fp scale per `group` consecutive weights
    of each row -- the standard edge format. qmax = 2^(bits-1)-1.
    """
    orig_shape = w.shape
    x = w.reshape(-1, orig_shape[-1]).float()
    out, cols = x.shape
    pad = (group - cols % group) % group
    if pad:
        x = torch.cat([x, torch.zeros(out, pad, device=x.device)], dim=1)
    x = x.reshape(out, -1, group)  # (out, n_groups, group)
    qmax = 2 ** (bits - 1) - 1  # 7 for 4-bit
    scale = x.abs().amax(dim=2, keepdim=True) / qmax
    if fp16_scales:
        # Match the flash artifact: round stored group scales to IEEE fp16
        # before quantizing and dequantizing the weights.
        scale = scale.half().float()
    # Match the backend packer: a zero (or fp16-underflowed) stored scale uses
    # 1 only for code selection, then multiplies those codes by the real zero
    # scale. This makes an all-zero group exactly zero instead of NaN.
    safe = torch.where(scale > 0, scale, torch.ones_like(scale))
    q = torch.clamp(torch.round(x / safe), -qmax, qmax)
    dq = (q * scale).reshape(out, -1)[:, :cols]
    return dq.reshape(orig_shape).to(w.dtype)


@torch.compiler.disable
def quantize_ternary_tensorwise(w, eps=1e-5):
    """BitNet-style {-1, 0, +1} fake quantization for one weight tensor.

    This intentionally does *not* route through ``quantize_groupwise(bits=1)``:
    that symmetric integer formula has qmax=0 at one bit and is undefined.
    TorchAO's BitNet training path instead uses one FP32 abs-mean scale for the
    complete Linear weight, rounds ``w / scale`` and clips the codes to
    ``[-1, 1]``.  Keep that definition here so model experiments and a future
    ESP32 packed-ternary format share one explicit oracle.

    The returned tensor is dequantized, as with ``quantize_groupwise``.  A
    zero tensor retains scale zero and therefore returns exact zeros; ``eps``
    protects only the division.
    """
    latent = w.float()
    scale = latent.abs().mean()
    safe = scale.clamp_min(eps)
    codes = torch.round(latent / safe).clamp(-1, 1)
    return (codes * scale).to(w.dtype)


def is_sparse_deployment_weight(model, name, weight):
    """Whether one matrix is row-gathered rather than streamed every token.

    A tied TinyLM token embedding is also the output head, so it must retain the
    dense/head format. Glimmer and fatembed use untied token tables and can store
    those sparse rows at a different width.
    """
    return ("ple_table" in name
            or "position_control" in name
            or ("tok_emb" in name and id(weight) != id(model.head.weight)))


def resolve_quantization_format(metadata=None, *, bits=None, table_bits=None,
                                group=None, skip_names=None, core_format=None,
                                ternary_includes=None):
    """Merge CLI overrides with the format recorded in a checkpoint.

    Selective ternary is part of the deployed format, not merely a training
    option.  Evaluating its latent checkpoint as ordinary i4 silently measures
    a different model, so every metadata-aware evaluator routes through this
    resolver. ``None`` means inherit; an explicit empty iterable clears a
    recorded selector and therefore requests all-core ternary.
    """
    metadata = metadata or {}
    selected_core = (core_format if core_format is not None
                     else metadata.get("core_format", "groupwise"))
    if selected_core not in ("groupwise", "ternary"):
        raise ValueError(f"unknown checkpoint core format {selected_core!r}")

    includes = (ternary_includes if ternary_includes is not None
                else metadata.get("ternary_include", ()))
    if isinstance(includes, str):
        includes = [value.strip() for value in includes.split(",")
                    if value.strip()]
    else:
        includes = [str(value).strip() for value in includes
                    if str(value).strip()]
    if includes and selected_core != "ternary":
        raise ValueError("ternary selectors require core_format='ternary'")

    skips = (skip_names if skip_names is not None
             else metadata.get("skip", ()))
    if isinstance(skips, str):
        skips = [value.strip() for value in skips.split(",") if value.strip()]
    else:
        skips = [str(value).strip() for value in skips if str(value).strip()]
    return {
        "dense_bits": bits if bits is not None else metadata.get("dense_bits", 0),
        "table_bits": (table_bits if table_bits is not None
                       else metadata.get("table_bits")),
        "group": group if group is not None else metadata.get("group", 128),
        "skip": skips,
        "core_format": selected_core,
        "ternary_include": includes,
    }


def quantize_model(model, bits=4, group=64, quant_table=True, fp16_scales=False,
                   skip_names=(), table_bits=None, core_format="groupwise",
                   ternary_includes=()):
    if core_format not in ("groupwise", "ternary"):
        raise ValueError("core_format must be 'groupwise' or 'ternary'")
    head_id = id(model.head.weight)
    n_q = 0
    with torch.no_grad():
        for name, p in model.named_parameters():
            if p.ndim < 2:
                continue  # norms, biases -> leave fp32
            # Mamba scan internals ship fp32 like norms (~4K params), matching
            # train.py's QAT skip exactly -- A_log is a 2-D raw Parameter and the
            # depthwise conv weight is 3-D, so both would otherwise slip in here
            # and quantize what training never fake-quantised.
            if "A_log" in name or "conv1d" in name:
                continue
            # Mirror of train.py's --qat-skip: tensors shipping at higher
            # precision must be excluded here too, or the eval prices a format
            # the arm never trained for.
            if any(s in name for s in skip_names):
                continue
            if "table" in name and not quant_table:
                continue
            sparse = is_sparse_deployment_weight(model, name, p)
            # Canonical BitNet applies ternary quantization to Linear weights,
            # while this project's tied embedding/head must remain one shared
            # higher-precision tensor.  Therefore only true dense CORE weights
            # take the ternary path; the head and sparse tables keep the exact
            # group-wise format already deployed by the backend.
            ternary = (core_format == "ternary" and not sparse
                       and id(p) != head_id
                       and (not ternary_includes
                            or any(value in name
                                   for value in ternary_includes)))
            if ternary:
                p.copy_(quantize_ternary_tensorwise(p.data))
            else:
                use_bits = table_bits if sparse and table_bits is not None else bits
                p.copy_(quantize_groupwise(
                    p.data, use_bits, group, fp16_scales))
            n_q += p.numel()
    return n_q


def load(path, device):
    ck = torch.load(path, map_location=device, weights_only=False)
    m = TinyLM(Config(**ck["cfg"])).to(device)
    m.load_state_dict(ck["state"])
    m.eval()
    return m


@torch.no_grad()
def val_loss(model, vocab, device, iters=60, bs=16, sl=256, seed=1234):
    suffix = "" if vocab == 4096 else f"_v{vocab}"
    data = np.memmap(os.path.join(DATA, f"val{suffix}.bin"), dtype=np.uint16, mode="r")
    rng = np.random.default_rng(seed)
    losses = []
    for _ in range(iters):
        ix = rng.integers(0, len(data) - sl - 1, bs)
        x = torch.from_numpy(np.stack([data[i:i+sl] for i in ix]).astype(np.int64)).to(device)
        y = torch.from_numpy(np.stack([data[i+1:i+1+sl] for i in ix]).astype(np.int64)).to(device)
        losses.append(model(x, y)[1].item())
    return sum(losses) / len(losses)


def get_device():
    if torch.backends.mps.is_available():
        return "mps"
    if torch.cuda.is_available():
        return "cuda"
    return "cpu"


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--bits", type=int, default=4)
    ap.add_argument("--core-format", choices=("groupwise", "ternary"),
                    default="groupwise",
                    help="ternary applies tensor-absmean {-1,0,+1} only to "
                         "core weights; head/tables retain --bits")
    ap.add_argument("--ternary-include", default="",
                    help="optional comma-separated parameter-name substrings; "
                         "unmatched core weights retain --bits")
    ap.add_argument("--group", type=int, default=64)
    ap.add_argument("--tag", default="cleandeploy")
    ap.add_argument("--seed", type=int, default=0)
    ap.add_argument("--fp16-scales", action="store_true",
                    help="round quantization scales to fp16 like the flash format")
    ap.add_argument("--skip", default="",
                    help='name substrings left fp32, mirroring train.py --qat-skip')
    ap.add_argument("--run", nargs="*", default=None,
                    help="checkpoint paths; bypass the historical arm/tag lookup")
    ap.add_argument("--eval-iters", type=int, default=60)
    ap.add_argument("--batch-size", type=int, default=16)
    ap.add_argument("--dynamic-qk", action="store_true",
                    help="also simulate the backend's per-vector int8 Glimmer Q@K")
    ap.add_argument("--table-bits", type=int, choices=(4, 8), default=None,
                    help="quantize sparse untied embeddings/PLE tables separately")
    ap.add_argument("--no-softcap", action="store_true",
                    help="also ablate Glimmer's final tanh softcap")
    args = ap.parse_args()
    if args.ternary_include and args.core_format != "ternary":
        ap.error("--ternary-include requires --core-format ternary")
    device = get_device()
    if args.dynamic_qk and device == "cuda":
        # dynamic_i8_qk uses fp32 GEMM on integer-valued codes. With TF32 the
        # accumulation is no longer the backend's exact int32 dot product.
        torch.set_float32_matmul_precision("highest")

    if args.run:
        meta_path = os.path.join(DATA, "sweep_meta.json")
        if os.path.exists(meta_path):
            with open(meta_path) as f:
                meta = json.load(f)
        else:
            meta = {}
        for path in args.run:
            ck = torch.load(path, map_location="cpu", weights_only=False)
            cfg = Config(**ck["cfg"])
            sl = cfg.seq_len
            m = load(path, device)
            fp = val_loss(m, cfg.vocab_size, device, args.eval_iters,
                          args.batch_size, sl)
            m = load(path, device)
            nq = quantize_model(
                m, args.bits, args.group, quant_table=True,
                fp16_scales=args.fp16_scales,
                skip_names=[s for s in args.skip.split(",") if s.strip()],
                table_bits=args.table_bits,
                core_format=args.core_format,
                ternary_includes=[
                    s for s in args.ternary_include.split(",") if s.strip()])
            q = val_loss(m, cfg.vocab_size, device, args.eval_iters,
                         args.batch_size, sl)
            q_dyn = None
            if args.dynamic_qk and cfg.architecture == "glimmer":
                m.cfg.dynamic_qk = True
                q_dyn = val_loss(m, cfg.vocab_size, device, args.eval_iters,
                                 args.batch_size, sl)
            q_nocap = q_both = None
            if args.no_softcap and cfg.architecture == "glimmer":
                m.cfg.dynamic_qk = False
                m.cfg.final_logit_softcapping = 0.0
                q_nocap = val_loss(m, cfg.vocab_size, device, args.eval_iters,
                                   args.batch_size, sl)
                if args.dynamic_qk:
                    m.cfg.dynamic_qk = True
                    q_both = val_loss(m, cfg.vocab_size, device,
                                      args.eval_iters, args.batch_size, sl)
            bits_token = q / math.log(2)
            bytes_token = meta.get(str(cfg.vocab_size), {}).get("val_bpt")
            bits_byte = bits_token / bytes_token if bytes_token else float("nan")
            dyn = ""
            if q_dyn is not None:
                dyn_bpt = q_dyn / math.log(2)
                dyn_bpb = dyn_bpt / bytes_token if bytes_token else float("nan")
                dyn = (f" q+dynqk={q_dyn:.4f} qk_deg={q_dyn-q:+.4f}"
                       f" dyn_bits/token={dyn_bpt:.4f}"
                       f" dyn_bits/byte={dyn_bpb:.4f}")
            nocap = ""
            if q_nocap is not None:
                nc_bpb = ((q_nocap / math.log(2)) / bytes_token
                          if bytes_token else float("nan"))
                nocap = (f" q+nosoft={q_nocap:.4f} soft_deg={q_nocap-q:+.4f}"
                         f" nosoft_bits/byte={nc_bpb:.4f}")
            both = ""
            if q_both is not None:
                both_bpb = ((q_both / math.log(2)) / bytes_token
                            if bytes_token else float("nan"))
                both = (f" q+dyn+nosoft={q_both:.4f}"
                        f" both_deg={q_both-q:+.4f}"
                        f" both_bits/byte={both_bpb:.4f}")
            ternary_label = ""
            if args.core_format == "ternary":
                ternary_label = (f"ternary[{args.ternary_include}]-core/"
                                  if args.ternary_include
                                  else "ternary-core/")
            form = (ternary_label
                    + (f"i{args.bits}"
                    if args.table_bits is None
                    else f"i{args.bits}/table-i{args.table_bits}"))
            print(f"{os.path.basename(path):32s} fp={fp:.4f} q={q:.4f}{dyn} "
                  f"{nocap}{both} format={form} deg={q-fp:+.4f} "
                  f"bits/token={bits_token:.4f} "
                  f"bits/byte={bits_byte:.4f} quantized={nq/1e6:.2f}M")
        return

    rows = {}
    for arm in ["baseline", "ple", "fatembed"]:
        path = os.path.join(RUNS, f"{arm}-{args.tag}-s{args.seed}.pt")
        if not os.path.exists(path):
            continue
        cfg_vocab = torch.load(path, map_location="cpu", weights_only=False)["cfg"]["vocab_size"]

        m = load(path, device)
        fp = val_loss(m, cfg_vocab, device)

        m = load(path, device)  # fresh copy
        nq = quantize_model(m, args.bits, args.group, quant_table=True,
                            fp16_scales=args.fp16_scales,
                            skip_names=[s for s in args.skip.split(",") if s.strip()],
                            core_format=args.core_format,
                            ternary_includes=[
                                s for s in args.ternary_include.split(",")
                                if s.strip()])
        q = val_loss(m, cfg_vocab, device)

        rows[arm] = (fp, q, nq)
        print(f"{arm:9s} fp32 val {fp:.4f} (ppl {math.exp(fp):.2f}) | "
              f"{args.bits}-bit val {q:.4f} (ppl {math.exp(q):.2f}) | "
              f"deg {q-fp:+.4f} | quantized {nq/1e6:.1f}M params")

    if "baseline" in rows and "ple" in rows:
        print(f"\n--- does PLE's edge survive {args.bits}-bit? ---")
        fp_gap = rows["baseline"][0] - rows["ple"][0]
        q_gap = rows["baseline"][1] - rows["ple"][1]
        print(f"  PLE vs baseline, fp32   : {fp_gap:+.4f} nats")
        print(f"  PLE vs baseline, {args.bits}-bit  : {q_gap:+.4f} nats")
        print(f"  edge retained           : {100*q_gap/fp_gap:.0f}%")


if __name__ == "__main__":
    main()