Modern Apps git

← Modern-Apps.git

ml: RmsNorm quad row path, gemma4 decode norms 8.4 -> 3.8 ms on Pixel

Commit
0c7b7d48fe8463ef8242f949ec83e64f81dd7ee4
Author
vayun-mathur <[email protected]>
When
2026-10-26 03:36 UTC (1 month ago)
Parents
a9e97cf

Diff

library/ml/src/main/rust/examples/check_gemma4_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_parity.rsindex 4bad336bfe..a26ac7fecb 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -520,7 +520,12 @@ fn time_decode(     }     if stamps {         match net.at(gemma4::Mode::DecodeStep.at(TIER)).and_then(|at| at.op_times()) {-            Ok(report) => print_kinds("decode step", &report),+            Ok(report) => {+                print_kinds("decode step", &report);+                if let Ok(plan) = gemma4::build(&weights.offsets(), gemma4::Mode::DecodeStep.at(TIER)) {+                    print_shapes(&report, &plan);+                }+            }             Err(why) => println!("timestamps unreadable: {why}"),         }         if let Some(head) = head_net.as_mut() {@@ -935,6 +940,29 @@ fn print_kinds(title: &str, report: &[(String, f64, f64)]) {     } } +/// Per-(kind, in_c, out_c) GPU time for the weight-streaming kinds, with the weight bandwidth.+fn print_shapes(report: &[(String, f64, f64)], plan: &modelrunner::nets::Plan) {+    use modelrunner::nets::{Kind, Op};+    let mut rows: Vec<(String, u32, u32, usize, f64, f64)> = Vec::new();+    let dispatches = plan.ops.iter().filter_map(|op| match op { Op::Dispatch { kind, push, .. } => Some((*kind, *push)), _ => None });+    for ((kind, push), (_, us, _)) in dispatches.zip(report) {+        let bits = match kind { Kind::ConvVecInt4 => 4.0, Kind::ConvVecInt8 => 8.0, Kind::RmsNorm => 16.0, _ => continue };+        let (in_c, out_c) = if kind == Kind::RmsNorm { (push.in_c, push.group.max(1)) } else { (push.in_c, push.out_c) };+        let bytes = if kind == Kind::RmsNorm { f64::from(in_c) * 2.0 } else { f64::from(in_c) * f64::from(out_c) * bits / 8.0 };+        let name = format!("{kind:?}");+        let push = modelrunner::nets::Push { in_c, out_c, ..push };+        match rows.iter_mut().find(|r| r.0 == name && r.1 == push.in_c && r.2 == push.out_c) {+            Some(r) => { r.3 += 1; r.4 += us; r.5 += bytes; }+            None => rows.push((name, push.in_c, push.out_c, 1, *us, bytes)),+        }+    }+    rows.sort_by(|a, b| b.4.total_cmp(&a.4));+    println!("{:>6} {:>10} {:>10} {:>8}  kind in_c -> out_c", "count", "total-ms", "mean-us", "GB/s");+    for (kind, in_c, out_c, n, us, bytes) in rows {+        println!("{n:>6} {:>10.2} {:>10.1} {:>8.1}  {kind} {in_c} -> {out_c}", us / 1000.0, us / n as f64, bytes / us / 1000.0);+    }+}+ /// Host RSS high-water mark and current RSS (Linux/Android only). fn print_memory() {     let Ok(status) = std::fs::read_to_string("/proc/self/status") else { return };
library/ml/src/main/rust/shaders/rmsnorm.comp
diff --git a/library/ml/src/main/rust/shaders/rmsnorm.comp b/library/ml/src/main/rust/shaders/rmsnorm.compindex 814f7ef670..4b0d765bc3 100644--- a/library/ml/src/main/rust/shaders/rmsnorm.comp+++ b/library/ml/src/main/rust/shaders/rmsnorm.comp@@ -24,13 +24,58 @@ //! # Row mode //! //! With `p.kw == 1` one workgroup owns one (group, position) row and its lanes split the-//! group's channels. See `reduce.glsl`.+//! group's channels. See `reduce.glsl`. A contiguous, quad-aligned row (one position, as in+//! every decode step) takes `quad_row`, four channels per load; its sum of squares adds in a+//! different order, so outputs can move by fp32 rounding against the scalar row mode.  #extension GL_KHR_shader_subgroup_basic : require #extension GL_KHR_shader_subgroup_arithmetic : require #include "common.glsl" #include "reduce.glsl" +/// Binding 0 as fp16 quads, for the contiguous row path. Aliases `arena`; each lane reads and+/// writes only its own quads.+layout(std430, binding = 0) buffer ArenaQuad {+    f16vec4 arena_quad[];+};++/// Binding 1 as fp16 quads, for the gains on the contiguous row path.+layout(std430, binding = 1) readonly buffer WeightsQuad {+    f16vec4 weights_quad[];+};++/// Row mode over one contiguous, quad-aligned row (a single position): a lane moves four+/// channels per load, so a 1536-wide decode row is six loads a lane per pass instead of 24.+/// Latency of those dependent loads, not bandwidth, was most of each 46 us dispatch.+void quad_row(uint base, float epsilon, uint per_group) {+    uint lane = gl_LocalInvocationID.x;+    uint lanes = gl_WorkGroupSize.x;+    uint in_q = (p.in0 + base) >> 2u;+    uint out_q = (p.out_at + base) >> 2u;+    uint res_q = (p.res + base) >> 2u;+    uint gain_q = p.weight >> 2u;+    uint quads = per_group >> 2u;+    float squares = 0.0;+    for (uint q = lane; q < quads; q += lanes) {+        vec4 v = vec4(arena_quad[in_q + q]);+        squares += v.x * v.x;+        squares += v.y * v.y;+        squares += v.z * v.z;+        squares += v.w * v.w;+    }+    float inverse = 1.0 / sqrt(workgroup_sum(squares) / float(per_group) + epsilon);+    for (uint q = lane; q < quads; q += lanes) {+        vec4 v = vec4(arena_quad[in_q + q]);+        vec4 gamma = vec4(weights_quad[gain_q + q]);+        vec4 normed = vec4(quant_store(v.x * inverse * gamma.x), quant_store(v.y * inverse * gamma.y),+                           quant_store(v.z * inverse * gamma.z), quant_store(v.w * inverse * gamma.w));+        if (p.res != 0xFFFFFFFFu) {+            normed += vec4(arena_quad[res_q + q]);+        }+        arena_quad[out_q + q] = f16vec4(normed);+    }+}+ void row_mode() {     uint position = reduce_row();     if (position >= p.count) {@@ -44,6 +89,13 @@ void row_mode() {     uint base = (position / stride) * per_group;     uint at_pos = position % stride;     float epsilon = uintBitsToFloat(p.param1_bits);+    bool quad = stride == 1u && (per_group & 3u) == 0u && ((p.in0 + base) & 3u) == 0u+        && ((p.out_at + base) & 3u) == 0u && (p.weight & 3u) == 0u+        && (p.res == 0xFFFFFFFFu || ((p.res + base) & 3u) == 0u);+    if (quad) {+        quad_row(base, epsilon, per_group);+        return;+    }     float squares = 0.0;     for (uint c = lane; c < per_group; c += lanes) {         float value = float(arena[p.in0 + (base + c) * stride + at_pos]);