Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / ml / src / main / rust / shaders / quantize.comp

quantize.comp35 lines · 1.6 KiBRaw
1#version 450
2//! `clamp(round(x / scale), -128, 127) * scale`, S10's per-tensor int8 round-trip.
3//!
4//! # Why an op and not a fold
5//!
6//! The live model quantizes the attention mixture (`Mm`) to int8 at a per-layer
7//! scale (the `attn_vec_einsum/composite` tensor: layer 0's is 0.03026575781404972)
8//! before the O projection consumes it. Without this the device runs the O-tail at
9//! full precision while the reference rounds to 1/128 steps, and the two diverge
10//! past any cosine gate (fp `Mm` vs live: 0.67; round-tripped: 0.97865 at L0).
11//! Rounding is not a scale and cannot fold into either neighbouring convolution.
12//!
13//! # Why the scale is a push constant
14//!
15//! One float per owning layer, fixed by the S10 bundle (see `MM_SCALE` in
16//! `nets::gemma4`). Like `softcap`'s cap it rides `p.param0_bits` as raw f32 bits
17//! rather than a weight tensor: no file-format change, no re-push of the 1 GB text
18//! model. The parity harness guards drift — a bundle change fails it loudly.
19//!
20//! # Push fields
21//!
22//! `p.in0` is the input, `p.out_at` the output, `p.param0_bits` the scale as raw
23//! f32 bits, and `p.count` the element count. Shapes are irrelevant: elementwise.
24//! Ties round half up (`floor(x + 0.5)`); live ties are measure-zero either way.
25#include "common.glsl"
26void main() {
27 uint index = global_index();
28 if (index >= p.count) {
29 return;
30 }
31 float scale = uintBitsToFloat(p.param0_bits);
32 float q = floor(float(arena[p.in0 + index]) / scale + 0.5);
33 q = clamp(q, -128.0, 127.0);
34 arena[p.out_at + index] = float16_t(q * scale);
35}