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

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

quantize_blocks.comp56 lines · 2.4 KiBRaw
1#version 450
2//! Block-quantises a channel-major fp16 activation `(in_c, positions)` to int8 for
3//! `conv_point_int4_dot.comp`: one scale per position per 32-channel block, matching the int4
4//! weights' `I4_BLOCK`.
5//!
6//! # Layout written at `p.out_at` (element offset, a multiple of 8)
7//!
8//! Data, `[block][half][position]`, one 16-byte cell each, so a run of positions is contiguous:
9//! word `2q` of the block (cell `q / 2`, word `2q % 4`) packs channels `8q + 0, 2, 4, 6` and word
10//! `2q + 1` channels `8q + 1, 3, 5, 7`, one signed byte each, low byte first. That is the order a
11//! weight word's nibbles fall into after `<< 4 & 0xF0F0F0F0` and `& 0xF0F0F0F0`. Then, from
12//! element `p.out_at + positions * in_c / 2`, a `[block][position]` table of f32 scales,
13//! `amax / 127 / 16`: the GEMM reads each nibble as a byte 16 times its value.
14//!
15//! # Push fields
16//!
17//! `p.in0` the input, `p.out_at` the output, `p.in_c` channels, `p.out_h * p.out_w` positions,
18//! `p.count` `positions * in_c / 32` invocations.
19#include "common.glsl"
20layout(std430, binding = 0) buffer ArenaWord {
21 uint arena_word[];
22};
23layout(std430, binding = 0) buffer ArenaOct {
24 uvec4 arena_oct[];
25};
26uint pack4(vec4 v, float inv) {
27 ivec4 q = clamp(ivec4(roundEven(v * inv)), ivec4(-127), ivec4(127));
28 return uint(q.x & 255) | (uint(q.y & 255) << 8u) | (uint(q.z & 255) << 16u) | (uint(q.w) << 24u);
29}
30void main() {
31 uint index = global_index();
32 if (index >= p.count) {
33 return;
34 }
35 uint positions = p.out_h * p.out_w;
36 uint position = index % positions;
37 uint block = index / positions;
38 float v[32];
39 float amax = 0.0;
40 uint at = p.in0 + block * I4_BLOCK * positions + position;
41 for (uint t = 0u; t < 32u; t++) {
42 v[t] = float(arena[at + t * positions]);
43 amax = max(amax, abs(v[t]));
44 }
45 float inv = amax > 0.0 ? 127.0 / amax : 0.0;
46 for (uint h = 0u; h < 2u; h++) {
47 uint k = h * 16u;
48 arena_oct[(p.out_at >> 3u) + (block * 2u + h) * positions + position] = uvec4(
49 pack4(vec4(v[k], v[k + 2u], v[k + 4u], v[k + 6u]), inv),
50 pack4(vec4(v[k + 1u], v[k + 3u], v[k + 5u], v[k + 7u]), inv),
51 pack4(vec4(v[k + 8u], v[k + 10u], v[k + 12u], v[k + 14u]), inv),
52 pack4(vec4(v[k + 9u], v[k + 11u], v[k + 13u], v[k + 15u]), inv));
53 }
54 arena_word[((p.out_at + positions * p.in_c / 2u) >> 1u) + index] =
55 floatBitsToUint(amax / 127.0 / 16.0);
56}