Buckets:
| """J4 step 1 (Addendum J, locked e6afa2c1…): what does quantisation do to DECISIONS, per subgroup? | |
| Simulated (fake) quantisation of a trained CountNet, the standard way to measure low-precision numerics without | |
| target kernels: | |
| - weights: symmetric per-output-channel, int8 ("w8") or int4 ("w4"); | |
| - activations: symmetric per-tensor int8 on every Conv2d output ("a8"), ranges calibrated as the 99.99th percentile | |
| of |activation| over the validation images (no test data touched). | |
| Configs: w8a8 (typical edge int8), w4a8, w8 (weights only). For each, test decisions (positive, high density) are | |
| compared with fp32 on the SAME images: flips overall and per device / pseudo-slide group, plus count MAE. | |
| """ | |
| from __future__ import annotations | |
| import copy | |
| import numpy as np | |
| import pandas as pd | |
| import torch | |
| import torch.nn as nn | |
| def _qw(w, bits): | |
| q = 2 ** (bits - 1) - 1 | |
| s = w.abs().flatten(1).amax(1).clamp(min=1e-12) / q | |
| return (torch.round(w / s.view(-1, *[1] * (w.dim() - 1))).clamp(-q, q) * s.view(-1, *[1] * (w.dim() - 1))) | |
| def quantise(model, wbits, abits, calib_batches): | |
| m = copy.deepcopy(model).eval() | |
| with torch.no_grad(): | |
| for mod in m.modules(): | |
| if isinstance(mod, nn.Conv2d) and wbits: | |
| mod.weight.copy_(_qw(mod.weight, wbits)) | |
| if not abits: | |
| return m | |
| convs = [mod for mod in m.modules() if isinstance(mod, nn.Conv2d)] | |
| amax = {id(c): [] for c in convs} | |
| hs = [c.register_forward_hook(lambda mod, i, o: amax[id(mod)].append(torch.quantile(o.detach().abs().flatten().float()[::97], 0.9999).item())) for c in convs] | |
| with torch.no_grad(): | |
| for x in calib_batches: | |
| m(x) | |
| for h in hs: | |
| h.remove() | |
| q = 2 ** (abits - 1) - 1 | |
| scale = {k: max(np.max(v), 1e-8) / q for k, v in amax.items() if v} | |
| def fq(mod, i, o): | |
| s = scale[id(mod)] | |
| return torch.round(o / s).clamp(-q, q) * s | |
| for c in convs: | |
| if id(c) in scale: | |
| c.register_forward_hook(fq) | |
| return m | |
| def flips(base, other, rows, by=("device", "group")): | |
| D = base.merge(other, on="image", suffixes=("", "_q")).merge(rows[["image", *by]], on="image") | |
| out = {"n": len(D)} | |
| for dec in ("pred_pos", "pred_high"): | |
| f = D[dec] != D[dec + "_q"] | |
| out[f"{dec}_flips"] = int(f.sum()) | |
| out[f"{dec}_flips_by_device"] = {k: f"{int(v.sum())}/{len(v)}" for k, v in f.groupby(D.device)} | |
| out["count_mae_vs_fp32"] = float((D.pred_parasite - D.pred_parasite_q).abs().mean()) | |
| return out | |
Xet Storage Details
- Size:
- 2.53 kB
- Xet hash:
- d7267da0d99b3a6224be8940b657a1c1f98b24d337076bcdd6f595c985b4263e
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.