ml: fp16-widened int8 GEMM weights opt-in, whisper encode 633 -> 537 ms on Pixel
- Commit
80f2c621e35aefa71e7b930c2e8cdd2b1f63e924- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-26 03:31 UTC (1 month ago)
- Parents
9ecc465
Diff
library/ml/src/main/rust/shaders/conv_point_int8.comp
diff --git a/library/ml/src/main/rust/shaders/conv_point_int8.comp b/library/ml/src/main/rust/shaders/conv_point_int8.compindex ae6931c14b..c02db9cba9 100644--- a/library/ml/src/main/rust/shaders/conv_point_int8.comp+++ b/library/ml/src/main/rust/shaders/conv_point_int8.comp@@ -227,11 +227,21 @@ void row_taps() { } } +#include "conv_point_widened.glsl"+ void main() { if (p.in1 == 1u) { split_rows(); return; }+ if (p.in1 == 3u) {+ widened_block();+ return;+ }+ if (p.in1 == 4u) {+ widened_split();+ return;+ } if (p.in1 == 2u) { row_taps(); return;
library/ml/src/main/rust/shaders/conv_point_widened.glsl
diff --git a/library/ml/src/main/rust/shaders/conv_point_widened.glsl b/library/ml/src/main/rust/shaders/conv_point_widened.glslnew file mode 100644index 0000000000..5194d2f988--- /dev/null+++ b/library/ml/src/main/rust/shaders/conv_point_widened.glsl@@ -0,0 +1,146 @@+//! `conv_point_int8.comp`'s wide paths over weights the runtime widened to fp16 at upload+//! (`p.in1` = 3: four channels per lane, = 4: two). Every int8 value is exact in fp16, so each+//! tap is the same float the int8 paths unpack, summed in the same order: bit-identical, without+//! the per-tap `bitfieldExtract` + int-to-float that made those paths ALU-bound. `p.weight` is+//! still a 32-bit word offset, of a 16-byte-aligned fp16 row block; `in_c % 16 == 0`.++/// Four positions starting at element `at`, which need not be quad-aligned.+vec4 shifted_quad(uint at, uint last_quad) {+ uint q = at >> 2u;+ uint s = at & 3u;+ f16vec4 a = arena_quad[q];+ f16vec4 b = arena_quad[min(q + 1u, last_quad)];+ f16vec4 h = s == 0u ? a+ : s == 1u ? f16vec4(a.yzw, b.x)+ : s == 2u ? f16vec4(a.zw, b.xy)+ : f16vec4(a.w, b.xyz);+ return vec4(h);+}++void store_row(uint channel, uint position_base, uint positions, vec4 sum) {+ if (channel >= p.out_c) {+ return;+ }+ float scale = float(weights[p.act_weight + channel]);+ float offset = float(weights[p.bias + channel]);+ for (uint j = 0u; j < BLOCK; j++) {+ if (position_base + j >= positions) {+ continue;+ }+ uint index = channel * positions + position_base + j;+ float value = quant_store(fused_store(sum[j] * scale + offset, p.act, channel, index));+ arena[p.out_at + index] = float16_t(value);+ }+}++void widened_block() {+ uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;+ if (tile >= p.count) {+ return;+ }+ uint positions = p.out_h * p.out_w;+ uint tiles_across = (positions + TILE - 1u) / TILE;+ uint lid = gl_LocalInvocationID.x;+ uint channel_base = (tile / tiles_across) * TILE + (lid >> 3u) * BLOCK;+ uint position_base = (tile % tiles_across) * TILE + (lid & 7u) * BLOCK;+ if (position_base >= positions) {+ return;+ }+ uint rows8[BLOCK];+ vec4 sum[BLOCK];+ for (uint i = 0u; i < BLOCK; i++) {+ uint row = min(channel_base + i, p.out_c - 1u);+ rows8[i] = (p.weight + ((row * p.in_c) >> 1u)) >> 2u;+ sum[i] = vec4(0.0);+ }+ if ((positions & 3u) == 0u && (p.in0 & 3u) == 0u) {+ uint quads = positions >> 2u;+ uint quad = (p.in0 + position_base) >> 2u;+ for (uint k = 0u; k < p.in_c; k += 8u) {+ uvec4 w[BLOCK];+ for (uint i = 0u; i < BLOCK; i++) {+ w[i] = weights128[rows8[i] + (k >> 3u)];+ }+ for (uint t = 0u; t < 8u; t++) {+ vec4 x = vec4(arena_quad[quad + (k + t) * quads]);+ for (uint i = 0u; i < BLOCK; i++) {+ sum[i] += unpackHalf2x16(w[i][t >> 1u])[t & 1u] * x;+ }+ }+ }+ } else {+ uint first = p.in0 + position_base;+ uint last_quad = (p.in0 + p.in_c * positions - 1u) >> 2u;+ for (uint k = 0u; k < p.in_c; k += 8u) {+ uvec4 w[BLOCK];+ for (uint i = 0u; i < BLOCK; i++) {+ w[i] = weights128[rows8[i] + (k >> 3u)];+ }+ for (uint t = 0u; t < 8u; t++) {+ vec4 x = shifted_quad(first + (k + t) * positions, last_quad);+ for (uint i = 0u; i < BLOCK; i++) {+ sum[i] += unpackHalf2x16(w[i][t >> 1u])[t & 1u] * x;+ }+ }+ }+ }+ for (uint i = 0u; i < BLOCK; i++) {+ store_row(channel_base + i, position_base, positions, sum[i]);+ }+}++void widened_split() {+ uint tile = gl_WorkGroupID.y * gl_NumWorkGroups.x + gl_WorkGroupID.x;+ if (tile >= p.count) {+ return;+ }+ uint positions = p.out_h * p.out_w;+ uint tiles_across = (positions + TILE - 1u) / TILE;+ uint lid = gl_LocalInvocationID.x;+ uint channel_base = (tile / tiles_across) * (TILE / BLOCK * SPLIT) + (lid >> 3u) * SPLIT;+ uint position_base = (tile % tiles_across) * TILE + (lid & 7u) * BLOCK;+ if (position_base >= positions) {+ return;+ }+ uint rows8[SPLIT];+ vec4 sum[SPLIT];+ for (uint i = 0u; i < SPLIT; i++) {+ uint row = min(channel_base + i, p.out_c - 1u);+ rows8[i] = (p.weight + ((row * p.in_c) >> 1u)) >> 2u;+ sum[i] = vec4(0.0);+ }+ if ((positions & 3u) == 0u && (p.in0 & 3u) == 0u) {+ uint quads = positions >> 2u;+ uint quad = (p.in0 + position_base) >> 2u;+ for (uint k = 0u; k < p.in_c; k += 8u) {+ uvec4 w[SPLIT];+ for (uint i = 0u; i < SPLIT; i++) {+ w[i] = weights128[rows8[i] + (k >> 3u)];+ }+ for (uint t = 0u; t < 8u; t++) {+ vec4 x = vec4(arena_quad[quad + (k + t) * quads]);+ for (uint i = 0u; i < SPLIT; i++) {+ sum[i] += unpackHalf2x16(w[i][t >> 1u])[t & 1u] * x;+ }+ }+ }+ } else {+ uint first = p.in0 + position_base;+ uint last_quad = (p.in0 + p.in_c * positions - 1u) >> 2u;+ for (uint k = 0u; k < p.in_c; k += 8u) {+ uvec4 w[SPLIT];+ for (uint i = 0u; i < SPLIT; i++) {+ w[i] = weights128[rows8[i] + (k >> 3u)];+ }+ for (uint t = 0u; t < 8u; t++) {+ vec4 x = shifted_quad(first + (k + t) * positions, last_quad);+ for (uint i = 0u; i < SPLIT; i++) {+ sum[i] += unpackHalf2x16(w[i][t >> 1u])[t & 1u] * x;+ }+ }+ }+ }+ for (uint i = 0u; i < SPLIT; i++) {+ store_row(channel_base + i, position_base, positions, sum[i]);+ }+}
library/ml/src/main/rust/src/bridge_part5.rs
diff --git a/library/ml/src/main/rust/src/bridge_part5.rs b/library/ml/src/main/rust/src/bridge_part5.rsindex 078707781c..48d6f1225a 100644--- a/library/ml/src/main/rust/src/bridge_part5.rs+++ b/library/ml/src/main/rust/src/bridge_part5.rs@@ -231,12 +231,13 @@ fn build_whisper<'l>( // Recorded on the decode step first, then the encoder every transcription runs first: the // first recording of each kernel is the expensive one, and this keeps it out of the first- // transcription's switch into decoding.- let mut net = Reshaped::streamed(+ // transcription's switch into decoding. Windowed over both so the encoder's int8 weights are+ // widened at upload (its plan lists them; the decode step's does not).+ let mut net = Reshaped::windowed( context::shared()?, weights.offsets(), &weights,- whisper::Mode::DecodeStep,+ &[whisper::Mode::DecodeStep, whisper::Mode::Encode], whisper_plan, )?; net.at(whisper::Mode::Encode)?;
library/ml/src/main/rust/src/nets/mod_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2.rs b/library/ml/src/main/rust/src/nets/mod_part2.rsindex 92a6587963..3658fdbb40 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -61,6 +61,11 @@ pub struct Plan { /// SCRFD has **nine** — score, box and keypoint maps at each of three strides — /// which is the reason this is a list. pub outputs: Vec<Binding>,++ /// Word offsets of int8 1x1 weights the runtime should widen to fp16 at upload, at every+ /// shape (so a one-position load plan lists what later GEMM plans use). Empty unless the+ /// net opted in with [`Builder::widen_int8`].+ pub widen: Vec<u32>, } impl Plan {
library/ml/src/main/rust/src/nets/mod_part2b.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2b.rs b/library/ml/src/main/rust/src/nets/mod_part2b.rsindex 39e2d14efa..d2372cf45d 100644--- a/library/ml/src/main/rust/src/nets/mod_part2b.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2b.rs@@ -16,6 +16,8 @@ pub struct Builder<'a> { /// Whether spatial convolutions lower to the register-blocked tiled path. /// See [`Builder::spatial_tiling`]. spatial_tiled: bool,+ /// See [`Builder::widen_int8`].+ widen_int8: bool, } /// Arena allocations are aligned to this many fp16 elements, i.e. 16 bytes — the same
library/ml/src/main/rust/src/nets/mod_part4.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part4.rs b/library/ml/src/main/rust/src/nets/mod_part4.rsindex 1fd3eb3818..f8417bfe8e 100644--- a/library/ml/src/main/rust/src/nets/mod_part4.rs+++ b/library/ml/src/main/rust/src/nets/mod_part4.rs@@ -11,9 +11,19 @@ impl<'a> Builder<'a> { inputs: Vec::new(), pad_edge: false, spatial_tiled: false,+ widen_int8: false, } } + /// Run this net's int8 GEMMs over fp16 copies of their weights, widened at upload.+ ///+ /// Exact (every int8 is an fp16, the sums are unchanged) and faster where the int8 unpack is+ /// the bottleneck, at twice the memory for those weights. [`Plan::widen`] lists them and the+ /// runtime falls back to the int8 path for any it did not widen.+ pub fn widen_int8(&mut self) {+ self.widen_int8 = true;+ }+ /// Lower dense spatial convolutions to the register-blocked path from here on. /// /// A builder-level mode like [`Builder::edge_padding`]: the vision nets set it once
library/ml/src/main/rust/src/nets/mod_part7.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part7.rs b/library/ml/src/main/rust/src/nets/mod_part7.rsindex e5af59407d..5062b647e3 100644--- a/library/ml/src/main/rust/src/nets/mod_part7.rs+++ b/library/ml/src/main/rust/src/nets/mod_part7.rs@@ -314,6 +314,7 @@ impl<'a> Builder<'a> { inputs: self.inputs.iter().map(|&id| binding(id)).collect::<Result<_, _>>()?, pinned: self.pinned.iter().map(|&id| binding(id)).collect::<Result<_, _>>()?, outputs: outputs.iter().map(|&id| binding(id)).collect::<Result<_, _>>()?,+ widen: self.widened_weights(), }) }
library/ml/src/main/rust/src/nets/mod_part9.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9.rs b/library/ml/src/main/rust/src/nets/mod_part9.rsindex 781ec884e7..17abc43d4b 100644--- a/library/ml/src/main/rust/src/nets/mod_part9.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9.rs@@ -88,6 +88,13 @@ impl<'a> Builder<'a> { && si.c % 16 == 0 && *weight % 4 == 0 && int8_tiles < CONV_POINT_INT8_SPLIT_BELOW;+ // Opted-in nets mark the wide paths 3 / 4 (fp16-widened weights, see+ // conv_point_widened.glsl); the runtime falls back to 0 / 1 if it did not widen.+ let widened = self.widen_int8+ && kind == Kind::ConvPointInt8+ && !row_gemm+ && si.c % 16 == 0+ && *weight % 4 == 0; // The untiled shader's register-blocked path (`in1` = 1): 4 channels x 8 columns // of a row per invocation. Ungrouped only: maia's grouped 1x1 got slower. let int8_blocked = kind == Kind::ConvInt8 && *group == 1;@@ -124,6 +131,8 @@ impl<'a> Builder<'a> { in0: input_at, in1: if row_gemm || grouped_vec { 2+ } else if widened {+ 3 + u32::from(split) } else { u32::from(split || int8_blocked || int4_wide) },
library/ml/src/main/rust/src/nets/mod_part9d.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part9d.rs b/library/ml/src/main/rust/src/nets/mod_part9d.rsindex bd3a967d26..203351d0e2 100644--- a/library/ml/src/main/rust/src/nets/mod_part9d.rs+++ b/library/ml/src/main/rust/src/nets/mod_part9d.rs@@ -88,3 +88,33 @@ impl<'a> Builder<'a> { Ok(()) } }++impl Builder<'_> {+ /// What [`Plan::widen`] lists: every int8 1x1 whose GEMM the widened paths can take.+ fn widened_weights(&self) -> Vec<u32> {+ let mut out = Vec::new();+ if !self.widen_int8 {+ return out;+ }+ for node in &self.nodes {+ let Node::ConvInt8 { input, weight, kernel, stride, pad, group, quant: Quant::I8, .. } =+ node+ else {+ continue;+ };+ let channels = self.shapes.get(input.0).map_or(0, |s| s.c);+ if *group == 1+ && *kernel == (1, 1)+ && *stride == (1, 1)+ && *pad == (0, 0)+ && channels > 0+ && channels % 16 == 0+ && *weight % 4 == 0+ && !out.contains(weight)+ {+ out.push(*weight);+ }+ }+ out+ }+}\ No newline at end of file
library/ml/src/main/rust/src/nets/schedule.rs
diff --git a/library/ml/src/main/rust/src/nets/schedule.rs b/library/ml/src/main/rust/src/nets/schedule.rsindex fc021084b1..1369dfac8f 100644--- a/library/ml/src/main/rust/src/nets/schedule.rs+++ b/library/ml/src/main/rust/src/nets/schedule.rs@@ -305,6 +305,7 @@ mod tests { inputs: vec![Binding { at: 0, shape: Shape { c: 1, h: 1, w: 1 } }], pinned: Vec::new(), outputs: vec![Binding { at: 0, shape: Shape { c: 1, h: 1, w: 1 } }],+ widen: Vec::new(), } }
library/ml/src/main/rust/src/nets/whisper.rs
diff --git a/library/ml/src/main/rust/src/nets/whisper.rs b/library/ml/src/main/rust/src/nets/whisper.rsindex c229f04dd0..f8be3c18ea 100644--- a/library/ml/src/main/rust/src/nets/whisper.rs+++ b/library/ml/src/main/rust/src/nets/whisper.rs@@ -286,6 +286,8 @@ fn declare_cross_caches(b: &mut Builder) -> Vec<(Id, Id)> { fn encode(weights: &dyn WeightSource) -> Result<Plan, String> { let mut builder = Builder::new(weights); let b = &mut builder;+ // Its 1500-position int8 GEMMs run 22% faster over fp16 copies (Pixel 8); exact.+ b.widen_int8(); name_host_tensors(b, &device_tensors(Mode::Encode)); let caches = declare_cross_caches(b);
library/ml/src/main/rust/src/vulkan/parity_part8.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity_part8.rs b/library/ml/src/main/rust/src/vulkan/parity_part8.rsindex 5a7f49185d..749b69bb9d 100644--- a/library/ml/src/main/rust/src/vulkan/parity_part8.rs+++ b/library/ml/src/main/rust/src/vulkan/parity_part8.rs@@ -160,3 +160,54 @@ fn a_two_stage_argmax_keeps_the_first_of_ties_across_slices() { assert_eq!(id, 5_000, "the first of an fp16 tie"); } }++/// `Builder::widen_int8`: the int8 GEMM over fp16-widened weights (`in1` 3 and 4) is+/// bit-identical to the int8 paths and agrees with the reference. 512 x 520 / 517 positions take+/// the four-row path, 40 x 52 / 49 the split one; the widths cover aligned and ragged loads.+#[test]+#[ignore = "needs a Vulkan device"]+fn a_widened_int8_gemm_matches_the_int8_paths_bit_for_bit() {+ for (out_channels, widths, path) in [(512u32, [520u32, 517], 3u32), (40, [52, 49], 4)] {+ let in_channels = 64u32;+ let kernel: Vec<i8> = (0..(out_channels * in_channels) as i32)+ .map(|i| ((i * 37) % 255 - 127) as i8)+ .collect();+ let scales: Vec<f32> =+ (0..out_channels).map(|c| 0.007_812_5 * (1.0 + (c % 7) as f32)).collect();+ let blob = write_mixed(+ graph::SUPERTONIC_VE,+ &[+ Fixture::I8(vec![out_channels, in_channels, 1, 1], kernel),+ Fixture::F16(vec![out_channels], scales),+ Fixture::F16(vec![out_channels], spread(out_channels as usize, 0.5)),+ ],+ );+ let weights = Weights::parse(&blob, graph::SUPERTONIC_VE).expect("the fixture blob parses");+ for width in widths {+ let input = spread((in_channels * width) as usize, 1.3);+ let mut builder = Builder::new(&weights);+ builder.widen_int8();+ let first = builder.input(Shape::new(in_channels, 1, width));+ let last = builder.conv_int8(+ first, 0, out_channels, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 1, Act::Gelu,+ );+ let plan = builder.finish(&[last]).expect("the widened plan builds");+ assert_eq!(plan.widen.len(), 1);+ assert!(plan.ops.iter().any(|op| matches!(+ op,+ crate::nets::Op::Dispatch { kind: crate::nets::Kind::ConvPointInt8, push, .. }+ if push.in1 == path+ )));+ let narrow = Plan { widen: Vec::new(), ..plan.clone() };+ let int8 = on_device(narrow, weights.data().to_vec(), &[&input]);+ let what = format!("a widened int8 gemm, {out_channels} x {width}");+ let host = run_multi(&plan, weights.data(), &[&input]).expect("the interpreter runs");+ let widened = on_device(plan, weights.data().to_vec(), &[&input]);+ matches(&what, &host, &widened);+ assert!(+ int8.iter().flatten().zip(widened.iter().flatten()).all(|(a, b)| a.to_bits() == b.to_bits()),+ "{what}: the widened path differs from the int8 path"+ );+ }+ }+}
library/ml/src/main/rust/src/vulkan/run.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run.rs b/library/ml/src/main/rust/src/vulkan/run.rsindex 96faf689e2..5191e3ce4c 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -34,7 +34,7 @@ use ash::vk; use crate::nets::{Op, Plan}; use crate::preprocess::{self, Normalise};-use crate::weights::Blob;+use crate::weights::{Blob, Dtype, Tensor}; use super::buffers::Buffer; use super::context::Context;@@ -276,6 +276,8 @@ pub struct Net { /// The `.maml` tensors inside the uploaded window, offsets relative to its start, for /// [`Segments::for_op`]. tensors: Vec<crate::weights::Tensor>,+ /// fp16 copies of int8 weights, past the window in the weights buffer. See [`Widened`].+ widened: Vec<Widened>, /// The `[lo, hi)` data-section bytes in the weights buffer. Byte 0 of the buffer is file /// byte `lo`; a plan reading outside the window is refused at record time. window: (u64, u64),@@ -340,4 +342,5 @@ include!("run_part2.rs"); include!("run_part7.rs"); include!("run_part3.rs"); include!("run_part4.rs");-include!("run_part5.rs");\ No newline at end of file+include!("run_part5.rs");+include!("run_part8.rs");\ No newline at end of file
library/ml/src/main/rust/src/vulkan/run_part1.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part1.rs b/library/ml/src/main/rust/src/vulkan/run_part1.rsindex 6beb3ce24b..cd9c1c3184 100644--- a/library/ml/src/main/rust/src/vulkan/run_part1.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part1.rs@@ -33,7 +33,9 @@ impl Net { let mut plans = vec![&plan]; plans.extend_from_slice(also); let window = super::segment::read_window(&plans, weights.tensors(), align)?;- Self::with_window(context, plan, weights, normalise, window)+ // Every plan's list: the first may be a decode step that lists none of the encoder's.+ let widen: Vec<u32> = plans.iter().flat_map(|each| each.widen.iter().copied()).collect();+ Self::with_window(context, plan, weights, normalise, window, &widen) } /// [`Net::new`], uploading the whole data section so any plan over this file can be@@ -45,7 +47,8 @@ impl Net { normalise: Normalise, ) -> Result<Net, String> { let window = (0, weights.data_len());- Self::with_window(context, plan, weights, normalise, window)+ let widen = plan.widen.clone();+ Self::with_window(context, plan, weights, normalise, window, &widen) } fn with_window(@@ -54,17 +57,22 @@ impl Net { weights: &dyn Blob, normalise: Normalise, window: (u64, u64),+ widen: &[u32], ) -> Result<Net, String> { let (lo, hi) = window; if lo > hi || hi > weights.data_len() { return Err(format!("weights window {lo}..{hi} of a {}-byte file", weights.data_len())); } let arena_bytes = (plan.arena_elems as vk::DeviceSize) * 2;+ // fp16 copies of the int8 weights the plan asked to widen go after the window.+ let base = (hi - lo).div_ceil(super::segment::ALIGNMENT) * super::segment::ALIGNMENT;+ let widened = widened_layout(widen, weights.tensors(), window, base);+ let end = widened.last().map_or(hi - lo, |w| w.dst + 2 * w.bytes - lo); // Vulkan forbids a zero-sized buffer, and the descriptor set needs a real one bound to // the weights binding whether or not any shader reads it. A plan can legitimately read // no weights at all — a purely elementwise one does — so this floors the allocation // rather than refusing the plan.- let weights_bytes = ((hi - lo) as vk::DeviceSize).max(2);+ let weights_bytes = (end as vk::DeviceSize).max(2); let input_elems = binding_elems(&plan.inputs); let output_elems = binding_elems(&plan.outputs); // One staging buffer for both directions: the inputs and the outputs are never in@@ -78,7 +86,11 @@ impl Net { let segments = Segments::plan(weights_bytes, &context.limits)?; // A few kilobytes, kept because `record` needs each tensor's extent to know which window // an op fits in, and `rebuild` installs plans this net was not constructed with.- let tensors = super::segment::window_tensors(weights.tensors(), lo, hi);+ let tensors = Self::widened_tensors(+ super::segment::window_tensors(weights.tensors(), lo, hi),+ &widened,+ lo,+ )?; let weights_buffer = Buffer::device_local(&context, weights_bytes)?; let arena = Buffer::device_local(&context, arena_bytes)?;@@ -117,6 +129,7 @@ impl Net { pipelines, segments, tensors,+ widened, window, command_pool, command_buffer: vk::CommandBuffer::null(),@@ -135,10 +148,12 @@ impl Net { let staged = std::time::Instant::now(); net.upload_weights(weights)?;+ net.upload_widened(weights)?; timing!(- "upload {} MB of {} MB (bytes {lo}..{hi}) in {:.0} ms",+ "upload {} MB of {} MB (bytes {lo}..{hi}, {} MB widened) in {:.0} ms", weights_bytes / (1024 * 1024), weights.data_len() / (1024 * 1024),+ net.widened_bytes() / (1024 * 1024), staged.elapsed().as_secs_f64() * 1000.0 ); net.command_buffer = net.allocate_command_buffer()?;
library/ml/src/main/rust/src/vulkan/run_part6.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part6.rs b/library/ml/src/main/rust/src/vulkan/run_part6.rsindex aa771a9050..9055e778bf 100644--- a/library/ml/src/main/rust/src/vulkan/run_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part6.rs@@ -19,7 +19,17 @@ impl Net { /// once per net rather than once per inference. fn upload_weights(&self, weights: &dyn Blob) -> Result<(), String> { let (lo, hi) = self.window;- let total = hi - lo;+ self.upload_with(0, hi - lo, &mut |offset, piece| weights.read_at(lo + offset, piece))+ }++ /// Write `total` bytes at weights-buffer byte `dst`, `fill(offset, piece)` producing each+ /// chunk. See [`Net::upload_weights`].+ fn upload_with(+ &self,+ dst: u64,+ total: u64,+ fill: &mut dyn FnMut(u64, &mut [u8]) -> Result<(), String>,+ ) -> Result<(), String> { if total == 0 { return Ok(()); }@@ -71,7 +81,7 @@ impl Net { Some(piece) => piece, None => break Err("a chunk is larger than its buffer".to_string()), };- if let Err(e) = weights.read_at(lo + written, piece) {+ if let Err(e) = fill(written, piece) { break Err(e); } // This side's previous copy (two chunks ago) may still be reading its staging@@ -98,7 +108,7 @@ impl Net { ) .map_err(|e| format!("begin_command_buffer {e:?}"))?; let region = vk::BufferCopy::default()- .dst_offset(written as vk::DeviceSize)+ .dst_offset((dst + written) as vk::DeviceSize) .size(size as vk::DeviceSize); device.cmd_copy_buffer( command_buffer,@@ -147,6 +157,7 @@ impl Net { kind: crate::nets::Kind, push: &crate::nets::Push, ) -> Result<crate::nets::Push, String> {+ let push = &self.widen_push(kind, push); let (lo, hi) = self.window; let reads = kind.weight_reads(push); for read in &reads {
library/ml/src/main/rust/src/vulkan/run_part8.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part8.rs b/library/ml/src/main/rust/src/vulkan/run_part8.rsnew file mode 100644index 0000000000..84800e4e84--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/run_part8.rs@@ -0,0 +1,141 @@+/// One int8 tensor's fp16 copy, appended to the weights buffer past the uploaded window.+///+/// See [`crate::nets::Builder::widen_int8`]. Offsets are file-data-section bytes; a copy's+/// `dst` lies past the file window, as if the file had been longer.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+struct Widened {+ /// Where the int8 tensor starts.+ src: u64,+ /// Its length in bytes, which is its element count.+ bytes: u64,+ /// Where its fp16 copy starts.+ dst: u64,+}++/// The copies `widen` asks for that lie in `window`, packed from window byte `base`.+///+/// A listed offset that is not inside a whole int8 tensor of the window, or whose copy could not+/// stay 16-byte aligned, is skipped: its ops keep the int8 path.+fn widened_layout(widen: &[u32], tensors: &[Tensor], window: (u64, u64), base: u64) -> Vec<Widened> {+ let (lo, hi) = window;+ let mut out: Vec<Widened> = Vec::new();+ let mut next = lo + base;+ for &word in widen {+ let at = u64::from(word) * 4;+ let Some(tensor) = tensors.iter().find(|t| {+ let start = u64::from(t.offset);+ at >= start && at < start + t.dtype.bytes(u64::from(t.len))+ }) else {+ continue;+ };+ let src = u64::from(tensor.offset);+ let bytes = u64::from(tensor.len);+ if !matches!(tensor.dtype, Dtype::I8)+ || src < lo+ || src + bytes > hi+ || src % 16 != 0+ || bytes % 8 != 0+ || out.iter().any(|w| w.src == src)+ {+ continue;+ }+ out.push(Widened { src, bytes, dst: next });+ next += bytes * 2;+ }+ out+}++/// `out` filled with the fp16 copies' bytes from file-relative byte `start`.+fn fill_widened(+ widened: &[Widened],+ weights: &dyn Blob,+ start: u64,+ out: &mut [u8],+ scratch: &mut Vec<u8>,+) -> Result<(), String> {+ static HALVES: OnceLock<[u16; 256]> = OnceLock::new();+ let halves = HALVES+ .get_or_init(|| std::array::from_fn(|b| preprocess::f32_to_f16(f32::from(b as u8 as i8))));+ let end = start + out.len() as u64;+ for w in widened {+ let (from, to) = (start.max(w.dst), end.min(w.dst + 2 * w.bytes));+ if from >= to {+ continue;+ }+ let count = usize::try_from((to - from) / 2).map_err(|_| "a widened span overflowed")?;+ scratch.resize(count, 0);+ weights.read_at(w.src + (from - w.dst) / 2, scratch)?;+ let at = usize::try_from(from - start).map_err(|_| "a widened span overflowed")?;+ let target = out.get_mut(at..at + 2 * count).ok_or("a widened span is outside its chunk")?;+ for (pair, &byte) in target.chunks_exact_mut(2).zip(scratch.iter()) {+ let bits = halves.get(usize::from(byte)).copied().unwrap_or(0);+ pair.copy_from_slice(&bits.to_le_bytes());+ }+ }+ Ok(())+}++impl Net {+ /// The window's tensors plus one fp16 entry per widened copy, offsets relative to `lo`.+ fn widened_tensors(+ mut tensors: Vec<Tensor>,+ widened: &[Widened],+ lo: u64,+ ) -> Result<Vec<Tensor>, String> {+ for w in widened {+ let len = u32::try_from(w.bytes).map_err(|_| "a widened tensor overflowed")?;+ tensors.push(Tensor {+ rank: 1,+ dims: [len, 0, 0, 0],+ offset: u32::try_from(w.dst - lo).map_err(|_| "a widened offset overflowed")?,+ len,+ dtype: Dtype::F16,+ });+ }+ Ok(tensors)+ }++ /// Upload the fp16 copies after the window, streamed in chunks like the window itself.+ fn upload_widened(&self, weights: &dyn Blob) -> Result<(), String> {+ let (Some(first), Some(last)) = (self.widened.first(), self.widened.last()) else {+ return Ok(());+ };+ let total = last.dst + 2 * last.bytes - first.dst;+ let mut scratch = Vec::new();+ self.upload_with(first.dst - self.window.0, total, &mut |offset, piece| {+ fill_widened(&self.widened, weights, first.dst + offset, piece, &mut scratch)+ })+ }++ /// A widened-path int8 GEMM (`in1` 3 or 4) pointed at its fp16 copy, or moved back to the+ /// int8 path (`in1` 0 or 1) when its weights were not widened or the copy is not reachable+ /// through one descriptor window together with the scale and bias.+ fn widen_push(&self, kind: crate::nets::Kind, push: &crate::nets::Push) -> crate::nets::Push {+ if kind != crate::nets::Kind::ConvPointInt8 || !(push.in1 == 3 || push.in1 == 4) {+ return *push;+ }+ let fallback = crate::nets::Push { in1: push.in1 - 3, ..*push };+ let at = u64::from(push.weight) * 4;+ let Some(w) = self.widened.iter().find(|w| at >= w.src && at < w.src + w.bytes) else {+ return fallback;+ };+ let dst = w.dst + 2 * (at - w.src);+ let Ok(word) = u32::try_from(dst / 4) else {+ return fallback;+ };+ if dst % 16 != 0 {+ return fallback;+ }+ let widened = crate::nets::Push { weight: word, ..*push };+ let rebased = super::segment::rebase_push(self.window.0, kind, &widened);+ match self.segments.for_op(0, kind, &rebased, &self.tensors) {+ Ok(_) => widened,+ Err(_) => fallback,+ }+ }++ /// Bytes of fp16 copies this net holds, for the load log.+ fn widened_bytes(&self) -> u64 {+ self.widened.iter().map(|w| 2 * w.bytes).sum()+ }+}