com.microsoft.QLinearConv / build /webgpu /quant-dp4a-matmul.wgsl.jinja
Xenova's picture
Xenova HF Staff
sync 4385228f788d
155c41d verified
Raw History Blame
26.6 kB
{% set ownRowSums = false -%}
{% macro quant_read_scalar_zero(fn_name, buffer_name, is_unsigned, present=true) %}
fn {{ fn_name }}() -> i32 {
{% if is_unsigned %}
return i32({{ buffer_name }}[0]);
{% else %}
return {{ buffer_name }}[0];
{% endif %}
}{% endmacro %}
{% macro quant_read_column_zero(fn_name, buffer_name, is_unsigned, present=true, per_column=false, param_name="col", return_type="i32") %}
fn {{ fn_name }}({% if per_column %}{{ param_name }}: u32{% endif %}) -> {{ return_type }} {
{% if per_column %}
{% if is_unsigned %}
return i32({{ buffer_name }}[{{ param_name }}]);
{% else %}
return {{ buffer_name }}[{{ param_name }}];
{% endif %}
{% else %}
{% if is_unsigned %}
return i32({{ buffer_name }}[0]);
{% else %}
return {{ buffer_name }}[0];
{% endif %}
{% endif %}
}{% endmacro %}
{% if not env.device.wgslLanguageFeatures.has("packed_4x8_integer_dot_product") %}
// Runtime source-compatible fallbacks for the packed 4x8 integer built-ins used
// by quantized kernels. Native implementations remain unshadowed when the
// language feature is present. The user functions retain the built-ins'
// @must_use contract, but cannot be @const; every call is runtime.
// Inputs are function parameters, so replacing a built-in call with one of
// these same-name functions preserves WGSL's single evaluation of each
// argument. Byte extraction is unsigned. Signed lanes use the exact
// i32(byte ^ 0x80u) - 128i sign extension, avoiding signed-left-shift overflow
// while preserving every 8-bit two's-complement value.
@must_use fn dot4I8Packed(e1: u32, e2: u32) -> i32 {
let shifts = vec4<u32>(0u, 8u, 16u, 24u);
let a_bytes = (vec4<u32>(e1) >> shifts) & vec4<u32>(0xffu);
let b_bytes = (vec4<u32>(e2) >> shifts) & vec4<u32>(0xffu);
let a = vec4<i32>(a_bytes ^ vec4<u32>(0x80u)) - vec4<i32>(128i);
let b = vec4<i32>(b_bytes ^ vec4<u32>(0x80u)) - vec4<i32>(128i);
return dot(a, b);
}
{% endif %}
{{ env.wgsl.resourceDeclarations }}
{% if requant != "none" %}
// Rare-boundary fallback: compute binary64-equivalent scale division
// and accumulator product using integer significands; no f64 feature required.
fn quant_u96_add(a: vec3<u32>, b: vec3<u32>) -> vec3<u32> {
let low = a.x + b.x;
let middle = a.y + b.y;
let with_carry = middle + u32(low < a.x);
return vec3<u32>(low, with_carry, a.z + b.z + u32(middle < a.y) + u32(with_carry < middle));
}
// The low word is the ordinary u32 product. Split at 16 bits so every
// partial product and carry used to construct the high word fits in u32.
fn quant_mul_u32(a: u32, b: u32) -> vec2<u32> {
let a_low = a & 0xffffu;
let a_high = a >> 16u;
let b_low = b & 0xffffu;
let b_high = b >> 16u;
let cross_low = a_high * b_low + ((a_low * b_low) >> 16u);
let cross_high = a_low * b_high + (cross_low & 0xffffu);
let high = a_high * b_high + (cross_low >> 16u) + (cross_high >> 16u);
return vec2<u32>(a * b, high);
}
fn quant_u96_round_shift(value: vec3<u32>, shift: u32) -> vec3<u32> {
if (shift == 0u) { return value; }
if (shift > 96u) { return vec3<u32>(0u); }
let limbs = vec4<u32>(value, 0u);
let word = shift >> 5u;
let bits = shift & 31u;
let middle = limbs[min(word + 1u, 3u)];
let high = limbs[min(word + 2u, 3u)];
var quotient = vec3<u32>(limbs[word], middle, high);
if (bits != 0u) {
quotient = (quotient >> vec3<u32>(bits)) | (vec3<u32>(middle, high, 0u) << vec3<u32>(32u - bits));
}
// The highest discarded bit is the guard. With the guard set, any lower set
// bit rounds up; an exact midpoint rounds to the even quotient.
let guard_word = (shift - 1u) >> 5u;
let guard_bit = 1u << ((shift - 1u) & 31u);
let discarded = limbs[guard_word];
let sticky = (discarded & (guard_bit - 1u)) != 0u ||
(guard_word >= 1u && value.x != 0u) || (guard_word >= 2u && value.y != 0u);
if ((discarded & guard_bit) != 0u && (sticky || (quotient.x & 1u) != 0u)) {
quotient = quant_u96_add(quotient, vec3<u32>(1u, 0u, 0u));
}
return quotient;
}
fn quant_float_significand(bits: u32) -> u32 {
return (bits & 0x7fffffu) | select(0x800000u, 0u, (bits & 0x7f800000u) == 0u);
}
fn quant_float_exponent(bits: u32) -> i32 {
return max(1, i32((bits >> 23u) & 255u)) - 150;
}
fn quant_round_binary64(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
if (acc == 0) { return 0; }
let a_bits = bitcast<u32>(a_s);
let b_bits = bitcast<u32>(b_s);
let y_bits = bitcast<u32>(y_s);
let a = quant_float_significand(a_bits);
let b = quant_float_significand(b_bits);
let denominator = quant_float_significand(y_bits);
if (a == 0u || b == 0u) { return 0; }
// The exact product of two 24-bit significands occupies at most 48 bits.
let p0 = (a & 65535u) * (b & 65535u);
let cross = (a >> 16u) * (b & 65535u) + (b >> 16u) * (a & 65535u);
let product_low = p0 + (cross << 16u);
let product_high = (a >> 16u) * (b >> 16u) + (cross >> 16u) + u32(product_low < p0);
var input_bit = select(31 - i32(countLeadingZeros(product_low)), 63 - i32(countLeadingZeros(product_high)), product_high != 0u);
var remainder = 0u;
var significant_bits = 0u;
var leading_exponent = 0;
var significand = vec2<u32>(0u);
// Long division generates the 53 bits of the binary64 multiplier. The
// remainder fits in 25 bits, including its left shift. At most 24 leading
// zero bits precede the first significant bit.
loop {
var incoming = 0u;
if (input_bit >= 32) { incoming = (product_high >> u32(input_bit - 32)) & 1u; }
else if (input_bit >= 0) { incoming = (product_low >> u32(input_bit)) & 1u; }
remainder = (remainder << 1u) | incoming;
let digit = u32(remainder >= denominator);
if (digit != 0u) { remainder -= denominator; }
if (significant_bits != 0u || digit != 0u) {
if (significant_bits == 0u) { leading_exponent = input_bit; }
significand = vec2<u32>((significand.x << 1u) | digit, (significand.y << 1u) | (significand.x >> 31u));
significant_bits++;
}
input_bit--;
if (significant_bits == 53u) { break; }
}
let twice_remainder = remainder << 1u;
if (twice_remainder > denominator || (twice_remainder == denominator && (significand.x & 1u) != 0u)) {
let low = significand.x + 1u;
significand = vec2<u32>(low, significand.y + u32(low == 0u));
}
let scale_exponent = quant_float_exponent(a_bits) + quant_float_exponent(b_bits) - quant_float_exponent(y_bits) + leading_exponent - 52;
// abs(INT_MIN) is representable as u32. Multiply the rounded multiplier's
// significand by the exact accumulator into three little-endian u32 limbs.
let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
let low_product = quant_mul_u32(significand.x, magnitude);
let high_product = quant_mul_u32(significand.y, magnitude);
let middle = low_product.y + high_product.x;
let product = vec3<u32>(low_product.x, middle, high_product.y + u32(middle < low_product.y));
var product_top = 31 - i32(countLeadingZeros(product.x));
if (product.y != 0u) { product_top = 63 - i32(countLeadingZeros(product.y)); }
if (product.z != 0u) { product_top = 95 - i32(countLeadingZeros(product.z)); }
if (product_top + scale_exponent >= 10) { return select(1024, -1024, acc < 0); }
if (product_top + scale_exponent < -2) { return 0; }
let product_shift = u32(max(0, product_top - 52));
let rounded_product = quant_u96_round_shift(product, product_shift);
let result_exponent = scale_exponent + i32(product_shift);
var rounded = rounded_product;
if (result_exponent < 0) { rounded = quant_u96_round_shift(rounded_product, u32(-result_exponent)); }
else { rounded.x <<= u32(result_exponent); }
return select(i32(rounded.x), -i32(rounded.x), acc < 0);
}
// Requantized results lie in [-1024, 1024]. The expansion helpers return this
// marker at a binary64 boundary instead of resolving it themselves, so a
// round_requantized call carries one binary64 resolver after inlining rather
// than one per boundary exit.
const QUANT_REQUANTIZE_BINARY64: i32 = 0x7fffffff;
// A power-of-two division and an exactly represented <=48-bit product need
// no binary64 boundary resolver. This includes ordinary dyadic quantization.
fn quant_exact_dyadic_product(acc: i32, scale: f32) -> bool {
let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
let significand = quant_float_significand(bitcast<u32>(scale));
let integer_bits = 32u - countLeadingZeros(magnitude) - countTrailingZeros(magnitude);
let scale_bits = 32u - countLeadingZeros(significand) - countTrailingZeros(significand);
return integer_bits + scale_bits <= 48u;
}
fn quant_normal_expansion_range(v: f32) -> bool {
let exponent = (bitcast<u32>(v) >> 23u) & 255u;
// Reserve two binary32 significands plus four carry/error bits above the
// minimum normal exponent, so residual arithmetic avoids FTZ underflow.
return exponent >= (1u + 2u * 24u + 4u) && exponent < 255u;
}
fn round_expansion_ratio(numerator_hi: f32, numerator_lo: f32, denominator: f32, dyadic_scale: f32, dyadic_candidate: bool, acc: i32) -> i32 {
let estimate = numerator_hi / denominator;
// Anything outside this range saturates after adding an 8-bit zero point;
// returning early also keeps floor/i32 conversion away from Inf and overflow.
if (estimate <= -1024.0) { return -1024; }
if (estimate >= 1024.0) { return 1024; }
let lo = floor(estimate);
let hi = lo + 1.0;
let midpoint = lo + 0.5;
let midpoint_hi = fma(midpoint, denominator, 0.0);
if ((bitcast<u32>(midpoint_hi) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
let midpoint_lo = fma(midpoint, denominator, -midpoint_hi);
// The high-word subtraction is exact for these similarly sized products
// (Sterbenz); adding the residual difference therefore preserves its sign
// even when the rounded high words straddle adjacent f32 values.
let midpoint_delta = fma(1.0, numerator_hi - midpoint_hi, numerator_lo - midpoint_lo);
// Resolve ambiguous expansion signs with binary64-equivalent arithmetic.
// Six FMA/product tails and their additions fit within this conservative
// 16*u^2 error envelope (u=2^-24), including binary64 quotient rounding.
if ((bitcast<u32>(midpoint_delta) & 0x7f800000u) == 0x7f800000u) { return QUANT_REQUANTIZE_BINARY64; }
if (abs(midpoint_delta) <= max(abs(numerator_hi), abs(midpoint_hi)) * 0x1p-44) {
if (!dyadic_candidate || !quant_exact_dyadic_product(acc, dyadic_scale)) { return QUANT_REQUANTIZE_BINARY64; }
}
if (midpoint_delta < 0.0) {
return i32(lo);
}
if (midpoint_delta > 0.0) {
return i32(hi);
}
let half_lo = floor(lo * 0.5);
let lo_is_even = lo - half_lo * 2.0 == 0.0;
return i32(select(hi, lo, lo_is_even));
}
// Multiplication by a power of two keeps every i32 bit in binary64. Round the
// exact dyadic value directly, including INT_MIN, half-even ties and saturation.
fn quant_round_power_two(acc: i32, exponent: i32) -> i32 {
let magnitude = select(u32(acc), 0u - u32(acc), acc < 0);
var rounded = 0u;
if (exponent >= 0) {
if (exponent >= 10) { return select(1024, -1024, acc < 0); }
rounded = min(magnitude, 1024u >> u32(exponent)) << u32(exponent);
} else {
let shift = u32(-exponent);
if (shift >= 32u) { return 0; }
let whole = magnitude >> shift;
let remainder = magnitude & ((1u << shift) - 1u);
let half = 1u << (shift - 1u);
rounded = min(1024u, whole + u32(remainder > half || (remainder == half && (whole & 1u) != 0u)));
}
return select(i32(rounded), -i32(rounded), acc < 0);
}
// Returns QUANT_REQUANTIZE_BINARY64 when only the binary64 resolver is exact.
fn round_requantized_precise(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
if (acc == 0) { return 0; }
let a_bits = bitcast<u32>(a_s);
let b_bits = bitcast<u32>(b_s);
let y_bits = bitcast<u32>(y_s);
if (((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u && min(a_bits, min(b_bits, y_bits)) != 0u && max(a_bits, max(b_bits, y_bits)) < 0x7f800000u) {
let exponent = i32(a_bits >> 23u) + i32(b_bits >> 23u) - i32(y_bits >> 23u) - 127;
return quant_round_power_two(acc, exponent);
}
let acc_f = f32(acc);
// Every i32 high part aligned to 256 is exactly representable in f32.
// Recover the conversion residual without an out-of-range i32(acc_f)
// conversion when INT_MAX rounds up to 2^31.
let acc_tail = fma(-1.0, acc_f - f32(acc & -256), f32(acc & 255));
// Equal b/y scales cancel exactly. Bypass their product and division so a
// rounded intermediate cannot move a near-half value onto the tie.
if (bitcast<u32>(b_s) == bitcast<u32>(y_s)) {
let direct_hi = fma(acc_f, a_s, 0.0);
let direct_lo = fma(acc_tail, a_s, fma(acc_f, a_s, -direct_hi));
if (!quant_normal_expansion_range(direct_hi)) { return QUANT_REQUANTIZE_BINARY64; }
return round_expansion_ratio(direct_hi, direct_lo, 1.0, a_s, true, acc);
}
// Keep the scale product as a two-float expansion. Its FMA residual preserves
// which side of a rounding midpoint a near-half value occupies.
let ab_hi = fma(a_s, b_s, 0.0);
let ab_lo = fma(a_s, b_s, -ab_hi);
if (!quant_normal_expansion_range(ab_hi) || !quant_normal_expansion_range(y_s) || y_s > 0x1p126) { return QUANT_REQUANTIZE_BINARY64; }
let product_hi = fma(acc_f, ab_hi, 0.0);
if (!quant_normal_expansion_range(product_hi)) { return QUANT_REQUANTIZE_BINARY64; }
let rounded_acc_tail = fma(acc_f, ab_hi, -product_hi) + fma(acc_f, ab_lo, 0.0);
let product_tail = fma(acc_tail, ab_hi, rounded_acc_tail) + fma(acc_tail, ab_lo, 0.0);
// Compare the expansion directly. Renormalizing it adds a cancelling
// subtraction/addition chain that can erase the residual during lowering.
let denominator_bits = bitcast<u32>(y_s);
let denominator_power_two = (denominator_bits & 0x7fffffu) == 0u;
let dyadic_candidate = denominator_power_two && ab_lo == 0.0;
return round_expansion_ratio(product_hi, product_tail, y_s, ab_hi, dyadic_candidate, acc);
}
// A conservative binary32 error filter accepts only a result safely inside one
// integer rounding bin. Ambiguous boundaries keep the full expansion/binary64
// path; this is an exact-result shortcut, not an approximate quantization mode.
fn round_requantized(acc: i32, a_s: f32, b_s: f32, y_s: f32) -> i32 {
if (acc == 0) { return 0; }
let a_bits = bitcast<u32>(a_s);
let b_bits = bitcast<u32>(b_s);
let y_bits = bitcast<u32>(y_s);
let ea = (a_bits >> 23u) & 255u;
let eb = (b_bits >> 23u) & 255u;
let ey = (y_bits >> 23u) & 255u;
// Certify the range before arithmetic: overflow need not produce infinity.
// Any nonzero i32 converts to a float with biased exponent <=158. These
// scale-only bounds cover every accumulator and can be shared across lanes.
// Reserve two significands plus carry bits above FTZ, and a factor of two
// below overflow for products, division and the expansion midpoint product.
// Every exit that needs the binary64 resolver falls through to its one call.
if (!(((a_bits | b_bits | y_bits) & 0x80000000u) != 0u ||
min(ea, eb) == 0u || max(ea, eb) >= 255u ||
ea + eb < 180u || ea + eb > 347u ||
ey < 53u || ey > 242u || ea + eb > ey + 220u)) {
let scale = fma(a_s, b_s, 0.0);
let product = fma(f32(acc), scale, 0.0);
let estimate = product / y_s;
if (estimate <= -1024.0) { return -1024; }
if (estimate >= 1024.0) { return 1024; }
let nearest = round(estimate);
// 32 binary32 unit roundoffs reserve room for the i32 conversion, two
// products, quotient, and distance arithmetic, plus binary64 rounding.
let margin = max(1.0, abs(estimate)) * 0x1p-19;
if (abs(estimate - nearest) < 0.5 - margin) { return i32(nearest); }
var use_expansion = true;
{% if device.adapterInfo.vendor != "apple" %}
// The conversion, two products and division can put the estimate several
// ulps across a midpoint. Allow eight unit roundoffs before relying on
// float residuals. Exact power-of-two ratios retain their integer shortcut.
if (abs(abs(estimate - nearest) - 0.5) <= max(1.0, abs(estimate)) * 0x1p-21) {
let dyadic_scales = ((a_bits | b_bits | y_bits) & 0x807fffffu) == 0u &&
min(a_bits, min(b_bits, y_bits)) != 0u &&
max(a_bits, max(b_bits, y_bits)) < 0x7f800000u;
use_expansion = dyadic_scales;
}
{% endif %}
if (use_expansion) {
let rounded = round_requantized_precise(acc, a_s, b_s, y_s);
if (rounded != QUANT_REQUANTIZE_BINARY64) { return rounded; }
}
}
return quant_round_binary64(acc, a_s, b_s, y_s);
}
{% endif %}
const TILE_M: u32 = {{ tileM }}u;
const TILE_N: u32 = {{ tileN }}u;
const KT_WORDS: u32 = {{ ktWords }}u;
const A_TILE_WORDS: u32 = TILE_M * KT_WORDS;
{% set GEMV_UNROLL = 4 %}
{% if tileM == 1 %}
const GEMV_K_UNROLL: u32 = {{ GEMV_UNROLL }}u;
{% endif %}
{% set needsBSum = true %}
var<workgroup> a_tile: array<u32, A_TILE_WORDS>;
var<workgroup> a_row_sum: array<{{ "i32" if ownRowSums else "atomic<i32>" }}, TILE_M>;
// Pack 4 widened A values into one u32 (byte 0 = lowest k).
fn pack_a(v: vec4<{{ aScalar }}>) -> u32 {
{% if aUnsigned %}
// u8 -> biased i8: (u - 128) two's-complement low byte == u ^ 0x80.
return ((v.x ^ 0x80u) & 0xFFu) | (((v.y ^ 0x80u) & 0xFFu) << 8u) | (((v.z ^ 0x80u) & 0xFFu) << 16u) | (((v.w ^ 0x80u) & 0xFFu) << 24u);
{% else %}
return (u32(v.x) & 0xFFu) | ((u32(v.y) & 0xFFu) << 8u) | ((u32(v.z) & 0xFFu) << 16u) | ((u32(v.w) & 0xFFu) << 24u);
{% endif %}
}
// Sum of the 4 bias-shifted A values of one packed word.
fn sum4_a(v: vec4<{{ aScalar }}>) -> i32 {
{% if aUnsigned %}
return i32(v.x + v.y + v.z + v.w) - 512;
{% else %}
return v.x + v.y + v.z + v.w;
{% endif %}
}
fn pack_b(b0: {{ bScalar }}, b1: {{ bScalar }}, b2: {{ bScalar }}, b3: {{ bScalar }}) -> u32 {
{% if bUnsigned %}
return ((b0 ^ 0x80u) & 0xFFu) | (((b1 ^ 0x80u) & 0xFFu) << 8u) | (((b2 ^ 0x80u) & 0xFFu) << 16u) | (((b3 ^ 0x80u) & 0xFFu) << 24u);
{% else %}
return (u32(b0) & 0xFFu) | ((u32(b1) & 0xFFu) << 8u) | ((u32(b2) & 0xFFu) << 16u) | ((u32(b3) & 0xFFu) << 24u);
{% endif %}
}
// Centralize the signed packed-int8 dot expression so unrolled callers cannot
// collide in lowering-generated temporaries.
fn dot4_packed(a_word: u32, b_word: u32) -> i32 {
return dot4I8Packed(a_word, b_word);
}
fn sum4_b(b0: {{ bScalar }}, b1: {{ bScalar }}, b2: {{ bScalar }}, b3: {{ bScalar }}) -> i32 {
{% if bUnsigned %}
return i32(b0 + b1 + b2 + b3) - 512;
{% else %}
return b0 + b1 + b2 + b3;
{% endif %}
}
{{ quant_read_column_zero("read_a_zero", "a_zero_point", aUnsigned, per_column=aZeroPerRow, param_name="row") }}
{{ quant_read_column_zero("read_b_zero", "b_zero_point", bUnsigned, per_column=bZeroPerColumn) }}
{% if requant != "none" %}
{{ quant_read_scalar_zero("read_y_zero", "y_zero_point", yUnsigned) }}
{% endif %}
@compute @workgroup_size(TILE_N, 1, 1)
fn main(@builtin(workgroup_id) wg: vec3<u32>, @builtin(local_invocation_id) lid: vec3<u32>) {
let batch = wg.z;
let a_base4 = batch * params.aBatchStride4;
let b_base = batch * params.bBatchStride;
let y_base = batch * params.yBatchStride;
let m_block = wg.y * TILE_M;
let n_block = wg.x * TILE_N;
let tid = lid.x;
let col = n_block + tid;
let n_valid = col < params.N;
{% if aPacked == false %}
// Tail variants keep the hot loop on complete words. Packing the one partial
// word afterward prevents its bounds checks from infecting every full-word load.
let k_words_total = params.K / 4u;
let tail_lanes = params.K - k_words_total * 4u;
{% else %}
let k_words_total = params.K / 4u;
{% endif %}
if (tid < TILE_M) {
{{ "a_row_sum[tid] = 0;" if ownRowSums else "atomicStore(&a_row_sum[tid], 0);" }}
}
workgroupBarrier();
{% if tileM == 1 %}
var r0: i32 = 0;
{% for u in range(1, GEMV_UNROLL) %}
var r0_{{ u }}: i32 = 0;
{% endfor %}
{% else %}
{% for m in range(tileM) %}
var r{{ m }}: i32 = 0;
{% endfor %}
{% endif %}
var sum_b: i32 = 0;
{% if tileM == 1 %}
{% for u in range(1, GEMV_UNROLL) %}
var sum_b_{{ u }}: i32 = 0;
{% endfor %}
{% endif %}
for (var kw0 = 0u; kw0 < k_words_total; kw0 = kw0 + KT_WORDS) {
let words = min(KT_WORDS, k_words_total - kw0);
// Cooperative vec4 load + pack of the A tile (TILE_M rows x `words` u32).
for (var i = tid; i < TILE_M * words; i = i + TILE_N) {
let mi = i / words;
let ki = i % words;
let src_m = m_block + mi;
var packed = 0u;
if (src_m < params.M) {
{% if aPacked == false %}
let k4 = (kw0 + ki) * 4u;
let a_row = a_base4 + src_m * params.K;
let v = vec4<{{ aScalar }}>(
a[a_row + k4],
a[a_row + k4 + 1u],
a[a_row + k4 + 2u],
a[a_row + k4 + 3u],
);
{% else %}
let v = a[a_base4 + src_m * k_words_total + kw0 + ki];
{% endif %}
packed = pack_a(v);
atomicAdd(&a_row_sum[mi], sum4_a(v));
}
a_tile[mi * KT_WORDS + ki] = packed;
}
workgroupBarrier();
if (n_valid) {
{% if tileM == 1 %}
// M=1 has only one output accumulator, so a scalar K loop forms a long
// dependent DP4A chain. Interleave several words while preserving the
// coalesced mapping of neighboring threads to neighboring B columns.
let unrolled_words = words - words % GEMV_K_UNROLL;
for (var kk = 0u; kk < unrolled_words; kk += GEMV_K_UNROLL) {
{% for u in range(GEMV_UNROLL) %}
let k4_{{ u }} = (kw0 + kk + {{ u }}u) * 4u;
let b_row_{{ u }} = b_base + k4_{{ u }} * params.N + col;
let b0_{{ u }} = b[b_row_{{ u }}];
let b1_{{ u }} = b[b_row_{{ u }} + params.N];
let b2_{{ u }} = b[b_row_{{ u }} + 2u * params.N];
let b3_{{ u }} = b[b_row_{{ u }} + 3u * params.N];
sum_b{{ "" if u == 0 else "_" ~ u }} += sum4_b(b0_{{ u }}, b1_{{ u }}, b2_{{ u }}, b3_{{ u }});
let bp_{{ u }} = pack_b(b0_{{ u }}, b1_{{ u }}, b2_{{ u }}, b3_{{ u }});
r0{{ "" if u == 0 else "_" ~ u }} += dot4_packed(a_tile[kk + {{ u }}u], bp_{{ u }});
{% endfor %}
}
for (var kk = unrolled_words; kk < words; kk++) {
let k4 = (kw0 + kk) * 4u;
let b_row = b_base + k4 * params.N + col;
let b0 = b[b_row];
let b1 = b[b_row + params.N];
let b2 = b[b_row + 2u * params.N];
let b3 = b[b_row + 3u * params.N];
sum_b += sum4_b(b0, b1, b2, b3);
let bp = pack_b(b0, b1, b2, b3);
r0 += dot4_packed(a_tile[kk], bp);
}
{% else %}
for (var kk = 0u; kk < words; kk = kk + 1u) {
let k4 = (kw0 + kk) * 4u;
let b_row = b_base + k4 * params.N + col;
let b0 = b[b_row];
let b1 = b[b_row + params.N];
let b2 = b[b_row + 2u * params.N];
let b3 = b[b_row + 3u * params.N];
sum_b = sum_b + sum4_b(b0, b1, b2, b3);
let bp = pack_b(b0, b1, b2, b3);
{% for m in range(tileM) %}
r{{ m }} = r{{ m }} + dot4_packed(a_tile[{{ m }}u * KT_WORDS + kk], bp);
{% endfor %}
}
{% endif %}
}
workgroupBarrier();
}
{% if aPacked == false %}
// Exactly one uniform guarded word handles K % 4. Missing lanes use the raw
// bias-domain zero (128 for u8, 0 for i8), so their shifted values, sums, and
// dot-product contributions are all zero while params.K remains unpadded for
// the zero-point correction below.
if (tail_lanes != 0u) {
if (tid < TILE_M) {
let src_m = m_block + tid;
var packed = 0u;
if (src_m < params.M) {
let k4 = k_words_total * 4u;
let a_row = a_base4 + src_m * params.K;
let a0 = a[a_row + k4];
var a1: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};
var a2: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};
if (tail_lanes > 1u) { a1 = a[a_row + k4 + 1u]; }
if (tail_lanes > 2u) { a2 = a[a_row + k4 + 2u]; }
let a3: {{ aScalar }} = {{ "128u" if aUnsigned else "0" }};
let v = vec4<{{ aScalar }}>(a0, a1, a2, a3);
packed = pack_a(v);
{{ "a_row_sum[tid] += dot4_packed(packed, 0x01010101u);" if ownRowSums else "atomicAdd(&a_row_sum[tid], sum4_a(v));" }}
}
a_tile[tid * KT_WORDS] = packed;
}
workgroupBarrier();
if (n_valid) {
let k4 = k_words_total * 4u;
let b_row = b_base + k4 * params.N + col;
let b0 = b[b_row];
var b1: {{ bScalar }} = {{ "128u" if bUnsigned else "0" }};
var b2: {{ bScalar }} = {{ "128u" if bUnsigned else "0" }};
if (tail_lanes > 1u) { b1 = b[b_row + params.N]; }
if (tail_lanes > 2u) { b2 = b[b_row + 2u * params.N]; }
let b3: {{ bScalar }} = {{ "128u" if bUnsigned else "0" }};
sum_b = sum_b + sum4_b(b0, b1, b2, b3);
let bp = pack_b(b0, b1, b2, b3);
{% for m in range(tileM) %}
r{{ m }} = r{{ m }} + dot4_packed(a_tile[{{ m }}u * KT_WORDS], bp);
{% endfor %}
}
workgroupBarrier();
}
{% endif %}
if (!n_valid) {
return;
}
// Fold bias + zero-point corrections (exact in modular i32 arithmetic).
let cb: i32 = {{ "128" if bUnsigned else "0" }} - read_b_zero({% if bZeroPerColumn %}col{% endif %});
{% if not aZeroPerRow %}
let ca: i32 = {{ "128" if aUnsigned else "0" }} - read_a_zero();
let kcc: i32 = i32(params.K) * ca * cb;
{% endif %}
{% if needsBSum and tileM == 1 %}
let sum_b_total = sum_b{% for u in range(1, GEMV_UNROLL) %} + sum_b_{{ u }}{% endfor %};
{% endif %}
{% for m in range(tileM) %}
{
let mr = m_block + {{ m }}u;
if (mr < params.M) {
{% if aZeroPerRow %}
let ca: i32 = {{ "128" if aUnsigned else "0" }} - read_a_zero(mr);
let kcc: i32 = i32(params.K) * ca * cb;
{% endif %}
var acc = r{{ m }}{% if tileM == 1 %}{% for u in range(1, GEMV_UNROLL) %} + r0_{{ u }}{% endfor %}{% endif %};
acc = acc + cb * atomicLoad(&a_row_sum[{{ m }}u]);
acc = acc + ca * {% if tileM == 1 %}sum_b_total{% else %}sum_b{% endif %};
acc = acc + kcc;
{% if hasBias %}
acc = acc + bias[{{ "col" if biasPerColumn is defined and biasPerColumn else "mr" }}];
{% endif %}
{% if requant == "none" %}
y[y_base + mr * params.N + col] = acc;
{% else %}
{% set scale_index = "col" if requant == "per_column" else ("mr" if requant == "per_row" else "0u") %}
let rounded = round_requantized(acc, f32(a_scale[0]), f32(b_scale[{{ scale_index }}]), f32(y_scale[0]));
let q = clamp(rounded + read_y_zero(), {{ qMin }}, {{ qMax }});
{% if yUnsigned %}
y[y_base + mr * params.N + col] = u32(q);
{% else %}
y[y_base + mr * params.N + col] = q;
{% endif %}
{% endif %}
}
}
{% endfor %}
}