library:ml: window the weights buffer under maxStorageBufferRange
- Commit
1fdab1f4b44fa3785f56571e6308c19774558f4e- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-29 03:01 UTC (3 months ago)
- Parents
2ae5869
Diff
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 3ace3e1a51..6e7499d7e1 100644--- a/library/ml/src/main/rust/src/nets/mod.rs+++ b/library/ml/src/main/rust/src/nets/mod.rs@@ -417,6 +417,85 @@ pub enum Op { }, } +/// One weights-buffer byte offset an [`Op::Dispatch`] reads a tensor from.+///+/// Exists because `vulkan::segment` has to know which region of the weights file each op+/// touches, and the answer is a property of the *shaders* rather than of segmentation: three+/// of [`Push`]'s fields hold weights offsets, and which of them a shader reads — and in what+/// units — depends on the [`Kind`]. Keeping the table here means it sits beside the fields it+/// describes and beside `tests::assert_no_aliasing`, which does the same job for the arena.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct WeightRead {+ /// Byte offset into the `.maml` data section.+ pub at: u64,+ /// Which [`Push`] field it came from, for error messages.+ pub field: &'static str,+}++impl Kind {+ /// Every weights offset this kind reads, in bytes, given one op's [`Push`].+ ///+ /// Read off the shaders rather than inferred: `shaders/*.comp` name `p.weight`, `p.bias` and+ /// `p.act_weight` explicitly, and `prelu` in `common.glsl` is what makes `act_weight` a read+ /// of any kind carrying [`Act::PRelu`] rather than only of the int8 pair.+ ///+ /// Bytes, not element indices, because `weight` is a **32-bit word** index for the two int8+ /// kinds and an fp16 element index everywhere else — the one place that difference has to be+ /// resolved rather than carried.+ pub fn weight_reads(self, push: &Push) -> Vec<WeightRead> {+ let elems = |at: u32| u64::from(at) * 2;+ let words = |at: u32| u64::from(at) * 4;+ let mut reads = Vec::new();+ match self {+ // A kernel, a bias, and a per-channel slope when the activation is PRelu.+ Kind::Conv | Kind::ConvTranspose | Kind::ConvPoint => {+ reads.push(WeightRead { at: elems(push.weight), field: "weight" });+ reads.push(WeightRead { at: elems(push.bias), field: "bias" });+ }+ // As above, plus the dequantisation scale, which occupies `act_weight` and is why+ // `Builder::conv_int8` refuses `Act::PRelu`.+ Kind::ConvInt8 | Kind::ConvPointInt8 => {+ reads.push(WeightRead { at: words(push.weight), field: "weight" });+ reads.push(WeightRead { at: elems(push.bias), field: "bias" });+ reads.push(WeightRead { at: elems(push.act_weight), field: "act_weight" });+ }+ // Gamma then beta, both rank-1.+ Kind::LayerNorm => {+ reads.push(WeightRead { at: elems(push.weight), field: "weight" });+ reads.push(WeightRead { at: elems(push.bias), field: "bias" });+ }+ // One table each: the relative position table, the literal to copy out, the+ // embedding rows.+ Kind::AttnScoresRelative | Kind::AttnApplyRelative | Kind::Constant | Kind::Embed => {+ reads.push(WeightRead { at: elems(push.weight), field: "weight" });+ }+ // Purely elementwise or arena-only. `attn_scores`, `softmax`, `attn_apply` and+ // `rotary` all take their second operand from the arena.+ Kind::MaxPool+ | Kind::AvgPool+ | Kind::Resize+ | Kind::ResizeNearest+ | Kind::GlobalAvgPool+ | Kind::Add+ | Kind::MulBroadcast+ | Kind::AddBroadcast+ | Kind::Mul+ | Kind::Affine+ | Kind::AttnScores+ | Kind::Softmax+ | Kind::AttnApply+ | Kind::Rotary => {}+ }+ if !reads.is_empty() && push.act == Act::PRelu(0).code() {+ let slope = WeightRead { at: elems(push.act_weight), field: "act_weight" };+ if !reads.contains(&slope) {+ reads.push(slope);+ }+ }+ reads+ }+}+ /// Where one of a net's inputs or outputs lives, and what shape it is. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Binding {
library/ml/src/main/rust/src/vulkan/context.rs
diff --git a/library/ml/src/main/rust/src/vulkan/context.rs b/library/ml/src/main/rust/src/vulkan/context.rsindex 251949e487..c060f41688 100644--- a/library/ml/src/main/rust/src/vulkan/context.rs+++ b/library/ml/src/main/rust/src/vulkan/context.rs@@ -56,6 +56,8 @@ pub struct Context { pub queue: vk::Queue, /// The family [`Context::queue`] came from. pub queue_family_index: u32,+ /// The three device limits the weights buffer has to fit inside.+ pub limits: Limits, /// Guards the queue above. /// /// `VkQueue` is *externally synchronised* in the Vulkan sense: the application must not@@ -78,6 +80,69 @@ pub struct Context { queue_lock: Mutex<()>, } +/// The device limits the weights buffer has to fit inside, queried rather than assumed.+///+/// # Why this is not another `MAX_WORKGROUPS_PER_DIM`+///+/// [`super::pipeline::MAX_WORKGROUPS_PER_DIM`] is hardcoded to the spec's guaranteed floor and+/// never queried, deliberately: a workgroup count can be *tiled* to fit any floor at no cost, so+/// one code path is worth more than the headroom a query would find. That argument does not carry+/// over. `maxStorageBufferRange`'s guaranteed minimum is 128 MiB, SMaLL-100's weights are 318 MiB,+/// and a 125 MiB embedding cannot be made smaller — so coding unconditionally to the floor would+/// force a descriptor set per segment on **every** device, including the ones reporting 4 GiB.+///+/// This is also already latent in shipped code rather than new with SMaLL-100: Supertonic's fp16+/// sampler was 121.7 MiB, which is 95% of the guarantee.+///+/// # The three of them+///+/// * `max_storage_buffer_range` bounds one descriptor's `range`, which is what forces segmenting.+/// * `min_storage_buffer_offset_alignment` bounds a descriptor's `offset`, and can be as coarse as+/// 256 while a `.maml` tensor is only 16-aligned. A segment base is therefore rounded **down**+/// to it, so the segment starts slightly before its first tensor; the extra bytes overlap the+/// previous segment, and both are read-only.+/// * `max_memory_allocation_size` bounds the single allocation the whole file goes into. Its+/// guaranteed minimum is 1 GiB, so 318 MiB has threefold headroom — but a device reporting less+/// should fail with that sentence rather than with `VK_ERROR_OUT_OF_DEVICE_MEMORY`.+#[derive(Clone, Copy, Debug)]+pub struct Limits {+ /// `VkPhysicalDeviceLimits::maxStorageBufferRange`. Guaranteed at least 128 MiB.+ pub max_storage_buffer_range: u64,+ /// `VkPhysicalDeviceLimits::minStorageBufferOffsetAlignment`. A power of two, at most 256.+ pub min_storage_buffer_offset_alignment: u64,+ /// `VkPhysicalDeviceMaintenance3Properties::maxMemoryAllocationSize`. At least 1 GiB.+ pub max_memory_allocation_size: u64,+}++/// Forces [`Limits::max_storage_buffer_range`] down, so the segmented path can be exercised.+///+/// Mali-G715 on the target device almost certainly reports a range far above anything this+/// runtime asks for, which would ship the segmenting code as dead and unverified. Setting this to+/// `33554432` runs **today's** nets segmented, and `vulkan::parity` does exactly that: the+/// Supertonic sampler must produce identical numbers with and without it.+const FORCED_RANGE: &str = "MODELRUNNER_MAX_STORAGE_RANGE";++impl Limits {+ /// Query them, applying [`FORCED_RANGE`] if it is set to a parseable non-zero value.+ fn query(instance: &ash::Instance, physical_device: vk::PhysicalDevice) -> Limits {+ let mut maintenance3 = vk::PhysicalDeviceMaintenance3Properties::default();+ let mut properties =+ vk::PhysicalDeviceProperties2::default().push_next(&mut maintenance3);+ // SAFETY: a plain property query on a device that was just enumerated. Maintenance3 is+ // core in Vulkan 1.1, which is this runtime's floor, so the chained struct is filled in.+ unsafe { instance.get_physical_device_properties2(physical_device, &mut properties) };+ let device = properties.properties.limits;+ let forced = std::env::var(FORCED_RANGE).ok().and_then(|v| v.parse::<u64>().ok());+ Limits {+ max_storage_buffer_range: forced+ .filter(|&v| v > 0)+ .unwrap_or_else(|| u64::from(device.max_storage_buffer_range)),+ min_storage_buffer_offset_alignment: device.min_storage_buffer_offset_alignment,+ max_memory_allocation_size: maintenance3.max_memory_allocation_size,+ }+ }+}+ impl Context { /// Bring up Vulkan with a compute queue and fp16 support, or explain why not. pub fn new() -> Result<Context, String> {@@ -145,6 +210,7 @@ impl Context { } }; let queue = device.get_device_queue(queue_family_index, 0);+ let limits = Limits::query(&instance, physical_device); Ok(Context { entry, instance,@@ -152,6 +218,7 @@ impl Context { device, queue, queue_family_index,+ limits, queue_lock: Mutex::new(()), }) }
library/ml/src/main/rust/src/vulkan/mod.rs
diff --git a/library/ml/src/main/rust/src/vulkan/mod.rs b/library/ml/src/main/rust/src/vulkan/mod.rsindex 35b50048fa..c50f5a0e0d 100644--- a/library/ml/src/main/rust/src/vulkan/mod.rs+++ b/library/ml/src/main/rust/src/vulkan/mod.rs@@ -8,7 +8,9 @@ //! Vulkan 1.1 makes necessary. //! * [`buffers`] — the weights buffer, the activation arena, and the one staging buffer //! both directions go through.-//! * [`pipeline`] — the seven compute pipelines and the single descriptor set they share.+//! * [`pipeline`] — the seven compute pipelines and the descriptor sets they share.+//! * [`segment`] — splitting the weights buffer into descriptor-sized pieces, because+//! `maxStorageBufferRange` is only guaranteed to be 128 MiB and SMaLL-100's weights are 318. //! * [`run`] — recording a [`crate::nets::Plan`] into one command buffer, and submitting it. //! //! Nothing above this layer knows Vulkan exists: [`crate::nets`] produces a flat plan of@@ -20,6 +22,7 @@ pub mod context; pub mod pipeline; pub mod reshape; pub mod run;+pub mod segment; #[cfg(test)] mod parity;
library/ml/src/main/rust/src/vulkan/parity.rs
diff --git a/library/ml/src/main/rust/src/vulkan/parity.rs b/library/ml/src/main/rust/src/vulkan/parity.rsindex 78dc596ea2..7a310604ca 100644--- a/library/ml/src/main/rust/src/vulkan/parity.rs+++ b/library/ml/src/main/rust/src/vulkan/parity.rs@@ -18,6 +18,23 @@ //! cargo test -p modelrunner --lib -- --ignored vulkan::parity //! ``` //!+//! # Running them segmented+//!+//! [`super::segment`] windows the weights buffer when it is larger than+//! `maxStorageBufferRange`, and on any device this runtime actually targets it never is — so the+//! windowed path would otherwise ship as dead code. Re-running the whole suite with the range+//! forced down exercises it against the same oracle:+//!+//! ```text+//! MODELRUNNER_MAX_STORAGE_RANGE=33554432 \+//! cargo test -p modelrunner --lib -- --ignored vulkan::parity+//! ```+//!+//! Every number must be identical to the unforced run: windowing changes which descriptor set is+//! bound and what the three weights offsets in [`crate::nets::Push`] are measured from, and+//! nothing else. The variable is read once, when the [`Context`] is created, which is why it is set+//! on the command line rather than inside a test — the device here is process-wide and shared.+//! //! # Tolerance //! //! Not exact equality. Both sides store activations as fp16, but a shader reduces in parallel
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 919bdb6f9b..0abcfc9f42 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -23,6 +23,7 @@ use ash::vk; use crate::nets::{Kind, Push}; use super::context::Context;+use super::segment::Segment; const CONV: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/conv.comp.spv")); const CONV_TRANSPOSE: &[u8] =@@ -95,12 +96,17 @@ pub const WORKGROUP: u32 = 64; /// floor unconditionally rather than querying the device keeps one code path. pub const MAX_WORKGROUPS_PER_DIM: u32 = 65_535; -/// Every compute pipeline, plus the layout and descriptor set they share.+/// Every compute pipeline, plus the layout and descriptor sets they share. pub struct Pipelines { /// Shared by all of them, 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,+ /// One set per weights segment: arena at binding 0, that segment of the weights at 1 and 2.+ ///+ /// Almost always exactly one. A second appears only when the weights are larger than+ /// `maxStorageBufferRange`, which today means SMaLL-100 on a device reporting the guaranteed+ /// minimum. Every set points at the same arena and the same weights buffer; they differ only+ /// in the weights descriptor's `(offset, range)`. See [`super::segment`].+ pub descriptor_sets: Vec<vk::DescriptorSet>, descriptor_layout: vk::DescriptorSetLayout, descriptor_pool: vk::DescriptorPool, conv: vk::Pipeline,@@ -136,6 +142,8 @@ impl Pipelines { /// whole reason rebuilding beats constructing a second net. The caller must have waited for /// the device to go idle first — a descriptor set may not be written while a command buffer /// that uses it is pending.+ ///+ /// Every segment's set is rewritten, because they all point at the same arena. pub fn rebind_arena( &self, device: &ash::Device,@@ -144,27 +152,33 @@ impl Pipelines { ) { let arena_info = vk::DescriptorBufferInfo::default().buffer(arena).offset(0).range(arena_size);- let write = vk::WriteDescriptorSet::default()- .dst_set(self.descriptor_set)- .dst_binding(0)- .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)- .buffer_info(std::slice::from_ref(&arena_info));- // SAFETY: a descriptor write to a set this struct owns, against a buffer the caller- // keeps alive. Nothing using the set is pending, per the contract above.- unsafe { device.update_descriptor_sets(std::slice::from_ref(&write), &[]) };+ let writes: Vec<_> = self+ .descriptor_sets+ .iter()+ .map(|&set| {+ vk::WriteDescriptorSet::default()+ .dst_set(set)+ .dst_binding(0)+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)+ .buffer_info(std::slice::from_ref(&arena_info))+ })+ .collect();+ // SAFETY: descriptor writes to sets this struct owns, against a buffer the caller keeps+ // alive. Nothing using them is pending, per the contract above.+ unsafe { device.update_descriptor_sets(&writes, &[]) }; } - /// Build all of them and point the descriptor set at `arena` and `weights`.+ /// Build all of them and point one descriptor set per segment at `arena` and `weights`. pub fn new( context: &Context, arena: vk::Buffer, arena_size: vk::DeviceSize, weights: vk::Buffer,- weights_size: vk::DeviceSize,+ segments: &[Segment], ) -> Result<Pipelines, String> { // SAFETY: every handle created below is destroyed by `Pipelines::destroy`, or on // the failure path here before returning.- unsafe { Self::create(context, arena, arena_size, weights, weights_size) }+ unsafe { Self::create(context, arena, arena_size, weights, segments) } } unsafe fn create(@@ -172,9 +186,12 @@ impl Pipelines { arena: vk::Buffer, arena_size: vk::DeviceSize, weights: vk::Buffer,- weights_size: vk::DeviceSize,+ segments: &[Segment], ) -> Result<Pipelines, String> { let device = &context.device;+ if segments.is_empty() {+ return Err("a net needs at least one weights segment".into());+ } let bindings = [ vk::DescriptorSetLayoutBinding::default()@@ -205,57 +222,75 @@ impl Pipelines { let mut cleanup = Cleanup::new(device); cleanup.descriptor_layout = Some(descriptor_layout); + let count = u32::try_from(segments.len()).map_err(|_| "too many weights segments")?; let pool_sizes = [vk::DescriptorPoolSize::default() .ty(vk::DescriptorType::STORAGE_BUFFER)- .descriptor_count(3)];+ .descriptor_count(3 * count)]; let descriptor_pool = device .create_descriptor_pool(- &vk::DescriptorPoolCreateInfo::default().max_sets(1).pool_sizes(&pool_sizes),+ &vk::DescriptorPoolCreateInfo::default().max_sets(count).pool_sizes(&pool_sizes), None, ) .map_err(|e| format!("create_descriptor_pool {e:?}"))?; cleanup.descriptor_pool = Some(descriptor_pool); - let layouts = [descriptor_layout];- let sets = device+ let layouts = vec![descriptor_layout; segments.len()];+ let descriptor_sets = device .allocate_descriptor_sets( &vk::DescriptorSetAllocateInfo::default() .descriptor_pool(descriptor_pool) .set_layouts(&layouts), ) .map_err(|e| format!("allocate_descriptor_sets {e:?}"))?;- let descriptor_set = match sets.first() {- Some(&s) => s,- None => return Err("allocate_descriptor_sets returned nothing".into()),- };+ if descriptor_sets.len() != segments.len() {+ return Err(format!(+ "allocate_descriptor_sets returned {} sets for {} segments",+ descriptor_sets.len(),+ segments.len()+ ));+ } let arena_info = vk::DescriptorBufferInfo::default() .buffer(arena) .offset(0) .range(arena_size);- let weights_info = vk::DescriptorBufferInfo::default()- .buffer(weights)- .offset(0)- .range(weights_size);- let writes = [- vk::WriteDescriptorSet::default()- .dst_set(descriptor_set)- .dst_binding(0)- .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)- .buffer_info(std::slice::from_ref(&arena_info)),- vk::WriteDescriptorSet::default()- .dst_set(descriptor_set)- .dst_binding(1)- .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)- .buffer_info(std::slice::from_ref(&weights_info)),- // Binding 2 is the same buffer as binding 1, viewed as 32-bit words so that int8+ // Held outside the loop so the `buffer_info` borrows stay live until the one+ // `update_descriptor_sets` below.+ let weight_infos: Vec<_> = segments+ .iter()+ .map(|segment| {+ vk::DescriptorBufferInfo::default()+ .buffer(weights)+ .offset(segment.base)+ .range(segment.len)+ })+ .collect();+ let mut writes = Vec::with_capacity(segments.len() * 3);+ for (set, info) in descriptor_sets.iter().zip(&weight_infos) {+ writes.push(+ vk::WriteDescriptorSet::default()+ .dst_set(*set)+ .dst_binding(0)+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)+ .buffer_info(std::slice::from_ref(&arena_info)),+ );+ writes.push(+ vk::WriteDescriptorSet::default()+ .dst_set(*set)+ .dst_binding(1)+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)+ .buffer_info(std::slice::from_ref(info)),+ );+ // Binding 2 is the same range as binding 1, viewed as 32-bit words so that int8 // tensors can be unpacked. Both are read-only, so aliasing them is safe.- vk::WriteDescriptorSet::default()- .dst_set(descriptor_set)- .dst_binding(2)- .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)- .buffer_info(std::slice::from_ref(&weights_info)),- ];+ writes.push(+ vk::WriteDescriptorSet::default()+ .dst_set(*set)+ .dst_binding(2)+ .descriptor_type(vk::DescriptorType::STORAGE_BUFFER)+ .buffer_info(std::slice::from_ref(info)),+ );+ } device.update_descriptor_sets(&writes, &[]); let push_range = vk::PushConstantRange::default()@@ -324,7 +359,7 @@ impl Pipelines { cleanup.disarm(); Ok(Pipelines { layout,- descriptor_set,+ descriptor_sets, descriptor_layout, descriptor_pool, conv,
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 8935231594..d7584cfed2 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -39,6 +39,7 @@ use crate::weights::Blob; use super::buffers::Buffer; use super::context::Context; use super::pipeline::{Pipelines, MAX_WORKGROUPS_PER_DIM, WORKGROUP};+use super::segment::Segments; /// A compiled, recorded network ready to run. pub struct Net {@@ -49,6 +50,12 @@ pub struct Net { arena: Buffer, staging: Buffer, pipelines: Pipelines,+ /// Which descriptor set each op's weights are visible through.+ ///+ /// Almost always one window over the whole file. See [`super::segment`].+ segments: Segments,+ /// The `.maml` tensor table, for [`Segments::for_op`].+ tensors: Vec<crate::weights::Tensor>, /// This net's own command pool, not the context's. /// /// A `VkCommandPool` is externally synchronised across *recording* as well as across@@ -105,6 +112,14 @@ impl Net { // 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; + // Before allocating anything: a file this device's descriptors cannot describe must fail+ // here, with the limit in the message, rather than at the first dispatch that reads past+ // a range. Windowing depends only on the length, so `rebuild` never redoes it.+ 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 = weights.tensors().to_vec();+ let weights_buffer = Buffer::device_local(&context, weights_bytes)?; let arena = Buffer::device_local(&context, arena_bytes)?; let staging = Buffer::staging(&context, staging_bytes)?;@@ -114,7 +129,7 @@ impl Net { arena.buffer, arena_bytes, weights_buffer.buffer,- weights_bytes,+ segments.all(), )?; // `RESET_COMMAND_BUFFER`, so a net can re-record without reallocating.@@ -134,6 +149,8 @@ impl Net { arena, staging, pipelines,+ segments,+ tensors, command_pool, command_buffer: vk::CommandBuffer::null(), fence: vk::Fence::null(),@@ -393,7 +410,7 @@ impl Net { } self.barrier(buffer); - for op in &self.plan.ops {+ for (step, op) in self.plan.ops.iter().enumerate() { match *op { Op::Dispatch { kind, push, invocations } => { device.cmd_bind_pipeline(@@ -401,14 +418,24 @@ impl Net { vk::PipelineBindPoint::COMPUTE, self.pipelines.for_kind(kind), );+ // The window an op's weights are visible through, and the push rebased+ // into it. Both are the identity unless the file was larger than one+ // descriptor's range, so the common case records what it always did.+ let segment =+ self.segments.for_op(step, kind, &push, &self.tensors)?.unwrap_or(0);+ let set = match self.pipelines.descriptor_sets.get(segment) {+ Some(&set) => set,+ None => return Err(format!("step {step} wants segment {segment}")),+ }; device.cmd_bind_descriptor_sets( buffer, vk::PipelineBindPoint::COMPUTE, self.pipelines.layout, 0,- &[self.pipelines.descriptor_set],+ &[set], &[], );+ let push = self.segments.rebase(segment, kind, &push); device.cmd_push_constants( buffer, self.pipelines.layout,
library/ml/src/main/rust/src/vulkan/segment.rs
diff --git a/library/ml/src/main/rust/src/vulkan/segment.rs b/library/ml/src/main/rust/src/vulkan/segment.rsnew file mode 100644index 0000000000..abbdfc38a7--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/segment.rs@@ -0,0 +1,449 @@+//! Splitting the weights buffer into descriptor-sized pieces.+//!+//! # The problem+//!+//! Every shader reads the whole weights file through one descriptor whose `range` is the file's+//! length, and `maxStorageBufferRange` is only guaranteed to be **128 MiB**. SMaLL-100's weights+//! are 318 MiB. So on a device reporting the minimum, one descriptor cannot describe the file at+//! all: the binding would be invalid, and validation would say so while a release build read+//! whatever the driver felt like past the range.+//!+//! It is not new with SMaLL-100 either. Supertonic's fp16 sampler shipped at 121.7 MiB, 95% of the+//! guarantee, so this was one model away from breaking already.+//!+//! # One buffer, several descriptors+//!+//! The file stays a **single** `VkBuffer` and a single allocation — nothing about the upload,+//! [`crate::weights::Blob::read_at`] or `Net::CHUNK_BYTES` changes. What is split is the+//! *descriptor*: one set per segment, each pointing at the same buffer with its own+//! `(offset, range)`, and `Net::record` binds the set an op needs before dispatching it.+//!+//! Per-segment `VkBuffer`s would work too, and would sidestep `minStorageBufferOffsetAlignment`+//! entirely, at the price of N allocations, an upload that has to know which buffer each byte+//! belongs to, and N sets of aliasing rules. The alignment is not actually a problem: it is at+//! most 256, a segment base is a multiple of the window stride which is rounded down to it, and+//! the overlap that creates is read-only in every segment.+//!+//! # Overlapping windows, so the split does not depend on the plan+//!+//! The obvious segmentation is greedy over the ops: fill a descriptor until the next op's tensors+//! do not fit, then start another. It gives the fewest segments, and it is wrong here, because+//! [`super::run::Net::rebuild`] installs a **different plan** over the same weights. SMaLL-100's+//! encoder and decoder passes read different subsets of one file, so a plan-derived segmentation+//! would have to be recomputed on every rebuild, and a recomputation that wanted *more* segments+//! than the descriptor pool was allocated for could only fail.+//!+//! So the segments are fixed windows of `range` bytes at a stride of `range / 4`, covering the+//! file. Any byte span shorter than `range - stride`, which is three quarters of the range, is+//! then **entirely inside** at least one window: a span starting at `from` is inside window+//! `from / stride`, which reaches to `(from / stride) * stride + range`. The largest span any op+//! here has is one of SMaLL-100's two logits halves at 65.9 MB, against 100.7 MB of guaranteed+//! headroom.+//!+//! The cost of the overlap is descriptor sets, not memory: ten of them for a 318 MiB file at the+//! guaranteed range, one for the same file on a device reporting 4 GiB. Since it depends only on+//! the file's length, `rebuild` needs to recompute nothing.+//!+//! # What stays invisible+//!+//! [`crate::weights::Tensor::offset`] stays absolute and file-relative, and so does every offset+//! in a [`Plan`]. Nothing in `nets/` knows a segment exists, which is what keeps+//! `nets::reference` — the only oracle for the shaders — and every parity fixture unchanged.+//! Rebasing happens here, at record time, and is a pure function of the segment and the push.+//!+//! [`Plan`]: crate::nets::Plan++use crate::nets::{Kind, Push};+use crate::weights::Tensor;++use super::context::Limits;++/// The `.maml` tensor alignment, from `scripts/ml/maml_convert.py`.+///+/// A stride is rounded down to a multiple of at least this, so that dividing a segment base by 2+/// for the fp16 view and by 4 for the 32-bit word view are both exact.+/// `minStorageBufferOffsetAlignment` may be *finer* than 16 — it is only required to be a power of+/// two — and 2 would not satisfy the word view.+const ALIGNMENT: u64 = 16;++/// A window count past which the device's reported range is not believable.+///+/// At the spec's guaranteed 128 MiB this allows a 32 GiB weights file, which is two orders of+/// magnitude past anything this runtime loads. Hitting it means `max_storage_buffer_range` came+/// back absurdly small, and thousands of descriptor sets would be a worse failure than a message.+const MAX_SEGMENTS: usize = 1024;++/// One descriptor's worth of the weights buffer.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Segment {+ /// Byte offset of the descriptor. A multiple of the device's required alignment.+ pub base: u64,+ /// Bytes the descriptor covers, never more than `max_storage_buffer_range`.+ pub len: u64,+}++/// The weights file as overlapping windows, one descriptor set each.+#[derive(Debug, PartialEq, Eq)]+pub struct Segments {+ segments: Vec<Segment>,+ /// Distance between window bases. Zero when there is only one window.+ stride: u64,+ /// The longest span a window is guaranteed to contain, `range - stride`.+ reach: u64,+}++impl Segments {+ /// Window `total` bytes of weights so that every op's tensors land inside one descriptor.+ ///+ /// Depends only on the file's length and the device, never on the plan. See the module docs.+ pub fn plan(total: u64, limits: &Limits) -> Result<Segments, String> {+ if total > limits.max_memory_allocation_size {+ return Err(format!(+ "{total} bytes of weights against a maxMemoryAllocationSize of {}. The spec \+ guarantees at least 1 GiB, so this device is unusually constrained and the model \+ is refused rather than loaded wrongly.",+ limits.max_memory_allocation_size+ ));+ }+ let granularity = limits.min_storage_buffer_offset_alignment.max(ALIGNMENT);+ let range = limits.max_storage_buffer_range;+ if range < granularity {+ return Err(format!(+ "maxStorageBufferRange {range} is below minStorageBufferOffsetAlignment \+ {granularity}"+ ));+ }+ if total <= range {+ // The overwhelmingly common case, and the only one before SMaLL-100: one descriptor+ // over the whole file, `base` zero, so `rebase` is the identity and `record` emits+ // exactly the commands it always did.+ return Ok(Segments { segments: vec![Segment { base: 0, len: total }], stride: 0, reach: range });+ }+ // A quarter of the range, rounded down to something both views can address.+ let stride = ((range / 4) / granularity) * granularity;+ if stride == 0 {+ return Err(format!("maxStorageBufferRange {range} is too small to window"));+ }+ let count = usize::try_from(total.div_ceil(stride)).map_err(|_| "too many segments")?;+ if count > MAX_SEGMENTS {+ return Err(format!(+ "{total} bytes of weights need {count} descriptor windows at a \+ maxStorageBufferRange of {range}, past the {MAX_SEGMENTS} this allows"+ ));+ }+ let segments = (0..count)+ .map(|index| {+ let base = index as u64 * stride;+ Segment { base, len: range.min(total - base) }+ })+ .collect();+ Ok(Segments { segments, stride, reach: range - stride })+ }++ /// The segments, in the order their descriptor sets are allocated.+ pub fn all(&self) -> &[Segment] {+ &self.segments+ }++ /// The window op `step` should be dispatched through, or `None` if it reads no weights.+ ///+ /// An op that reads none keeps whatever set is already bound, which is always a valid one.+ pub fn for_op(+ &self,+ step: usize,+ kind: Kind,+ push: &Push,+ tensors: &[Tensor],+ ) -> Result<Option<usize>, String> {+ let Some((from, to)) = self.span(step, kind, push, tensors)? else {+ return Ok(None);+ };+ if self.stride == 0 {+ return Ok(Some(0));+ }+ let index = usize::try_from(from / self.stride).map_err(|_| "a segment index overflowed")?;+ let Some(segment) = self.segments.get(index) else {+ return Err(format!("step {step} reads at byte {from}, past the last segment"));+ };+ if to > segment.base + segment.len {+ return Err(format!(+ "step {step} ({kind:?}) reads bytes {from}..{to} of the weights, a span of {} \+ against the {} one descriptor window is guaranteed to hold. Split the tensor in \+ the converter.",+ to - from,+ self.reach+ ));+ }+ Ok(Some(index))+ }++ /// `push` with its three weights offsets made relative to segment `index`.+ ///+ /// The units differ per field and per kind — `weight` is a 32-bit word index for the int8 pair+ /// and an fp16 element index otherwise — which is why the base is divided rather than+ /// subtracted from one normalised offset. A base is a multiple of `ALIGNMENT`, so both+ /// divisions are exact.+ pub fn rebase(&self, index: usize, kind: Kind, push: &Push) -> Push {+ let base = self.segments.get(index).map_or(0, |segment| segment.base);+ if base == 0 {+ return *push;+ }+ let elems = (base / 2) as u32;+ let words = (base / 4) as u32;+ let mut out = *push;+ for read in kind.weight_reads(push) {+ match read.field {+ "weight" if matches!(kind, Kind::ConvInt8 | Kind::ConvPointInt8) => {+ out.weight = push.weight.saturating_sub(words);+ }+ "weight" => out.weight = push.weight.saturating_sub(elems),+ "bias" => out.bias = push.bias.saturating_sub(elems),+ "act_weight" => out.act_weight = push.act_weight.saturating_sub(elems),+ _ => {}+ }+ }+ out+ }++ /// The `[from, to)` byte span of the weights one op reads, or `None` if it reads none.+ ///+ /// Each offset is resolved against the tensor table rather than reconstructed from the push's+ /// shape fields, so the extent is exact for every kind without this knowing what any of them+ /// compute. An offset landing in no tensor is a bug in the net module — a push pointing+ /// somewhere the file does not describe — and is reported rather than read on the device.+ fn span(+ &self,+ step: usize,+ kind: Kind,+ push: &Push,+ tensors: &[Tensor],+ ) -> Result<Option<(u64, u64)>, String> {+ let reads = kind.weight_reads(push);+ if reads.is_empty() {+ return Ok(None);+ }+ let mut from = u64::MAX;+ let mut to = 0u64;+ for read in reads {+ let end = tensor_end(read.at, tensors).ok_or_else(|| {+ format!(+ "step {step} ({kind:?}) reads {} at byte {}, which is inside none of the {} \+ tensors the file describes",+ read.field,+ read.at,+ tensors.len()+ )+ })?;+ from = from.min(read.at);+ to = to.max(end);+ }+ Ok(Some((from, to)))+ }+}++/// The end of the tensor containing byte `at`.+///+/// A linear scan, run once per op per recording over a table of at most a few hundred entries.+fn tensor_end(at: u64, tensors: &[Tensor]) -> Option<u64> {+ tensors.iter().find_map(|tensor| {+ let start = u64::from(tensor.offset);+ let bytes = u64::from(tensor.len) * if tensor.int8 { 1 } else { 2 };+ (at >= start && at < start + bytes.max(1)).then_some(start + bytes)+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ /// The spec's guaranteed floor for the two limits that matter, plus 1 GiB of allocation.+ fn floor() -> Limits {+ Limits {+ max_storage_buffer_range: 128 << 20,+ min_storage_buffer_offset_alignment: 256,+ max_memory_allocation_size: 1 << 30,+ }+ }++ #[test]+ fn a_file_inside_the_range_is_one_window() {+ let segments = Segments::plan(121_700_000, &floor()).unwrap();+ assert_eq!(segments.all(), [Segment { base: 0, len: 121_700_000 }]);+ // Base zero, so `rebase` must be the identity: the common case records what it always did.+ let push = Push { weight: 7, bias: 9, act_weight: 11, ..Push::default() };+ assert_eq!(segments.rebase(0, Kind::Conv, &push), push);+ }++ #[test]+ fn a_larger_file_is_covered_by_overlapping_windows() {+ let limits = floor();+ let total = 333_783_488u64;+ let segments = Segments::plan(total, &limits).unwrap();+ let stride = (128 << 20) / 4;+ assert_eq!(segments.all().len(), total.div_ceil(stride) as usize);+ for window in segments.all() {+ assert_eq!(window.base % 256, 0, "a base must satisfy the device's alignment");+ assert_eq!(window.base % ALIGNMENT, 0, "and be addressable as fp16 and as words");+ assert!(window.len <= limits.max_storage_buffer_range, "{window:?}");+ assert!(window.base + window.len <= total, "{window:?} runs past the file");+ }+ // The whole file is covered: consecutive bases are one stride apart and the last window+ // reaches the end.+ let last = segments.all().last().unwrap();+ assert_eq!(last.base + last.len, total);+ }++ #[test]+ fn every_span_short_enough_lands_inside_one_window() {+ let limits = floor();+ let total = 333_783_488u64;+ let segments = Segments::plan(total, &limits).unwrap();+ // One int8 tensor the size of SMaLL-100's larger logits half, walked across the file. This+ // is the span the three-quarter reach exists for.+ let biggest = 65_593_344u64;+ let mut at = 0u64;+ while at + biggest <= total {+ let index = (at / segments.stride) as usize;+ let window = segments.all()[index];+ assert!(+ at >= window.base && at + biggest <= window.base + window.len,+ "{at}..{} is not inside {window:?}",+ at + biggest+ );+ at += 4_096_301;+ }+ }++ #[test]+ fn a_split_file_rebases_both_views_exactly() {+ let segments = Segments::plan(333_783_488, &floor()).unwrap();+ let window = segments.all()[3];+ assert!(window.base > 0);+ // An fp16 kernel: `weight` and `bias` are element indices.+ let fp16 = Push {+ weight: (window.base / 2) as u32 + 10,+ bias: (window.base / 2) as u32 + 20,+ ..Push::default()+ };+ let out = segments.rebase(3, Kind::Conv, &fp16);+ assert_eq!((out.weight, out.bias), (10, 20));+ // An int8 kernel: `weight` is a word index, `bias` and the scale are element indices.+ let int8 = Push {+ weight: (window.base / 4) as u32 + 5,+ bias: (window.base / 2) as u32 + 6,+ act_weight: (window.base / 2) as u32 + 7,+ ..Push::default()+ };+ let out = segments.rebase(3, Kind::ConvPointInt8, &int8);+ assert_eq!((out.weight, out.bias, out.act_weight), (5, 6, 7));+ }++ #[test]+ fn an_op_reading_no_weights_needs_no_window() {+ let segments = Segments::plan(333_783_488, &floor()).unwrap();+ let push = Push { in0: 4, in1: 8, ..Push::default() };+ assert_eq!(segments.for_op(0, Kind::Add, &push, &[]).unwrap(), None);+ // And rebasing one changes nothing, because it reads nothing.+ assert_eq!(segments.rebase(3, Kind::Add, &push), push);+ }++ #[test]+ fn an_offset_in_no_tensor_is_refused() {+ let segments = Segments::plan(1024, &floor()).unwrap();+ let tensors = [Tensor { rank: 1, dims: [8, 0, 0, 0], offset: 0, len: 8, int8: false }];+ let push = Push { weight: 0, bias: 400, ..Push::default() };+ let error = segments.for_op(2, Kind::Conv, &push, &tensors).unwrap_err();+ assert!(error.contains("step 2"), "{error}");+ assert!(error.contains("bias"), "{error}");+ }++ #[test]+ fn a_span_longer_than_the_reach_is_refused() {+ let limits = Limits { max_storage_buffer_range: 4096, ..floor() };+ let segments = Segments::plan(16_384, &limits).unwrap();+ // The reach is `range - stride` = 3072, but a span starting at a multiple of the stride+ // gets the whole range. So this is placed *off* the stride, at 1536: window 1 covers+ // 1024..5120 and the span runs to 5136.+ let tensors =+ [Tensor { rank: 1, dims: [1800, 0, 0, 0], offset: 1536, len: 1800, int8: false }];+ let push = Push { weight: 768, bias: 768, ..Push::default() };+ let error = segments.for_op(0, Kind::Conv, &push, &tensors).unwrap_err();+ assert!(error.contains("Split the tensor in the converter"), "{error}");+ }++ #[test]+ fn an_int8_kernel_is_never_separated_from_its_scale_and_bias() {+ // A layer laid out the way `maml_convert.build` writes one: an int8 kernel, then its fp16+ // per-output-channel scale, then its fp16 bias, each starting on a 16-byte boundary. This+ // is the group a boundary must never fall inside, and the windows are forced small enough+ // that the layer does not start in the first one.+ let limits = Limits { max_storage_buffer_range: 1 << 20, ..floor() };+ let out = 512u32;+ let inputs = 256u32;+ let kernel_at = 3_145_728u64;+ let kernel_bytes = u64::from(out) * u64::from(inputs);+ let scale_at = kernel_at + kernel_bytes;+ let bias_at = scale_at + u64::from(out) * 2;+ let total = bias_at + u64::from(out) * 2;+ let tensors = [+ Tensor {+ rank: 4,+ dims: [out, inputs, 1, 1],+ offset: kernel_at as u32,+ len: out * inputs,+ int8: true,+ },+ Tensor { rank: 1, dims: [out, 0, 0, 0], offset: scale_at as u32, len: out, int8: false },+ Tensor { rank: 1, dims: [out, 0, 0, 0], offset: bias_at as u32, len: out, int8: false },+ ];+ let segments = Segments::plan(total, &limits).unwrap();+ assert!(segments.all().len() > 1, "the limit must actually force windowing");++ let push = Push {+ weight: (kernel_at / 4) as u32,+ bias: (bias_at / 2) as u32,+ act_weight: (scale_at / 2) as u32,+ ..Push::default()+ };+ let index = segments+ .for_op(0, Kind::ConvPointInt8, &push, &tensors)+ .unwrap()+ .expect("an int8 convolution reads weights");+ let window = segments.all()[index];+ // All three inside the one window, which is the invariant.+ assert!(kernel_at >= window.base, "the kernel starts before its window");+ assert!(total <= window.base + window.len, "the bias ends past its window");++ // And the rebased offsets address the same three tensors from the window's base.+ let out_push = segments.rebase(index, Kind::ConvPointInt8, &push);+ assert_eq!(u64::from(out_push.weight) * 4 + window.base, kernel_at);+ assert_eq!(u64::from(out_push.act_weight) * 2 + window.base, scale_at);+ assert_eq!(u64::from(out_push.bias) * 2 + window.base, bias_at);+ }++ #[test]+ fn a_prelu_slope_is_part_of_the_span_it_is_read_with() {+ // `prelu` in `common.glsl` reads `act_weight` for *any* kind carrying the activation, not+ // only the int8 pair, so the slope has to be inside the same window as the kernel.+ let tensors = [+ Tensor { rank: 4, dims: [4, 1, 1, 1], offset: 0, len: 4, int8: false },+ Tensor { rank: 1, dims: [4, 0, 0, 0], offset: 16, len: 4, int8: false },+ Tensor { rank: 1, dims: [4, 0, 0, 0], offset: 32, len: 4, int8: false },+ ];+ let segments = Segments::plan(40, &floor()).unwrap();+ let push = Push { weight: 0, bias: 8, act_weight: 16, act: 4, ..Push::default() };+ let reads = Kind::Conv.weight_reads(&push);+ assert_eq!(reads.len(), 3, "kernel, bias and slope: {reads:?}");+ assert_eq!(segments.span(0, Kind::Conv, &push, &tensors).unwrap(), Some((0, 40)));+ // Without PRelu the slope is not read, so it is not part of the span.+ let plain = Push { act: 1, ..push };+ assert_eq!(Kind::Conv.weight_reads(&plain).len(), 2);+ }++ #[test]+ fn a_file_past_the_allocation_cap_is_refused_with_the_reason() {+ let limits = Limits { max_memory_allocation_size: 1 << 20, ..floor() };+ let error = Segments::plan(2 << 20, &limits).unwrap_err();+ assert!(error.contains("maxMemoryAllocationSize"), "{error}");+ }+}
library/ml/src/main/rust/src/weights.rs
diff --git a/library/ml/src/main/rust/src/weights.rs b/library/ml/src/main/rust/src/weights.rsindex 11b79f8099..9956710573 100644--- a/library/ml/src/main/rust/src/weights.rs+++ b/library/ml/src/main/rust/src/weights.rs@@ -70,7 +70,7 @@ pub mod graph { pub const SUPERTONIC_TTL: u32 = 13; /// Supertonic 3's flow-matching sampler. See [`crate::nets::supertonic_sampler`]. pub const SUPERTONIC_VE: u32 = 14;- /// SMaLL-100 translation, encoder and decoder in one file. See [`crate::nets::small100`].+ /// SMaLL-100 translation, encoder and decoder in one file. See `crate::nets::small100`. /// /// One graph rather than two because the 128,112-row embedding is **tied**: it is the encoder's /// input table, the decoder's input table and the logits kernel, and two files would upload@@ -129,6 +129,14 @@ pub trait Blob { /// Bytes in the data section. fn data_len(&self) -> u64; + /// The tensor table, so `vulkan::segment` can find the extent of every tensor an op reads.+ ///+ /// Nothing about *running* a net needs the table - a [`Plan`] carries every resolved offset,+ /// which is what makes [`Weights`] and [`Streamed`] interchangeable. Segmenting the weights+ /// buffer does: it has to know where each tensor ends to choose a boundary that does not fall+ /// inside one, and only the table says that.+ fn tensors(&self) -> &[Tensor];+ /// Fill `into` from `offset` bytes into the data section. /// /// A short read is an error rather than a partial fill: every caller here knows exactly how@@ -384,6 +392,10 @@ impl Blob for Weights { self.data.len() as u64 } + fn tensors(&self) -> &[Tensor] {+ &self.table.tensors+ }+ fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> { let start = usize::try_from(offset).map_err(|_| "a data offset overflowed usize")?; let end = start@@ -500,6 +512,10 @@ impl Blob for Streamed { self.data_len } + fn tensors(&self) -> &[Tensor] {+ &self.table.tensors+ }+ fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> { let end = offset .checked_add(into.len() as u64)