library:ml: multi-IO plans, fused PReLU, nearest resize
- Commit
c83bfe90032528831fed78da27a07ab1e7551fec- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-27 02:21 UTC (3 months ago)
- Parents
03c6adb
Diff
library/ml/src/main/rust/shaders/common.glsl
diff --git a/library/ml/src/main/rust/shaders/common.glsl b/library/ml/src/main/rust/shaders/common.glslindex d1eed5c0f1..e263e26985 100644--- a/library/ml/src/main/rust/shaders/common.glsl+++ b/library/ml/src/main/rust/shaders/common.glsl@@ -65,6 +65,7 @@ layout(push_constant) uniform Push { uint pad_l; uint group; uint act;+ uint act_weight; uint count; } p; @@ -73,6 +74,7 @@ layout(push_constant) uniform Push { #define ACT_RELU 1u #define ACT_HARDSWISH 2u #define ACT_SIGMOID 3u+#define ACT_PRELU 4u // This invocation's output element, across a 2D grid of workgroups. //@@ -89,10 +91,14 @@ uint global_index() { return group * gl_WorkGroupSize.x + gl_LocalInvocationID.x; } -// The activation fused into a layer's store. Every ReLU, HardSwish and Sigmoid in both-// networks directly follows a convolution, so this is the only place activations-// happen and there is no standalone activation pass.-float activate(float x, uint kind) {+// The activation fused into a layer's store. Every ReLU, HardSwish, Sigmoid and PReLU in+// every network here directly follows a convolution, so this is the only place+// activations happen and there is no standalone activation pass.+//+// `channel` is the output channel, needed only by PReLU, whose slope is one value per+// channel at `p.act_weight` in the weights buffer. Passing it unconditionally costs a+// register and keeps one signature.+float activate(float x, uint kind, uint channel) { if (kind == ACT_RELU) { return max(x, 0.0); }@@ -103,6 +109,12 @@ float activate(float x, uint kind) { if (kind == ACT_SIGMOID) { return 1.0 / (1.0 + exp(-x)); }+ if (kind == ACT_PRELU) {+ // ONNX PRelu. The branch is on the sign of the accumulator, so it diverges+ // within a wave; a `mix` on the comparison would too, and this reads as the+ // definition does.+ return x < 0.0 ? x * float(weights[p.act_weight + channel]) : x;+ } return x; }
library/ml/src/main/rust/shaders/conv.comp
diff --git a/library/ml/src/main/rust/shaders/conv.comp b/library/ml/src/main/rust/shaders/conv.compindex 139e63aec7..e90cd5c9bf 100644--- a/library/ml/src/main/rust/shaders/conv.comp+++ b/library/ml/src/main/rust/shaders/conv.comp@@ -62,5 +62,5 @@ void main() { } } - arena[p.out_at + index] = float16_t(activate(acc, p.act));+ arena[p.out_at + index] = float16_t(activate(acc, p.act, oc)); }
library/ml/src/main/rust/shaders/conv_transpose.comp
diff --git a/library/ml/src/main/rust/shaders/conv_transpose.comp b/library/ml/src/main/rust/shaders/conv_transpose.compindex c8f71a2da2..82f3e97073 100644--- a/library/ml/src/main/rust/shaders/conv_transpose.comp+++ b/library/ml/src/main/rust/shaders/conv_transpose.comp@@ -60,5 +60,5 @@ void main() { } } - arena[p.out_at + index] = float16_t(activate(acc, p.act));+ arena[p.out_at + index] = float16_t(activate(acc, p.act, oc)); }
library/ml/src/main/rust/shaders/resize_nearest.comp
diff --git a/library/ml/src/main/rust/shaders/resize_nearest.comp b/library/ml/src/main/rust/shaders/resize_nearest.compnew file mode 100644index 0000000000..bdd7dd5f6a--- /dev/null+++ b/library/ml/src/main/rust/shaders/resize_nearest.comp@@ -0,0 +1,43 @@+#version 450+//! Nearest-neighbour resize, `asymmetric` coordinates and `floor` rounding. Two uses,+//! both SCRFD feature-pyramid upsamples.+//!+//! # Why this is not a flag on `resize.comp`+//!+//! The two conventions share no arithmetic. Bilinear `half_pixel` samples at+//! `(dst + 0.5) * in / out - 0.5` and blends four taps; this picks one tap at+//! `floor(dst * in / out)`. SCRFD's neck adds each upsampled level to a lateral+//! convolution of the level below, so running it through the bilinear kernel would+//! smear every one of those additions — an error that leaves the detector working and+//! quietly worse at small faces.+//!+//! # Exact in integers+//!+//! `asymmetric` with `floor` is `floor(dst * in / out)`, which for unsigned integers is+//! just `dst * in / out`. So there is no float here at all, and a 2x upsample lands+//! exactly on `dst / 2` rather than within a rounding error of it. `in_w` and `out_w`+//! are both at most a few thousand, so the product cannot overflow `uint`.++#include "common.glsl"++// The source index for `dst`, clamped. ONNX would never generate an out-of-range index+// for an upsample, but a downsample with a rounding quirk could, and a clamp is cheaper+// than reasoning about it.+uint nearest(uint dst, uint in_extent, uint out_extent) {+ return min(dst * in_extent / out_extent, in_extent - 1u);+}++void main() {+ uint index = global_index();+ if (index >= p.count) {+ return;+ }+ uint oc, oy, ox;+ unpack(index, oc, oy, ox);++ uint iy = nearest(oy, p.in_h, p.out_h);+ uint ix = nearest(ox, p.in_w, p.out_w);++ uint plane = p.in0 + oc * p.in_h * p.in_w;+ arena[p.out_at + index] = arena[plane + iy * p.in_w + ix];+}
library/ml/src/main/rust/src/bridge.rs
diff --git a/library/ml/src/main/rust/src/bridge.rs b/library/ml/src/main/rust/src/bridge.rsindex 64cacf5fbf..ad9f66f4bd 100644--- a/library/ml/src/main/rust/src/bridge.rs+++ b/library/ml/src/main/rust/src/bridge.rs@@ -189,7 +189,11 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskWidth return 0; } // SAFETY: as `segment`.- unsafe { &*(handle as *const Handle) }.net.output_size().0 as jint+ unsafe { &*(handle as *const Handle) }+ .net+ .output_size()+ .map(|(width, _)| width as jint)+ .unwrap_or(0) } /// The mask's height.@@ -207,7 +211,11 @@ pub unsafe extern "system" fn Java_com_vayunmathur_library_ml_MlNative_maskHeigh return 0; } // SAFETY: as `segment`.- unsafe { &*(handle as *const Handle) }.net.output_size().1 as jint+ unsafe { &*(handle as *const Handle) }+ .net+ .output_size()+ .map(|(_, height)| height as jint)+ .unwrap_or(0) } /// Free everything the handle owns, waiting for the GPU to go idle first.
library/ml/src/main/rust/src/nets/mod.rs
diff --git a/library/ml/src/main/rust/src/nets/mod.rs b/library/ml/src/main/rust/src/nets/mod.rsindex 1ed17a041c..e1a1d0d955 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -64,6 +64,10 @@ impl Shape { /// The activation a layer folds into its own store, saving a full pass over the /// output. U^2-Netp is 112 ReLUs over up to 6.5M elements each; not fusing them would /// roughly double its memory traffic.+///+/// Fusing is not merely an optimisation for [`Act::PRelu`]: MobileFaceNet's 34 `PRelu`+/// nodes each follow a `Conv` directly, so there is no shape of graph in which one+/// would need to stand alone. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Act { /// Store the accumulator as-is.@@ -74,6 +78,13 @@ pub enum Act { HardSwish, /// `1 / (1 + exp(-x))`. Sigmoid,+ /// ONNX `PRelu`: `x < 0 ? slope[c] * x : x`, one slope per output channel.+ ///+ /// Unlike the others this carries state — the slope's position in the `.vkml`+ /// tensor table, which [`Builder`] resolves to an offset like any other weight and+ /// passes down in [`Push::act_weight`]. A plain `Relu` is the same thing at slope+ /// zero, and is kept separate because it needs no memory traffic at all.+ PRelu(usize), } impl Act {@@ -83,6 +94,7 @@ impl Act { Act::Relu => 1, Act::HardSwish => 2, Act::Sigmoid => 3,+ Act::PRelu(_) => 4, } } }@@ -98,6 +110,13 @@ pub enum Kind { MaxPool, /// Bilinear resize, `half_pixel` coordinates. Resize,+ /// Nearest-neighbour resize, `asymmetric` coordinates and `floor` rounding.+ ///+ /// SCRFD's feature-pyramid upsamples are `mode=nearest`, which is a different+ /// pipeline rather than a flag on [`Kind::Resize`] because the two share no+ /// arithmetic: `src = floor(dst * in / out)` against `(dst + 0.5) * in / out - 0.5`.+ /// Running an FPN through the bilinear one blurs every lateral it adds.+ ResizeNearest, /// Mean over H and W, keeping C. The squeeze in a squeeze-excite block. GlobalAvgPool, /// Elementwise sum of two equal shapes.@@ -157,6 +176,9 @@ pub struct Push { pub group: u32, /// [`Act::code`]. pub act: u32,+ /// Element offset of the per-channel slope [`Act::PRelu`] reads, in the weights+ /// buffer. Zero and unread for every other activation.+ pub act_weight: u32, /// Output elements, so an over-dispatched workgroup can bail. pub count: u32, }@@ -189,6 +211,15 @@ pub enum Op { }, } +/// Where one of a net's inputs or outputs lives, and what shape it is.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Binding {+ /// Element offset in the activation arena.+ pub at: u32,+ /// The tensor's shape, so the host does not restate it.+ pub shape: Shape,+}+ /// A compiled forward pass: what to run, and how much scratch it needs. #[derive(Debug, PartialEq, Eq)] pub struct Plan {@@ -196,14 +227,35 @@ pub struct Plan { pub ops: Vec<Op>, /// Elements the activation arena must hold. pub arena_elems: u32,- /// Where the preprocessed input goes, in elements.- pub input: u32,- /// The input's shape, so preprocessing does not restate it.- pub input_shape: Shape,- /// Where the mask comes back from, in elements.- pub output: u32,- /// The output's shape.- pub output_shape: Shape,+ /// Where the preprocessed inputs go, in the order they were declared.+ ///+ /// A `Vec` rather than one binding because the models this runtime is growing into+ /// are not single-input: VITS's duration predictor takes three tensors and the+ /// SMaLL-100 decoder four. Both shipping nets declare exactly one.+ pub inputs: Vec<Binding>,+ /// Where the results come back from, in the order [`Builder::finish`] was given.+ ///+ /// 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>,+}++impl Plan {+ /// The only input, for the nets that have exactly one.+ pub fn input(&self) -> Result<Binding, String> {+ match self.inputs.as_slice() {+ [only] => Ok(*only),+ other => Err(format!("this net has {} inputs, not one", other.len())),+ }+ }++ /// The only output, for the nets that have exactly one.+ pub fn output(&self) -> Result<Binding, String> {+ match self.outputs.as_slice() {+ [only] => Ok(*only),+ other => Err(format!("this net has {} outputs, not one", other.len())),+ }+ } } /// Where a net's weights come from.@@ -248,6 +300,8 @@ enum Node { pad: (u32, u32), group: u32, act: Act,+ /// Resolved offset of [`Act::PRelu`]'s slope, zero otherwise.+ act_weight: u32, transpose: bool, }, MaxPool {@@ -259,6 +313,7 @@ enum Node { Resize { input: Id, out: Id,+ nearest: bool, }, GlobalAvgPool { input: Id,@@ -281,12 +336,14 @@ pub struct Builder<'a> { weights: &'a dyn WeightSource, shapes: Vec<Shape>, nodes: Vec<Node>,- /// Tensors that must keep a stable offset for the whole pass: the input and the- /// output. Everything else is free to be reused once its last reader has run.+ /// Tensors that must keep a stable offset for the whole pass: the inputs and the+ /// outputs. Everything else is free to be reused once its last reader has run. pinned: Vec<Id>, error: Option<String>,- input: Id,- input_shape: Shape,+ inputs: Vec<Id>,+ /// One flag per tensor in the file, set when the pass reads it. See+ /// [`Builder::finish`], which insists every one was.+ read: Vec<bool>, } /// Arena allocations are aligned to this many fp16 elements, i.e. 16 bytes — the same@@ -294,25 +351,28 @@ pub struct Builder<'a> { const ALIGN_ELEMS: u32 = 8; impl<'a> Builder<'a> {- /// Start a pass whose input is `shape`.- pub fn new(weights: &'a dyn WeightSource, shape: Shape) -> Builder<'a> {- let mut builder = Builder {+ /// Start recording a pass. Declare its inputs with [`Builder::input`].+ pub fn new(weights: &'a dyn WeightSource) -> Builder<'a> {+ Builder {+ read: vec![false; weights.count()], weights, shapes: Vec::new(), nodes: Vec::new(), pinned: Vec::new(), error: None,- input: Id(0),- input_shape: shape,- };- builder.input = builder.tensor(shape);- builder.pinned.push(builder.input);- builder+ inputs: Vec::new(),+ } } - /// The network's input tensor.- pub fn input(&self) -> Id {- self.input+ /// Declare an input of `shape`.+ ///+ /// Callable more than once, in which case [`Plan::inputs`] lists them in this+ /// order and the host must upload them in the same one.+ pub fn input(&mut self, shape: Shape) -> Id {+ let id = self.tensor(shape);+ self.inputs.push(id);+ self.pinned.push(id);+ id } fn tensor(&mut self, shape: Shape) -> Id {@@ -378,6 +438,7 @@ impl<'a> Builder<'a> { let (pad_t, pad_l, pad_b, pad_r) = pads; let out_h = conv_out(in_shape.h, kh, stride.0, dilation.0, pad_t + pad_b); let out_w = conv_out(in_shape.w, kw, stride.1, dilation.1, pad_l + pad_r);+ let act_weight = self.act_weight(act, m); let out = self.tensor(Shape::new(m, out_h, out_w)); self.nodes.push(Node::Conv { input,@@ -390,11 +451,21 @@ impl<'a> Builder<'a> { pad: (pad_t, pad_l), group, act,+ act_weight, transpose: false, }); out } + /// Resolve [`Act::PRelu`]'s slope tensor, which is `[channels, 1, 1]` in the ONNX+ /// exports this reads.+ fn act_weight(&mut self, act: Act, channels: u32) -> u32 {+ match act {+ Act::PRelu(index) => self.weight(index, &[channels, 1, 1]),+ _ => 0,+ }+ }+ /// The common case in both nets: `3x3` or `1x1`, stride 1, `pad == dilation` /// (which keeps the output size), one group. pub fn conv_same(@@ -442,6 +513,7 @@ impl<'a> Builder<'a> { let (pad_t, pad_l, pad_b, pad_r) = pads; let out_h = deconv_out(in_shape.h, kh, stride.0, pad_t + pad_b); let out_w = deconv_out(in_shape.w, kw, stride.1, pad_l + pad_r);+ let act_weight = self.act_weight(act, m); let out = self.tensor(Shape::new(m, out_h, out_w)); self.nodes.push(Node::Conv { input,@@ -454,12 +526,20 @@ impl<'a> Builder<'a> { pad: (pad_t, pad_l), group: 1, act,+ act_weight, transpose: true, }); out } fn weight(&mut self, index: usize, dims: &[u32]) -> u32 {+ match self.read.get_mut(index) {+ Some(slot) => *slot = true,+ None => self.fail(format!(+ "tensor {index}: the file holds {}",+ self.weights.count()+ )),+ } match self.weights.shaped(index, dims) { Ok(offset) => offset, Err(e) => {@@ -493,8 +573,8 @@ impl<'a> Builder<'a> { out } - /// Bilinear resize to `like`'s spatial size, which is how both nets always use it- /// — U^2-Net's `_upsample_like`, and the selfie net's decoder skips.+ /// Bilinear resize to `like`'s spatial size, which is how both shipping nets always+ /// use it — U^2-Net's `_upsample_like`, and the selfie net's decoder skips. pub fn resize_like(&mut self, input: Id, like: Id) -> Id { let target = self.shape_of(like); self.resize_to(input, target.h, target.w)@@ -504,7 +584,16 @@ impl<'a> Builder<'a> { pub fn resize_to(&mut self, input: Id, h: u32, w: u32) -> Id { let in_shape = self.shape_of(input); let out = self.tensor(Shape::new(in_shape.c, h, w));- self.nodes.push(Node::Resize { input, out });+ self.nodes.push(Node::Resize { input, out, nearest: false });+ out+ }++ /// Nearest-neighbour resize to `like`'s spatial size — SCRFD's two FPN upsamples.+ pub fn resize_nearest_like(&mut self, input: Id, like: Id) -> Id {+ let target = self.shape_of(like);+ let in_shape = self.shape_of(input);+ let out = self.tensor(Shape::new(in_shape.c, target.h, target.w));+ self.nodes.push(Node::Resize { input, out, nearest: true }); out } @@ -561,24 +650,26 @@ impl<'a> Builder<'a> { out } - /// Pack the arena and resolve every offset, with `output` as the result tensor.- pub fn finish(mut self, output: Id) -> Result<Plan, String> {- self.pinned.push(output);+ /// Pack the arena and resolve every offset, with `outputs` as the result tensors.+ pub fn finish(mut self, outputs: &[Id]) -> Result<Plan, String> {+ self.pinned.extend_from_slice(outputs); if let Some(e) = self.error.take() { return Err(e); }- let consumed = self.weights.count();- // Every tensor in the file must have been read. An unread tail is the shape- // of a forward pass that stopped early, which is otherwise invisible.- let read = self- .nodes- .iter()- .filter(|n| matches!(n, Node::Conv { .. }))- .count()- * 2;- if read != consumed {+ if self.inputs.is_empty() {+ return Err("a pass with no input".into());+ }+ if outputs.is_empty() {+ return Err("a pass with no output".into());+ }+ // Every tensor in the file must have been read. An unread one is the shape of a+ // forward pass that stopped early or skipped a layer, which is otherwise+ // invisible — the file loads, the pass runs, and one layer convolves with+ // whatever its neighbour's weights happen to be.+ if let Some(index) = self.read.iter().position(|&read| !read) { return Err(format!(- "the forward pass reads {read} tensors but the file holds {consumed}"+ "the forward pass never reads tensor {index} of {}",+ self.read.len() )); } @@ -625,23 +716,24 @@ impl<'a> Builder<'a> { } } - let input = offsets- .get(self.input.0)- .copied()- .flatten()- .ok_or("the input was never allocated")?;- let out_offset = offsets- .get(output.0)- .copied()- .flatten()- .ok_or("the output was never written")?;+ let binding = |id: Id| -> Result<Binding, String> {+ let at = offsets+ .get(id.0)+ .copied()+ .flatten()+ .ok_or_else(|| format!("tensor {} was never allocated", id.0))?;+ let shape = self+ .shapes+ .get(id.0)+ .copied()+ .ok_or_else(|| format!("tensor {} has no shape", id.0))?;+ Ok(Binding { at, shape })+ }; Ok(Plan { ops, arena_elems: arena.high_water,- input,- input_shape: self.input_shape,- output: out_offset,- output_shape: self.shapes.get(output.0).copied().ok_or("bad output id")?,+ inputs: self.inputs.iter().map(|&id| binding(id)).collect::<Result<_, _>>()?,+ outputs: outputs.iter().map(|&id| binding(id)).collect::<Result<_, _>>()?, }) } @@ -677,6 +769,7 @@ impl<'a> Builder<'a> { pad, group, act,+ act_weight, transpose, } => { let (si, so) = (shape(*input), shape(*out));@@ -703,6 +796,7 @@ impl<'a> Builder<'a> { pad_l: pad.1, group: *group, act: act.code(),+ act_weight: *act_weight, count: so.len(), ..Push::default() },@@ -732,10 +826,10 @@ impl<'a> Builder<'a> { invocations: so.len(), }); }- Node::Resize { input, out } => {+ Node::Resize { input, out, nearest } => { let (si, so) = (shape(*input), shape(*out)); ops.push(Op::Dispatch {- kind: Kind::Resize,+ kind: if *nearest { Kind::ResizeNearest } else { Kind::Resize }, push: Push { in0: at(*input)?, out: at(*out)?,@@ -1014,7 +1108,7 @@ pub(crate) mod tests { fn the_push_block_has_no_padding() { // The shaders read it at fixed offsets, so a gap Rust inserted would shift // every field after it.- assert_eq!(std::mem::size_of::<Push>(), 22 * 4);+ assert_eq!(std::mem::size_of::<Push>(), 23 * 4); assert_eq!(std::mem::align_of::<Push>(), 4); } @@ -1086,29 +1180,33 @@ pub(crate) mod tests { 2 } }- let mut builder = Builder::new(&Wrong, Shape::new(3, 8, 8));- let out = builder.conv_same(builder.input(), 0, 4, 3, 1, Act::Relu);- let error = builder.finish(out).expect_err("bad weights");+ let mut builder = Builder::new(&Wrong);+ let input = builder.input(Shape::new(3, 8, 8));+ let out = builder.conv_same(input, 0, 4, 3, 1, Act::Relu);+ let error = builder.finish(&[out]).expect_err("bad weights"); assert!(error.contains("tensor 0"), "{error}"); } #[test] fn a_pass_that_leaves_tensors_unread_fails_the_build() { let source = Shapes::new(4);- let mut builder = Builder::new(&source, Shape::new(3, 8, 8));- let out = builder.conv_same(builder.input(), 0, 4, 3, 1, Act::Relu);- let error = builder.finish(out).expect_err("short pass");- assert!(error.contains("reads 2 tensors but the file holds 4"), "{error}");+ let mut builder = Builder::new(&source);+ let input = builder.input(Shape::new(3, 8, 8));+ let out = builder.conv_same(input, 0, 4, 3, 1, Act::Relu);+ let error = builder.finish(&[out]).expect_err("short pass");+ // Named by index, not just counted: a pass that skipped a layer in the middle+ // reads the right *number* of tensors and the wrong ones.+ assert!(error.contains("never reads tensor 2 of 4"), "{error}"); } #[test] fn concat_lowers_to_contiguous_copies_and_no_shader() { let source = Shapes::new(0);- let mut builder = Builder::new(&source, Shape::new(2, 2, 2));- let a = builder.input();+ let mut builder = Builder::new(&source);+ let a = builder.input(Shape::new(2, 2, 2)); let b = builder.resize_to(a, 2, 2); let joined = builder.concat(&[a, b]);- let plan = builder.finish(joined).expect("builds");+ let plan = builder.finish(&[joined]).expect("builds"); let copies: Vec<&Op> = plan.ops.iter().filter(|o| matches!(o, Op::Copy { .. })).collect(); assert_eq!(copies.len(), 2); // The second part lands exactly one part's worth of elements after the first:
library/ml/src/main/rust/src/nets/reference.rs
diff --git a/library/ml/src/main/rust/src/nets/reference.rs b/library/ml/src/main/rust/src/nets/reference.rsindex 95c386493a..527eca0d8c 100644--- a/library/ml/src/main/rust/src/nets/reference.rs+++ b/library/ml/src/main/rust/src/nets/reference.rs@@ -53,14 +53,26 @@ mod act { pub const HARDSWISH: u32 = 2; /// The logistic function. pub const SIGMOID: u32 = 3;+ /// `x < 0 ? slope[c] * x : x`.+ pub const PRELU: u32 = 4; } /// The fused activation, mirroring `activate` in `common.glsl`.-fn activate(x: f32, kind: u32) -> f32 {+///+/// `slope` is the PReLU coefficient for this output channel, already fetched; the+/// others ignore it.+fn activate(x: f32, kind: u32, slope: f32) -> f32 { match kind { act::RELU => x.max(0.0), act::HARDSWISH => x * (x * (1.0 / 6.0) + 0.5).clamp(0.0, 1.0), act::SIGMOID => 1.0 / (1.0 + (-x).exp()),+ act::PRELU => {+ if x < 0.0 {+ x * slope+ } else {+ x+ }+ } _ => x, } }@@ -70,16 +82,32 @@ fn through_f16(value: f32) -> f32 { f16_to_f32(f32_to_f16(value)) } -/// Run `plan` on the host and return its output.+/// Run `plan` on the host and return its outputs, in [`Plan::outputs`] order. /// /// `weights` is the `.vkml` data section verbatim — the same bytes the device gets — /// so this accepts [`crate::weights::Weights::data`] and a shipped asset directly.-/// `input` is fp32 in the plan's input shape; it is rounded to fp16 on the way in,-/// exactly as an upload would.-pub fn run(plan: &Plan, weights: &[u8], input: &[f32]) -> Result<Vec<f32>, String> {- let mut reference = Reference::new(plan, weights, input)?;+/// `inputs` is one fp32 slice per [`Plan::inputs`] entry; each is rounded to fp16 on+/// the way in, exactly as an upload would.+pub fn run_multi(+ plan: &Plan,+ weights: &[u8],+ inputs: &[&[f32]],+) -> Result<Vec<Vec<f32>>, String> {+ let mut reference = Reference::new(plan, weights, inputs)?; reference.execute(plan)?;- reference.read(plan.output, plan.output_shape.len())+ plan.outputs+ .iter()+ .map(|out| reference.read(out.at, out.shape.len()))+ .collect()+}++/// [`run_multi`] for the single-input, single-output nets.+pub fn run(plan: &Plan, weights: &[u8], input: &[f32]) -> Result<Vec<f32>, String> {+ let outputs = run_multi(plan, weights, &[input])?;+ match <[Vec<f32>; 1]>::try_from(outputs) {+ Ok([only]) => Ok(only),+ Err(other) => Err(format!("this net has {} outputs, not one", other.len())),+ } } /// A host execution of a [`Plan`]: the activation arena, and the weights it reads.@@ -93,12 +121,12 @@ pub struct Reference { } impl Reference {- fn new(plan: &Plan, weights: &[u8], input: &[f32]) -> Result<Reference, String> {- if input.len() != plan.input_shape.len() as usize {+ fn new(plan: &Plan, weights: &[u8], inputs: &[&[f32]]) -> Result<Reference, String> {+ if inputs.len() != plan.inputs.len() { return Err(format!(- "{} input values for {:?}",- input.len(),- plan.input_shape+ "{} input slices for a net with {} inputs",+ inputs.len(),+ plan.inputs.len() )); } if !weights.len().is_multiple_of(2) {@@ -114,8 +142,17 @@ impl Reference { let mut reference = Reference { arena: vec![0.0; plan.arena_elems as usize], weights: decoded };- for (i, &value) in input.iter().enumerate() {- reference.store(plan.input, i as u32, value)?;+ for (binding, values) in plan.inputs.iter().zip(inputs) {+ if values.len() != binding.shape.len() as usize {+ return Err(format!(+ "{} input values for {:?}",+ values.len(),+ binding.shape+ ));+ }+ for (i, &value) in values.iter().enumerate() {+ reference.store(binding.at, i as u32, value)?;+ } } Ok(reference) }@@ -130,6 +167,7 @@ impl Reference { Kind::ConvTranspose => self.conv_transpose(push), Kind::MaxPool => self.max_pool(push), Kind::Resize => self.resize(push),+ Kind::ResizeNearest => self.resize_nearest(push), Kind::GlobalAvgPool => self.global_avg_pool(push), Kind::Add => self.add(push), Kind::MulBroadcast => self.mul_broadcast(push),@@ -195,6 +233,7 @@ impl Reference { for oc in 0..p.out_c { let first_in = (oc / out_per_group) * in_per_group; let kernel_at = p.weight + oc * in_per_group * p.kh * p.kw;+ let slope = self.slope(p, oc)?; for oy in 0..p.out_h { for ox in 0..p.out_w { let mut acc = self.weight(p.bias, oc)?;@@ -218,13 +257,22 @@ impl Reference { } } }- self.store(p.out, nchw(p, oc, oy, ox), activate(acc, p.act))?;+ self.store(p.out, nchw(p, oc, oy, ox), activate(acc, p.act, slope))?; } } } Ok(()) } + /// The PReLU slope for output channel `c`, or zero when the activation is not PReLU.+ fn slope(&self, p: &Push, c: u32) -> Result<f32, String> {+ if p.act == act::PRELU {+ self.weight(p.act_weight, c)+ } else {+ Ok(0.0)+ }+ }+ /// Transposed convolution: ONNX semantics, weights `[in_c, out_c / group, kh, kw]`. /// /// Note the layout: input channels are outermost here and outermost-but-one in@@ -239,6 +287,7 @@ impl Reference { return Err(format!("a transposed convolution in {} groups", p.group)); } for oc in 0..p.out_c {+ let slope = self.slope(p, oc)?; for oy in 0..p.out_h { for ox in 0..p.out_w { let mut acc = self.weight(p.bias, oc)?;@@ -261,7 +310,7 @@ impl Reference { } } }- self.store(p.out, nchw(p, oc, oy, ox), activate(acc, p.act))?;+ self.store(p.out, nchw(p, oc, oy, ox), activate(acc, p.act, slope))?; } } }@@ -323,6 +372,29 @@ impl Reference { Ok(()) } + /// Nearest-neighbour resize, ONNX `asymmetric` coordinates with `floor` rounding:+ /// `src = floor(dst * in / out)`, which in integers is an exact division.+ ///+ /// SCRFD's feature pyramid, and deliberately a different function from+ /// [`Reference::resize`] rather than a mode flag — the two agree nowhere.+ fn resize_nearest(&mut self, p: &Push) -> Result<(), String> {+ if p.out_h == 0 || p.out_w == 0 || p.in_h == 0 || p.in_w == 0 {+ return Err("a resize of a zero extent".into());+ }+ for oc in 0..p.out_c {+ let plane = oc * p.in_h * p.in_w;+ for oy in 0..p.out_h {+ let iy = (oy * p.in_h / p.out_h).min(p.in_h - 1);+ for ox in 0..p.out_w {+ let ix = (ox * p.in_w / p.out_w).min(p.in_w - 1);+ let value = self.load(p.in0, plane + iy * p.in_w + ix)?;+ self.store(p.out, nchw(p, oc, oy, ox), value)?;+ }+ }+ }+ Ok(())+ }+ /// Mean over H and W, to `C x 1 x 1`. ONNX `ReduceMean` over axes `[2, 3]`. fn global_avg_pool(&mut self, p: &Push) -> Result<(), String> { let elements = p.in_h * p.in_w;@@ -597,10 +669,10 @@ mod tests { record: impl FnOnce(&mut Builder, Id) -> Id, ) -> Vec<f32> { let given = Given::new(tensors).expect("the fixture tensors are consistent");- let mut builder = Builder::new(&given, input_shape);- let first = builder.input();+ let mut builder = Builder::new(&given);+ let first = builder.input(input_shape); let last = record(&mut builder, first);- let plan = builder.finish(last).expect("the fixture plan builds");+ let plan = builder.finish(&[last]).expect("the fixture plan builds"); run(&plan, given.data(), input).expect("the fixture plan runs") } @@ -790,6 +862,111 @@ mod tests { assert_eq!(Act::Sigmoid.code(), act::SIGMOID); } + #[test]+ fn prelu_scales_only_the_negative_side_and_per_channel() {+ // Two channels with different slopes, so a PReLU that read one slope for the+ // whole tensor — or indexed it by element instead of by channel — is visible.+ // Slopes 0.25 and 4.0; inputs -2 and 3 in each channel.+ let got = one(+ Shape::new(2, 1, 2),+ &[-2.0, 3.0, -2.0, 3.0],+ &[+ (vec![2, 1, 1, 1], vec![1.0, 1.0]),+ (vec![2], vec![0.0, 0.0]),+ (vec![2, 1, 1], vec![0.25, 4.0]),+ ],+ |b, x| {+ b.conv(x, 0, 2, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 2, Act::PRelu(2))+ },+ );+ close(&got, &[-0.5, 3.0, -8.0, 3.0]);+ }++ #[test]+ fn prelu_at_slope_one_is_the_identity_and_at_zero_is_relu() {+ // The two degenerate slopes, which pin the sign convention: a shader that+ // scaled the positive side instead would pass the identity case and fail this.+ let got = one(+ Shape::new(2, 1, 2),+ &[-4.0, 4.0, -4.0, 4.0],+ &[+ (vec![2, 1, 1, 1], vec![1.0, 1.0]),+ (vec![2], vec![0.0, 0.0]),+ (vec![2, 1, 1], vec![1.0, 0.0]),+ ],+ |b, x| {+ b.conv(x, 0, 2, (1, 1), (1, 1), (1, 1), (0, 0, 0, 0), 2, Act::PRelu(2))+ },+ );+ close(&got, &[-4.0, 4.0, 0.0, 4.0]);+ }++ #[test]+ fn a_nearest_resize_repeats_each_source_pixel_rather_than_blending() {+ // Two columns to four, `asymmetric` + `floor`: src = floor(dst * 2 / 4) = dst/2,+ // so 0, 0, 1, 1. The bilinear kernel gives 0, 1, 3, 4 for the same input, which+ // is what makes this the discriminating fixture.+ let got = one(Shape::new(1, 1, 2), &[0.0, 4.0], &[], |b, x| {+ let like = b.resize_to(x, 1, 4);+ b.resize_nearest_like(x, like)+ });+ close(&got, &[0.0, 0.0, 4.0, 4.0]);+ }++ #[test]+ fn a_nearest_resize_upsamples_both_axes_together() {+ // A 2x2 doubled to 4x4. Each source pixel becomes a 2x2 block, so a row/column+ // transposition in the index arithmetic changes the answer.+ let got = one(Shape::new(1, 2, 2), &[1.0, 2.0, 3.0, 4.0], &[], |b, x| {+ let like = b.resize_to(x, 4, 4);+ b.resize_nearest_like(x, like)+ });+ close(+ &got,+ &[+ 1.0, 1.0, 2.0, 2.0, //+ 1.0, 1.0, 2.0, 2.0, //+ 3.0, 3.0, 4.0, 4.0, //+ 3.0, 3.0, 4.0, 4.0,+ ],+ );+ }++ #[test]+ fn a_plan_can_declare_more_than_one_input_and_output() {+ // SCRFD needs nine outputs and the VITS duration predictor three inputs, so the+ // plan's bindings are lists. This checks both ends: two inputs land at distinct+ // arena offsets, and two outputs come back in the order `finish` was given.+ let given = Given::new(&[]).expect("no tensors");+ let mut b = Builder::new(&given);+ let first = b.input(Shape::new(1, 1, 2));+ let second = b.input(Shape::new(1, 1, 2));+ let sum = b.add(first, second);+ let doubled = b.add(sum, sum);+ let plan = b.finish(&[doubled, sum]).expect("builds");++ assert_eq!(plan.inputs.len(), 2);+ assert_ne!(+ plan.inputs.first().map(|b| b.at),+ plan.inputs.get(1).map(|b| b.at),+ "the two inputs share an offset"+ );+ let got = run_multi(&plan, given.data(), &[&[1.0, 2.0], &[10.0, 20.0]])+ .expect("the two-input plan runs");+ assert_eq!(got, vec![vec![22.0, 44.0], vec![11.0, 22.0]]);+ }++ #[test]+ fn a_single_output_helper_refuses_a_multi_output_plan() {+ let given = Given::new(&[]).expect("no tensors");+ let mut b = Builder::new(&given);+ let first = b.input(Shape::new(1, 1, 1));+ let same = b.add(first, first);+ let plan = b.finish(&[same, first]).expect("builds");+ let error = run(&plan, given.data(), &[1.0]).expect_err("two outputs");+ assert!(error.contains("2 outputs"), "{error}");+ }+ #[test] fn relu_clamps_at_zero_without_touching_positives() { let got = one(@@ -842,9 +1019,10 @@ mod tests { #[test] fn a_mismatched_input_length_is_refused_rather_than_padded() { let given = Given::new(&[]).expect("no tensors");- let mut builder = Builder::new(&given, Shape::new(1, 2, 2));- let out = builder.resize_to(builder.input(), 2, 2);- let plan = builder.finish(out).expect("builds");+ let mut builder = Builder::new(&given);+ let input = builder.input(Shape::new(1, 2, 2));+ let out = builder.resize_to(input, 2, 2);+ let plan = builder.finish(&[out]).expect("builds"); let error = run(&plan, given.data(), &[1.0, 2.0]).expect_err("too few values"); assert!(error.contains("2 input values"), "{error}"); }@@ -854,8 +1032,9 @@ mod tests { /// This is what keeps the interpreter itself honest on every `cargo test`: the two /// real nets below are hundreds of times larger and have to be opted into. fn miniature(weights: &dyn WeightSource) -> Result<Plan, String> {- let mut b = Builder::new(weights, Shape::new(3, 8, 8));- let x = b.conv(b.input(), 0, 8, (3, 3), (2, 2), (1, 1), (0, 0, 1, 1), 1, Act::HardSwish);+ let mut b = Builder::new(weights);+ let first = b.input(Shape::new(3, 8, 8));+ let x = b.conv(first, 0, 8, (3, 3), (2, 2), (1, 1), (0, 0, 1, 1), 1, Act::HardSwish); let pooled = b.global_avg_pool(x); let gate = b.conv_same(pooled, 2, 8, 1, 1, Act::Sigmoid); let gated = b.mul_channel(x, gate);@@ -865,7 +1044,7 @@ mod tests { let merged = b.add(gated, up); let joined = b.concat(&[merged, up]); let out = b.conv_transpose(joined, 6, 1, (2, 2), (2, 2), (0, 0, 0, 0), Act::Sigmoid);- b.finish(out)+ b.finish(&[out]) } #[test]@@ -873,12 +1052,12 @@ mod tests { let source = Invented::new(8); let plan = miniature(&source).expect("the miniature net builds"); let data = source.into_data();- let input: Vec<f32> = (0..plan.input_shape.len())+ let input: Vec<f32> = (0..plan.input().expect("one input").shape.len()) .map(|i| (i as f32 * 0.37).sin()) .collect(); let got = run(&plan, &data, &input).expect("the miniature net runs"); - assert_eq!(got.len(), plan.output_shape.len() as usize);+ assert_eq!(got.len(), plan.output().expect("one output").shape.len() as usize); // A sigmoid output, so every value is a probability. A NaN or an fp16 overflow // anywhere upstream lands outside this. for (i, &value) in got.iter().enumerate() {@@ -894,7 +1073,7 @@ mod tests { let source = Invented::new(8); let plan = miniature(&source).expect("builds"); let data = source.into_data();- let input = vec![0.25; plan.input_shape.len() as usize];+ let input = vec![0.25; plan.input().expect("one input").shape.len() as usize]; assert_eq!( run(&plan, &data, &input).expect("first run"), run(&plan, &data, &input).expect("second run")@@ -997,11 +1176,12 @@ mod tests { /// `tests/assets.rs` prints its memory figures: the numbers are what a reviewer /// wants to see, and pinning them would pin this runtime's fp16 rounding. fn assert_usable_mask(name: &str, plan: &Plan, weights: &[u8]) {- let inputs = [("ramp", ramp(plan.input_shape)), ("blob", blob(plan.input_shape))];+ let shape = plan.input().expect("one input").shape;+ let inputs = [("ramp", ramp(shape)), ("blob", blob(shape))]; let mut masks = Vec::new(); for (label, input) in &inputs { let mask = run(plan, weights, input).unwrap_or_else(|e| panic!("{name}/{label}: {e}"));- assert_eq!(mask.len(), plan.output_shape.len() as usize);+ assert_eq!(mask.len(), plan.output().expect("one output").shape.len() as usize); for (i, &value) in mask.iter().enumerate() { assert!( value.is_finite() && (0.0..=1.0).contains(&value),@@ -1049,7 +1229,10 @@ mod tests { let weights = crate::weights::Weights::parse(&bytes, crate::weights::graph::SELFIE) .expect("the shipped selfie asset parses"); let plan = selfie::build(&weights).expect("selfie builds");- assert_eq!(plan.output_shape, Shape::new(1, selfie::SIZE, selfie::SIZE));+ assert_eq!(+ plan.output().expect("one output").shape,+ Shape::new(1, selfie::SIZE, selfie::SIZE)+ ); assert_usable_mask("selfie", &plan, weights.data()); } @@ -1062,7 +1245,10 @@ mod tests { let weights = crate::weights::Weights::parse(&bytes, crate::weights::graph::U2NETP) .expect("the shipped u2netp asset parses"); let plan = u2netp::build(&weights).expect("u2netp builds");- assert_eq!(plan.output_shape, Shape::new(1, u2netp::SIZE, u2netp::SIZE));+ assert_eq!(+ plan.output().expect("one output").shape,+ Shape::new(1, u2netp::SIZE, u2netp::SIZE)+ ); assert_usable_mask("u2netp", &plan, weights.data()); } }
library/ml/src/main/rust/src/nets/selfie.rs
diff --git a/library/ml/src/main/rust/src/nets/selfie.rs b/library/ml/src/main/rust/src/nets/selfie.rsindex 7ab1439a7d..aa3fc7f607 100644--- a/library/ml/src/main/rust/src/nets/selfie.rs+++ b/library/ml/src/main/rust/src/nets/selfie.rs@@ -128,10 +128,10 @@ fn final_block(b: &mut Builder, layers: &mut Layers, deep: Id, skip: Id, channel /// Compile the whole forward pass. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {- let mut b = Builder::new(weights, Shape::new(3, SIZE, SIZE));+ let mut b = Builder::new(weights); let mut layers = Layers { next: 0 }; let l = &mut layers;- let input = b.input();+ let input = b.input(Shape::new(3, SIZE, SIZE)); // Stem. `pads = [0, 0, 1, 1]` on all three strided 3x3s: no padding above or left. // 256 -> 128 -> 64 -> 32.@@ -181,7 +181,7 @@ pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> { // 128 -> 256, and the sigmoid that makes it an alpha. let alphas = b.conv_transpose(x, l.take(), 1, (2, 2), (2, 2), (0, 0, 0, 0), Act::Sigmoid);- b.finish(alphas)+ b.finish(&[alphas]) } #[cfg(test)]@@ -257,8 +257,8 @@ mod tests { #[test] fn the_input_and_output_are_the_shapes_kotlin_expects() { let plan = plan();- assert_eq!(plan.input_shape, Shape::new(3, SIZE, SIZE));- assert_eq!(plan.output_shape, Shape::new(1, SIZE, SIZE));+ assert_eq!(plan.input().expect("one input").shape, Shape::new(3, SIZE, SIZE));+ assert_eq!(plan.output().expect("one output").shape, Shape::new(1, SIZE, SIZE)); } #[test]
library/ml/src/main/rust/src/nets/u2netp.rs
diff --git a/library/ml/src/main/rust/src/nets/u2netp.rs b/library/ml/src/main/rust/src/nets/u2netp.rsindex 8e2ea4ef3f..b6143abfc7 100644--- a/library/ml/src/main/rust/src/nets/u2netp.rs+++ b/library/ml/src/main/rust/src/nets/u2netp.rs@@ -226,12 +226,12 @@ fn rsu4f(b: &mut Builder, layers: &mut Layers, x: Id) -> Id { /// Of the seven outputs the ONNX declares — the fused `d0` and the six per-scale side /// maps — only `d0` is produced. `MlSegmentation.kt` never read the others. pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> {- let mut b = Builder::new(weights, Shape::new(3, SIZE, SIZE));+ let mut b = Builder::new(weights); let mut layers = Layers { next: 0 }; let l = &mut layers; // Encoder. Each stage halves the resolution: 320, 160, 80, 40, 20, 10.- let input = b.input();+ let input = b.input(Shape::new(3, SIZE, SIZE)); let hx1 = rsu7(&mut b, l, input); let hx = b.max_pool_2x2(hx1); let hx2 = rsu6(&mut b, l, hx);@@ -275,7 +275,7 @@ pub fn build(weights: &dyn WeightSource) -> Result<Plan, String> { let fused = b.concat(&sides); let d0 = b.conv_same(fused, l.take(), 1, 1, 1, Act::Sigmoid); - b.finish(d0)+ b.finish(&[d0]) } #[cfg(test)]@@ -359,8 +359,8 @@ mod tests { #[test] fn the_input_and_output_are_the_shapes_kotlin_expects() { let plan = plan();- assert_eq!(plan.input_shape, Shape::new(3, SIZE, SIZE));- assert_eq!(plan.output_shape, Shape::new(1, SIZE, SIZE));+ assert_eq!(plan.input().expect("one input").shape, Shape::new(3, SIZE, SIZE));+ assert_eq!(plan.output().expect("one output").shape, Shape::new(1, SIZE, SIZE)); } #[test]
library/ml/src/main/rust/src/vulkan/pipeline.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline.rs b/library/ml/src/main/rust/src/vulkan/pipeline.rsindex 03dde0d6f5..e7548f73e8 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -1,4 +1,4 @@-//! The seven compute pipelines, and the one descriptor set they all share.+//! The eight compute pipelines, and the one descriptor set they all share. //! //! # One layout, one descriptor set, written once //!@@ -29,6 +29,8 @@ const CONV_TRANSPOSE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv_transpose.comp.spv")); const MAXPOOL: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/maxpool.comp.spv")); const RESIZE: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/resize.comp.spv"));+const RESIZE_NEAREST: &[u8] =+ include_bytes!(concat!(env!("OUT_DIR"), "/resize_nearest.comp.spv")); const GAP: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/gap.comp.spv")); const ADD: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/add.comp.spv")); const MUL_BCAST: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/mul_bcast.comp.spv"));@@ -48,7 +50,7 @@ pub const MAX_WORKGROUPS_PER_DIM: u32 = 65_535; /// Every compute pipeline, plus the layout and descriptor set they share. pub struct Pipelines {- /// Shared by all seven, so a bind never invalidates push constants.+ /// Shared by all eight, so a bind never invalidates push constants. pub layout: vk::PipelineLayout, /// The one set: arena at binding 0, weights at binding 1. pub descriptor_set: vk::DescriptorSet,@@ -58,13 +60,14 @@ pub struct Pipelines { conv_transpose: vk::Pipeline, maxpool: vk::Pipeline, resize: vk::Pipeline,+ resize_nearest: vk::Pipeline, gap: vk::Pipeline, add: vk::Pipeline, mul_bcast: vk::Pipeline, } impl Pipelines {- /// Build all seven and point the descriptor set at `arena` and `weights`.+ /// Build all eight and point the descriptor set at `arena` and `weights`. pub fn new( context: &Context, arena: vk::Buffer,@@ -169,7 +172,7 @@ impl Pipelines { cleanup.layout = Some(layout); let mut built = Vec::new();- for spirv in [CONV, CONV_TRANSPOSE, MAXPOOL, RESIZE, GAP, ADD, MUL_BCAST] {+ for spirv in [CONV, CONV_TRANSPOSE, MAXPOOL, RESIZE, RESIZE_NEAREST, GAP, ADD, MUL_BCAST] { match compute_pipeline(device, layout, spirv) { Ok(pipeline) => built.push(pipeline), Err(e) => {@@ -180,10 +183,11 @@ impl Pipelines { } } }- let [conv, conv_transpose, maxpool, resize, gap, add, mul_bcast] = match built.as_slice() {- [a, b, c, d, e, f, g] => [*a, *b, *c, *d, *e, *f, *g],- _ => return Err("wrong pipeline count".into()),- };+ let [conv, conv_transpose, maxpool, resize, resize_nearest, gap, add, mul_bcast] =+ match built.as_slice() {+ [a, b, c, d, e, f, g, h] => [*a, *b, *c, *d, *e, *f, *g, *h],+ _ => return Err("wrong pipeline count".into()),+ }; cleanup.disarm(); Ok(Pipelines {@@ -195,6 +199,7 @@ impl Pipelines { conv_transpose, maxpool, resize,+ resize_nearest, gap, add, mul_bcast,@@ -208,6 +213,7 @@ impl Pipelines { Kind::ConvTranspose => self.conv_transpose, Kind::MaxPool => self.maxpool, Kind::Resize => self.resize,+ Kind::ResizeNearest => self.resize_nearest, Kind::GlobalAvgPool => self.gap, Kind::Add => self.add, Kind::MulBroadcast => self.mul_bcast,@@ -223,6 +229,7 @@ impl Pipelines { self.conv_transpose, self.maxpool, self.resize,+ self.resize_nearest, self.gap, self.add, self.mul_bcast,
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 87efe72bb7..8d44f354f7 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -80,10 +80,11 @@ impl Net { ) -> Result<Net, String> { let arena_bytes = (plan.arena_elems as vk::DeviceSize) * 2; let weights_bytes = weights.data().len() as vk::DeviceSize;- let input_elems = plan.input_shape.len() as usize;- let output_elems = plan.output_shape.len() as usize;- // One staging buffer for both directions: the input and the output are never in- // flight at the same time, because an inference is a single blocking submit.+ 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+ // flight at the same time, because an inference is a single blocking submit. Each+ // side packs its bindings end to end from offset 0, in declaration order. let staging_bytes = (input_elems.max(output_elems) as vk::DeviceSize) * 2; let weights_buffer = Buffer::device_local(&context, weights_bytes)?;@@ -224,17 +225,24 @@ impl Net { &[], ); - let input_bytes = (self.plan.input_shape.len() as vk::DeviceSize) * 2;- let region = vk::BufferCopy::default()- .src_offset(0)- .dst_offset((self.plan.input as vk::DeviceSize) * 2)- .size(input_bytes);- device.cmd_copy_buffer(- buffer,- self.staging.buffer,- self.arena.buffer,- std::slice::from_ref(®ion),- );+ // One copy per input, packed end to end in the staging buffer in declaration+ // order. Both shipping nets have exactly one; SCRFD's nine outputs come back+ // the same way below.+ let mut staged = 0u64;+ for input in &self.plan.inputs {+ let bytes = (input.shape.len() as vk::DeviceSize) * 2;+ let region = vk::BufferCopy::default()+ .src_offset(staged)+ .dst_offset((input.at as vk::DeviceSize) * 2)+ .size(bytes);+ device.cmd_copy_buffer(+ buffer,+ self.staging.buffer,+ self.arena.buffer,+ std::slice::from_ref(®ion),+ );+ staged += bytes;+ } self.barrier(buffer); for op in &self.plan.ops {@@ -292,17 +300,21 @@ impl Net { self.barrier(buffer); } - let output_bytes = (self.plan.output_shape.len() as vk::DeviceSize) * 2;- let region = vk::BufferCopy::default()- .src_offset((self.plan.output as vk::DeviceSize) * 2)- .dst_offset(0)- .size(output_bytes);- device.cmd_copy_buffer(- buffer,- self.arena.buffer,- self.staging.buffer,- std::slice::from_ref(®ion),- );+ let mut read_back = 0u64;+ for output in &self.plan.outputs {+ let bytes = (output.shape.len() as vk::DeviceSize) * 2;+ let region = vk::BufferCopy::default()+ .src_offset((output.at as vk::DeviceSize) * 2)+ .dst_offset(read_back)+ .size(bytes);+ device.cmd_copy_buffer(+ buffer,+ self.arena.buffer,+ self.staging.buffer,+ std::slice::from_ref(®ion),+ );+ read_back += bytes;+ } // Waiting on a fence makes the copy's writes *available*, but the device-to-host // domain operation still needs a memory dependency naming HOST_READ — and@@ -401,6 +413,10 @@ impl Net { /// /// `pixels` is `ARGB_8888` as `Bitmap.getPixels` produces it. The returned mask is /// `output_shape.h * output_shape.w` long, row-major.+ ///+ /// Single-input, single-output: this is the bitmap-in, mask-out path both shipping+ /// nets use, and it refuses a plan shaped otherwise rather than silently reading only+ /// the first binding. pub fn infer( &mut self, pixels: &[i32],@@ -410,11 +426,16 @@ impl Net { if self.poisoned { return Err("a previous submission timed out; this network is unusable".into()); }+ let input = self.plan.input()?;+ // Reject a multi-output plan here rather than returning only the first binding:+ // `output_scratch` spans every output, so the concatenation would look like a+ // mask of the wrong size instead of an error.+ let _single_output = self.plan.output()?; preprocess::to_planar_f16( pixels, width, height,- self.plan.input_shape,+ input.shape, &self.normalise, &mut self.input_scratch, )?;@@ -459,11 +480,17 @@ impl Net { } /// The mask's dimensions, which is what the Kotlin wrapper reports to its caller.- pub fn output_size(&self) -> (u32, u32) {- (self.plan.output_shape.w, self.plan.output_shape.h)+ pub fn output_size(&self) -> Result<(u32, u32), String> {+ let output = self.plan.output()?;+ Ok((output.shape.w, output.shape.h)) } } +/// Total elements across `bindings`, which is how much staging space one direction needs.+fn binding_elems(bindings: &[crate::nets::Binding]) -> usize {+ bindings.iter().map(|b| b.shape.len() as usize).sum()+}+ /// Long enough that a slow first dispatch on a cold driver is not mistaken for a hang, /// short enough that a genuinely hung GPU does not block a UI thread forever. `:camera` /// runs this on a dedicated executor, `:photos` on its own thread, so neither blocks the