Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / scripts / ml / quant_task_eval.py
quant_task_eval.py291 lines · 11.9 KiBRaw
| 1 | #!/usr/bin/env python3 |
| 2 | """What a quantisation costs each model *at its output*, rather than at its weights. |
| 3 | |
| 4 | `maml_convert.Fidelity` gates on `cosine(fp32 weight, int8 * scale)` per tensor. That is a |
| 5 | screen, and this session established how weak a one: Maia's int4 passed a 0.99 bar at group 16 |
| 6 | and still changed one move in eleven. A cosine says the weights were reproduced; it says |
| 7 | nothing about whether the model still does its job, and the relationship between the two is |
| 8 | steeply nonlinear and different for every architecture. |
| 9 | |
| 10 | So this runs the real graph twice on the same inputs — once as exported, once with every |
| 11 | eligible convolution requantised — and reports the divergence in units the app cares about: |
| 12 | |
| 13 | * **embedding** (`mobilefacenet`): cosine between the two embeddings. This is the number a face |
| 14 | match thresholds on, so a displacement of 0.01 is directly comparable to the ~0.3 threshold |
| 15 | ArcFace-style recognition uses. |
| 16 | * **mask** (`u2netp`, `selfie`): IoU of the thresholded masks, plus the worst per-pixel delta. |
| 17 | A saliency mask that moves a few pixels at the edge is invisible; one that loses a region is |
| 18 | not, and IoU is what tells them apart. |
| 19 | * **dense** (everything else): correlation and worst deviation relative to the output range, |
| 20 | which is what `onnx_parity.py` reports. |
| 21 | |
| 22 | Weights are requantised in place with `maml_convert.quantise_per_channel` (or the grouped |
| 23 | variant), which is the arithmetic the shaders perform, so this measures the shipped scheme and |
| 24 | not an idealisation of it. |
| 25 | |
| 26 | python scripts/ml/quant_task_eval.py --onnx build/onnx/u2netp.onnx --graph u2netp --bits 8 |
| 27 | python scripts/ml/quant_task_eval.py --onnx build/onnx/mobilefacenet.onnx \\ |
| 28 | --graph mobilefacenet --bits 4 --group 32 |
| 29 | """ |
| 30 | |
| 31 | import argparse |
| 32 | import glob |
| 33 | import os |
| 34 | import sys |
| 35 | |
| 36 | import numpy as np |
| 37 | |
| 38 | HERE = os.path.dirname(os.path.abspath(__file__)) |
| 39 | ROOT = os.path.dirname(os.path.dirname(HERE)) |
| 40 | sys.path.insert(0, HERE) |
| 41 | |
| 42 | import maml_convert # noqa: E402 |
| 43 | |
| 44 | # How to judge each graph's output. See the module docstring. |
| 45 | METRICS = { |
| 46 | "mobilefacenet": "embedding", |
| 47 | "u2netp": "mask", |
| 48 | "selfie": "mask", |
| 49 | "scrfd": "dense", |
| 50 | "ppocr_det": "mask", |
| 51 | "ppocr_rec": "dense", |
| 52 | } |
| 53 | |
| 54 | # The input each graph wants, as `[channels, height, width]`. |
| 55 | SHAPES = { |
| 56 | "mobilefacenet": (3, 112, 112), |
| 57 | "u2netp": (3, 320, 320), |
| 58 | "selfie": (3, 256, 256), |
| 59 | "scrfd": (3, 640, 640), |
| 60 | "ppocr_det": (3, 640, 640), |
| 61 | "ppocr_rec": (3, 48, 320), |
| 62 | } |
| 63 | |
| 64 | # `(mean, std, bgr)` per graph, transcribed from `library/ml/.../preprocess.rs`. Feeding a |
| 65 | # model the wrong normalisation puts it off its training distribution, which shows up as |
| 66 | # quantisation sensitivity that is really just a preprocessing bug. |
| 67 | NORMALISE = { |
| 68 | "mobilefacenet": ((0.5, 0.5, 0.5), (0.5, 0.5, 0.5), False), |
| 69 | "u2netp": ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225), False), |
| 70 | "selfie": ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0), False), |
| 71 | "scrfd": ((0.5, 0.5, 0.5), (128 / 255, 128 / 255, 128 / 255), False), |
| 72 | "ppocr_det": ((0.485, 0.456, 0.406), (0.229, 0.224, 0.225), True), |
| 73 | "ppocr_rec": ((0.5, 0.5, 0.5), (0.5, 0.5, 0.5), True), |
| 74 | } |
| 75 | |
| 76 | # Real photographs already in the tree, from `:camera`'s Rust tests. Natural images matter |
| 77 | # here: on random noise a saliency mask is empty and a detector fires nowhere, which makes IoU |
| 78 | # and box metrics degenerate rather than merely noisy. See the `--images` flag. |
| 79 | PHOTOS = "camera/src/main/rust/testdata" |
| 80 | |
| 81 | |
| 82 | def photo_feeds(graph, count): |
| 83 | """`count` real photographs, resized and normalised the way the app feeds this graph.""" |
| 84 | from PIL import Image |
| 85 | |
| 86 | channels, height, width = SHAPES[graph] |
| 87 | mean, std, bgr = NORMALISE[graph] |
| 88 | found = sorted(glob.glob(os.path.join(ROOT, PHOTOS, "*.jpg"))) |
| 89 | if not found: |
| 90 | raise SystemExit(f"no photographs in {PHOTOS}") |
| 91 | feeds = [] |
| 92 | for path in found[:count]: |
| 93 | image = Image.open(path).convert("RGB").resize((width, height), Image.BILINEAR) |
| 94 | pixels = np.asarray(image, dtype=np.float32) / 255.0 |
| 95 | if bgr: |
| 96 | pixels = pixels[:, :, ::-1] |
| 97 | pixels = (pixels - np.array(mean, np.float32)) / np.array(std, np.float32) |
| 98 | feeds.append( |
| 99 | np.ascontiguousarray(pixels.transpose(2, 0, 1)[None], dtype=np.float32) |
| 100 | ) |
| 101 | return feeds |
| 102 | |
| 103 | |
| 104 | def requantise(weight, bits, group): |
| 105 | """`weight` through a round trip of the scheme the shaders read.""" |
| 106 | if bits == 8 and not group: |
| 107 | kernel, scale = maml_convert.quantise_per_channel(weight) |
| 108 | return (kernel.astype(np.float32).reshape(weight.shape[0], -1) * scale[:, None]).reshape( |
| 109 | weight.shape |
| 110 | ) |
| 111 | limit = float(2 ** (bits - 1) - 1) |
| 112 | rows = np.ascontiguousarray(weight, np.float32).reshape(weight.shape[0], -1) |
| 113 | width = rows.shape[1] |
| 114 | span = width if not group else min(group, width) |
| 115 | out = np.empty_like(rows) |
| 116 | for start in range(0, width, span): |
| 117 | block = rows[:, start:start + span] |
| 118 | absmax = np.abs(block).max(axis=1) |
| 119 | scale = np.where(absmax > 0, absmax / limit, 1.0).astype(np.float32) |
| 120 | codes = np.clip( |
| 121 | np.floor(np.abs(block) / scale[:, None] + 0.5) * np.sign(block), -limit, limit |
| 122 | ) |
| 123 | out[:, start:start + span] = codes * scale.astype(np.float16).astype(np.float32)[:, None] |
| 124 | return out.reshape(weight.shape) |
| 125 | |
| 126 | |
| 127 | def quantised_model(path, bits, group): |
| 128 | """A copy of the ONNX at `path` with every eligible convolution requantised.""" |
| 129 | import onnx |
| 130 | from onnx import numpy_helper |
| 131 | |
| 132 | model = onnx.load(path) |
| 133 | inits = {i.name: i for i in model.graph.initializer} |
| 134 | consumers = {} |
| 135 | for node in model.graph.node: |
| 136 | for name in node.input: |
| 137 | consumers.setdefault(name, []).append(node) |
| 138 | |
| 139 | touched = 0 |
| 140 | worst = 1.0 |
| 141 | for node in model.graph.node: |
| 142 | if not maml_convert.int8_eligible(node, consumers): |
| 143 | continue |
| 144 | name = node.input[1] |
| 145 | if name not in inits: |
| 146 | continue |
| 147 | weight = numpy_helper.to_array(inits[name]).astype(np.float32) |
| 148 | if weight.ndim < 2: |
| 149 | continue |
| 150 | low = requantise(weight, bits, group) |
| 151 | flat, back = weight.ravel(), low.ravel() |
| 152 | cosine = float( |
| 153 | np.dot(flat, back) / max(np.linalg.norm(flat) * np.linalg.norm(back), 1e-30) |
| 154 | ) |
| 155 | worst = min(worst, cosine) |
| 156 | inits[name].CopyFrom(numpy_helper.from_array(low, name)) |
| 157 | touched += 1 |
| 158 | return model, touched, worst |
| 159 | |
| 160 | |
| 161 | def run(model, feeds): |
| 162 | import onnxruntime as ort |
| 163 | |
| 164 | session = ort.InferenceSession( |
| 165 | model.SerializeToString(), providers=["CPUExecutionProvider"] |
| 166 | ) |
| 167 | name = session.get_inputs()[0].name |
| 168 | return [session.run(None, {name: f})[0] for f in feeds] |
| 169 | |
| 170 | |
| 171 | def report(kind, reference, low): |
| 172 | """The divergence between two runs, in the units `kind` calls for.""" |
| 173 | if kind == "embedding": |
| 174 | worst = 1.0 |
| 175 | for a, b in zip(reference, low): |
| 176 | a, b = a.ravel(), b.ravel() |
| 177 | worst = min( |
| 178 | worst, |
| 179 | float(np.dot(a, b) / max(np.linalg.norm(a) * np.linalg.norm(b), 1e-30)), |
| 180 | ) |
| 181 | print(f" embedding cosine against fp32: worst {worst:.6f}") |
| 182 | print( |
| 183 | " a face match thresholds near 0.3, so displacement here is the whole budget: " |
| 184 | f"{1 - worst:.6f} used" |
| 185 | ) |
| 186 | return worst |
| 187 | if kind == "mask": |
| 188 | worst_iou = 1.0 |
| 189 | worst_delta = 0.0 |
| 190 | degenerate = 0 |
| 191 | for a, b in zip(reference, low): |
| 192 | pa, pb = a.ravel() > 0.5, b.ravel() > 0.5 |
| 193 | # A mask that is essentially all-background or all-foreground makes IoU a coin |
| 194 | # flip: an empty reference against a handful of stray positives scores 0, and two |
| 195 | # near-empty masks score 1, neither of which says anything about the model. Random |
| 196 | # inputs produce exactly that, so it is counted and reported rather than averaged in. |
| 197 | coverage = pa.mean() |
| 198 | if coverage < 0.001 or coverage > 0.999: |
| 199 | degenerate += 1 |
| 200 | continue |
| 201 | union = np.logical_or(pa, pb).sum() |
| 202 | iou = 1.0 if union == 0 else float(np.logical_and(pa, pb).sum() / union) |
| 203 | worst_iou = min(worst_iou, iou) |
| 204 | worst_delta = max(worst_delta, float(np.abs(a - b).max())) |
| 205 | if degenerate: |
| 206 | # IoU is unusable, but the raw saliency map still is: correlation and mean error |
| 207 | # over the probabilities say how far the map moved without depending on a |
| 208 | # threshold that happens to sit in an empty region. |
| 209 | flat_a = np.concatenate([a.ravel() for a in reference]).astype(np.float64) |
| 210 | flat_b = np.concatenate([b.ravel() for b in low]).astype(np.float64) |
| 211 | correlation = float(np.corrcoef(flat_a, flat_b)[0, 1]) |
| 212 | mae = float(np.abs(flat_a - flat_b).mean()) |
| 213 | print( |
| 214 | f" mask IoU: unusable — {degenerate}/{len(reference)} reference masks are " |
| 215 | "degenerate (no clear subject in these photos)" |
| 216 | ) |
| 217 | print( |
| 218 | f" saliency map instead: correlation {correlation:.6f} " |
| 219 | f"mean abs error {mae:.5f} worst pixel " |
| 220 | f"{max(float(np.abs(a - b).max()) for a, b in zip(reference, low)):.4f}" |
| 221 | ) |
| 222 | return correlation |
| 223 | print(f" mask IoU at 0.5: worst {worst_iou:.6f} worst pixel delta {worst_delta:.4f}") |
| 224 | return worst_iou |
| 225 | worst_corr = 1.0 |
| 226 | worst_rel = 0.0 |
| 227 | for a, b in zip(reference, low): |
| 228 | a, b = a.ravel().astype(np.float64), b.ravel().astype(np.float64) |
| 229 | spread = a.max() - a.min() |
| 230 | worst_corr = min(worst_corr, float(np.corrcoef(a, b)[0, 1])) |
| 231 | worst_rel = max(worst_rel, float(np.abs(a - b).max() / max(spread, 1e-9))) |
| 232 | print(f" output correlation: worst {worst_corr:.6f} worst deviation {worst_rel * 100:.3f}%") |
| 233 | return worst_corr |
| 234 | |
| 235 | |
| 236 | def main(): |
| 237 | parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) |
| 238 | parser.add_argument("--onnx", required=True) |
| 239 | parser.add_argument("--graph", required=True, choices=sorted(SHAPES)) |
| 240 | parser.add_argument("--bits", type=int, default=8, choices=[4, 5, 6, 8]) |
| 241 | parser.add_argument("--group", type=int, default=0) |
| 242 | parser.add_argument("--inputs", type=int, default=8) |
| 243 | parser.add_argument("--seed", type=int, default=5) |
| 244 | parser.add_argument( |
| 245 | "--noise", |
| 246 | action="store_true", |
| 247 | help="use random inputs instead of the real photographs in camera's testdata", |
| 248 | ) |
| 249 | args = parser.parse_args() |
| 250 | |
| 251 | try: |
| 252 | import onnx # noqa: F401 |
| 253 | import onnxruntime # noqa: F401 |
| 254 | except ImportError as missing: |
| 255 | raise SystemExit(f"needs onnx and onnxruntime: {missing}") |
| 256 | |
| 257 | if args.noise: |
| 258 | # Random inputs. Sound for a *relative* comparison of two weightings of the same graph |
| 259 | # — both sides see identical bytes — but a saliency mask or a detection map is |
| 260 | # degenerate on noise, so the mask metric will refuse to report. Kept for the dense |
| 261 | # graphs and for reproducing the earlier measurements. |
| 262 | rng = np.random.default_rng(args.seed) |
| 263 | channels, height, width = SHAPES[args.graph] |
| 264 | feeds = [ |
| 265 | rng.standard_normal((1, channels, height, width)).astype(np.float32) |
| 266 | for _ in range(args.inputs) |
| 267 | ] |
| 268 | source = "random noise" |
| 269 | else: |
| 270 | feeds = photo_feeds(args.graph, args.inputs) |
| 271 | source = f"{len(feeds)} real photographs from {PHOTOS}" |
| 272 | |
| 273 | import onnx |
| 274 | |
| 275 | reference_model = onnx.load(args.onnx) |
| 276 | low_model, touched, worst_weight = quantised_model(args.onnx, args.bits, args.group) |
| 277 | grouping = "per output channel" if not args.group else f"per {args.group} weights" |
| 278 | print( |
| 279 | f"{args.graph}: int{args.bits}, {grouping}, {touched} convolutions requantised, " |
| 280 | f"worst weight cosine {worst_weight:.6f}" |
| 281 | ) |
| 282 | print(f" input: {source}") |
| 283 | |
| 284 | reference = run(reference_model, feeds) |
| 285 | low = run(low_model, feeds) |
| 286 | report(METRICS[args.graph], reference, low) |
| 287 | return 0 |
| 288 | |
| 289 | |
| 290 | if __name__ == "__main__": |
| 291 | raise SystemExit(main()) |