ml: split weights past maxMemoryAllocationSize into overlapping blocks; gemma4 loads on Adreno
- Commit
11258417d4cbd7136071081c58c3d37b2de15da4- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-02 05:43 UTC (1 month ago)
- Parents
b96e4df
gemma4_text's 1.03 GiB of weights went into one device-local buffer, and Adreno reports maxMemoryAllocationSize as the spec's 1 GiB floor, so the model was refused on the Galaxy Tab S7 / A52s (#897). A file past the limit is now laid out as equal blocks, one VkBuffer each, overlapping by min(96 MiB, a window's reach) so every op's span lands inside one block. Each block is windowed as a single buffer was; descriptor sets point at their block's buffer, the upload copies each chunk into every block covering it, and record barriers every block. The layout depends only on the length, so rebuild still recomputes nothing. Files under the limit keep one buffer. MODELRUNNER_MAX_ALLOCATION / debug.modelrunner.max_allocation forces the limit down to exercise the path on devices reporting more. Tested: segment_extra unit tests; vulkan::parity 102/102 on Pixel 9 Pro XL unforced, with MODELRUNNER_MAX_STORAGE_RANGE=33554432, and with that plus MODELRUNNER_MAX_ALLOCATION=33554432 (boundary fixture uploads as 3 blocks); openassistant chats with max_allocation=1073741824.
Diff
library/ml/src/main/rust/examples/probe_limits.rs
diff --git a/library/ml/src/main/rust/examples/probe_limits.rs b/library/ml/src/main/rust/examples/probe_limits.rsindex 1be8e0751d..a26f30160d 100644--- a/library/ml/src/main/rust/examples/probe_limits.rs+++ b/library/ml/src/main/rust/examples/probe_limits.rs@@ -7,12 +7,9 @@ //! //! # Why this exists //!-//! `modelrunner::vulkan::run` puts the **entire** weights data section into one-//! `Buffer::device_local`, so a model is bounded by `maxMemoryAllocationSize` and not merely by-//! how much memory the device has. `maxStorageBufferRange` is handled by-//! `modelrunner::vulkan::segment`, which windows the *descriptor*; nothing windows the-//! *allocation*. The largest file the runtime loads today is NLLB at 617 MB, comfortably under-//! the 1 GiB the spec guarantees, so the ceiling has never been approached and never measured.+//! `modelrunner::vulkan::run` splits the weights into blocks of at most `maxMemoryAllocationSize`+//! (see `modelrunner::vulkan::segment`), so the reported limit decides how many allocations a+//! model takes. What it cannot decide is whether each one actually succeeds. //! //! A reported limit and a limit that works are different things — a driver may advertise a //! number it cannot honour once the heap is shared with a compositor — so this asks the device@@ -116,6 +113,9 @@ fn describe_limits(context: &Arc<Context>) { if std::env::var("MODELRUNNER_MAX_STORAGE_RANGE").is_ok() { println!(" (MODELRUNNER_MAX_STORAGE_RANGE is set, so the range above is forced)"); }+ if std::env::var("MODELRUNNER_MAX_ALLOCATION").is_ok() {+ println!(" (MODELRUNNER_MAX_ALLOCATION is set, so the allocation limit above is forced)");+ } println!(); } @@ -184,7 +184,7 @@ fn probe_allocations(context: &Arc<Context>) { println!("verdict fits Gemma 3n E2B at int4 ({}) in one buffer", bytes(needed)); } else { println!("verdict does NOT fit Gemma 3n E2B at int4 ({}) in one buffer", bytes(needed));- println!(" weights would have to become multi-buffer, or the model must change");+ println!(" the runtime will split its weights across several blocks"); } println!(); println!("A desktop GPU passing this says nothing about a phone. See the module docs.");
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 21ab9ba41f..bfd7344cb6 100644--- a/library/ml/src/main/rust/src/vulkan/context.rs+++ b/library/ml/src/main/rust/src/vulkan/context.rs@@ -114,9 +114,8 @@ pub struct Context { /// 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`.+/// * `max_memory_allocation_size` bounds one weights block. Its guaranteed minimum is 1 GiB and+/// Adreno reports exactly that, so a larger file is split into several blocks. #[derive(Clone, Copy, Debug)] pub struct Limits { /// `VkPhysicalDeviceLimits::maxStorageBufferRange`. Guaranteed at least 128 MiB.@@ -148,8 +147,17 @@ pub struct Limits { /// Supertonic sampler must produce identical numbers with and without it. const FORCED_RANGE: &str = "MODELRUNNER_MAX_STORAGE_RANGE"; +/// Forces [`Limits::max_memory_allocation_size`] down, so the multi-block path can be exercised+/// on a device that reports more than Adreno's 1 GiB: `MODELRUNNER_MAX_ALLOCATION` for the test+/// binary, `adb shell setprop debug.modelrunner.max_allocation` for the app. `1073741824` loads+/// Gemma 4 as an Adreno part would; `33554432`, together with+/// `MODELRUNNER_MAX_STORAGE_RANGE=33554432`, splits the parity fixtures. It only lowers the+/// limit, never raises it.+const FORCED_ALLOCATION: &str = "max_allocation";+ impl Limits {- /// Query them, applying [`FORCED_RANGE`] if it is set to a parseable non-zero value.+ /// Query them, applying [`FORCED_RANGE`] and [`FORCED_ALLOCATION`] if set to parseable+ /// non-zero values. fn query(instance: &ash::Instance, physical_device: vk::PhysicalDevice) -> Limits { let mut maintenance3 = vk::PhysicalDeviceMaintenance3Properties::default(); let mut properties =@@ -159,6 +167,8 @@ impl Limits { 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());+ let forced_allocation =+ crate::knobs::get(FORCED_ALLOCATION).and_then(|v| v.parse::<u64>().ok()); // Timestamp validity lives on the queue family in Vulkan 1.3, not on // the device: the best any compute family offers is what the query // pool can rely on.@@ -177,7 +187,11 @@ impl Limits { .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,+ max_memory_allocation_size: forced_allocation+ .filter(|&v| v > 0)+ .map_or(maintenance3.max_memory_allocation_size, |v| {+ v.min(maintenance3.max_memory_allocation_size)+ }), timestamp_period: device.timestamp_period, timestamp_valid_bits, }
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 794dba5192..86f54c980b 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline.rs@@ -235,9 +235,9 @@ pub struct Pipelines { /// 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`].+ /// `maxStorageBufferRange` or `maxMemoryAllocationSize`. Every set points at the same arena;+ /// they differ in which block's buffer the weights descriptor names and its+ /// `(offset, range)`. See [`super::segment`]. pub descriptor_sets: Vec<vk::DescriptorSet>, descriptor_pool: vk::DescriptorPool, }@@ -275,12 +275,13 @@ impl Pipelines { unsafe { device.update_descriptor_sets(&writes, &[]) }; } - /// Build all of them and point one descriptor set per segment at `arena` and `weights`.+ /// Build all of them and point one descriptor set per segment at `arena` and the weights+ /// buffer of that segment's block. pub fn new( context: &Context, arena: vk::Buffer, arena_size: vk::DeviceSize,- weights: vk::Buffer,+ weights: &[vk::Buffer], params: vk::Buffer, segments: &[Segment], ) -> Result<Pipelines, String> {@@ -295,7 +296,7 @@ impl Pipelines { shaders: Arc<Shaders>, arena: vk::Buffer, arena_size: vk::DeviceSize,- weights: vk::Buffer,+ weights: &[vk::Buffer], params: vk::Buffer, segments: &[Segment], ) -> Result<Pipelines, String> {@@ -344,15 +345,18 @@ impl Pipelines { .range(vk::WHOLE_SIZE); // Held outside the loop so the `buffer_info` borrows stay live until the one // `update_descriptor_sets` below.- let weight_infos: Vec<_> = segments+ let weight_infos = segments .iter() .map(|segment| {- vk::DescriptorBufferInfo::default()- .buffer(weights)+ let buffer = weights.get(segment.block).copied().ok_or_else(|| {+ format!("a segment in block {} of {}", segment.block, weights.len())+ })?;+ Ok(vk::DescriptorBufferInfo::default()+ .buffer(buffer) .offset(segment.base)- .range(segment.len)+ .range(segment.len)) })- .collect();+ .collect::<Result<Vec<_>, String>>()?; let mut writes = Vec::with_capacity(segments.len() * BINDINGS as usize); for (set, info) in descriptor_sets.iter().zip(&weight_infos) { writes.push(
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 0acb532cb8..92941e4250 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -261,7 +261,8 @@ pub struct Net { context: Arc<Context>, plan: Plan, normalise: Normalise,- weights: Buffer,+ /// One buffer per [`Segments::blocks`] entry; almost always exactly one.+ weights: Vec<Buffer>, arena: Buffer, staging: Buffer, /// Values the shaders read that change per step without a re-record.
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 17d6cfdce9..63fb086ae5 100644--- a/library/ml/src/main/rust/src/vulkan/run_part1.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part1.rs@@ -92,17 +92,22 @@ impl Net { lo, )?; - let weights_buffer = Buffer::device_local(&context, weights_bytes)?;+ let weights_buffers = segments+ .blocks()+ .iter()+ .map(|block| Buffer::device_local(&context, block.len))+ .collect::<Result<Vec<_>, _>>()?; let arena = Buffer::device_local(&context, arena_bytes)?; let staging = Buffer::staging(&context, staging_bytes)?; let params = Buffer::step_params(&context, StepParams::BYTES)?; let staged = std::time::Instant::now();+ let weight_handles: Vec<vk::Buffer> = weights_buffers.iter().map(|b| b.buffer).collect(); let pipelines = Pipelines::new( &context, arena.buffer, arena_bytes,- weights_buffer.buffer,+ &weight_handles, params.buffer, segments.all(), )?;@@ -122,7 +127,7 @@ impl Net { context, plan, normalise,- weights: weights_buffer,+ weights: weights_buffers, arena, staging, params,@@ -151,10 +156,11 @@ impl Net { net.upload_weights(weights)?; net.upload_widened(weights)?; timing!(- "upload {} MB of {} MB (bytes {lo}..{hi}, {} MB widened) in {:.0} ms",+ "upload {} MB of {} MB (bytes {lo}..{hi}, {} MB widened, {} blocks) in {:.0} ms", weights_bytes / (1024 * 1024), weights.data_len() / (1024 * 1024), net.widened_bytes() / (1024 * 1024),+ net.weights.len(), staged.elapsed().as_secs_f64() * 1000.0 ); net.command_buffer = net.allocate_command_buffer()?;
library/ml/src/main/rust/src/vulkan/run_part2.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part2.rs b/library/ml/src/main/rust/src/vulkan/run_part2.rsindex 9796e7c541..2b8f9c775d 100644--- a/library/ml/src/main/rust/src/vulkan/run_part2.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part2.rs@@ -18,21 +18,27 @@ impl Net { // making that TRANSFER_WRITE visible to every SHADER_READ below needs a real // barrier. Recorded once at the top rather than folded into `barrier`, because // the weights buffer is never written again.- let weights_visible = vk::BufferMemoryBarrier::default()- .src_access_mask(vk::AccessFlags::TRANSFER_WRITE)- .dst_access_mask(vk::AccessFlags::SHADER_READ)- .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)- .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)- .buffer(self.weights.buffer)- .offset(0)- .size(vk::WHOLE_SIZE);+ let weights_visible: Vec<_> = self+ .weights+ .iter()+ .map(|block| {+ vk::BufferMemoryBarrier::default()+ .src_access_mask(vk::AccessFlags::TRANSFER_WRITE)+ .dst_access_mask(vk::AccessFlags::SHADER_READ)+ .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)+ .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)+ .buffer(block.buffer)+ .offset(0)+ .size(vk::WHOLE_SIZE)+ })+ .collect(); device.cmd_pipeline_barrier( buffer, vk::PipelineStageFlags::TRANSFER, vk::PipelineStageFlags::COMPUTE_SHADER, vk::DependencyFlags::empty(), &[],- std::slice::from_ref(&weights_visible),+ &weights_visible, &[], ); // Timestamps start clean: a query pool left over from an earlier
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 9055e778bf..f28e0a87b0 100644--- a/library/ml/src/main/rust/src/vulkan/run_part6.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part6.rs@@ -107,15 +107,25 @@ impl Net { .flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT), ) .map_err(|e| format!("begin_command_buffer {e:?}"))?;- let region = vk::BufferCopy::default()- .dst_offset((dst + written) as vk::DeviceSize)- .size(size as vk::DeviceSize);- device.cmd_copy_buffer(- command_buffer,- staging[side].buffer,- self.weights.buffer,- std::slice::from_ref(®ion),- );+ // Once into every block holding any of these bytes: twice across an overlap,+ // from the same staging buffer.+ let (start, end) = (dst + written, dst + written + size);+ for (block, target) in self.segments.blocks().iter().zip(&self.weights) {+ let (from, to) = (start.max(block.base), end.min(block.base + block.len));+ if from >= to {+ continue;+ }+ let region = vk::BufferCopy::default()+ .src_offset((from - start) as vk::DeviceSize)+ .dst_offset((from - block.base) as vk::DeviceSize)+ .size((to - from) as vk::DeviceSize);+ device.cmd_copy_buffer(+ command_buffer,+ staging[side].buffer,+ target.buffer,+ std::slice::from_ref(®ion),+ );+ } device .end_command_buffer(command_buffer) .map_err(|e| format!("end_command_buffer {e:?}"))?;
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.rsindex 6fa94a1819..3f162f3cb4 100644--- a/library/ml/src/main/rust/src/vulkan/segment.rs+++ b/library/ml/src/main/rust/src/vulkan/segment.rs@@ -13,16 +13,19 @@ //! //! # 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+//! A file that fits in one allocation stays a **single** `VkBuffer`. 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.+//! # Several buffers, when one allocation is not enough+//!+//! `maxMemoryAllocationSize` is only guaranteed to be 1 GiB, and Adreno reports exactly that.+//! Gemma 4's text file is 1.03 GiB. So a file past the limit becomes several **blocks**, one+//! `VkBuffer` each, laid out by the same trick as the windows below: fixed blocks at a stride,+//! overlapping by [`BLOCK_OVERLAP`] at most, so any span no longer than the overlap is entirely+//! inside one block. The overlap is uploaded twice — device memory, not file reads — and the+//! layout depends only on the length, so `rebuild` still recomputes nothing. Each block is then+//! windowed on its own exactly as a single buffer is. //! //! # Overlapping windows, so the split does not depend on the plan //!@@ -73,23 +76,46 @@ pub(crate) const ALIGNMENT: u64 = 16; /// back absurdly small, and thousands of descriptor sets would be a worse failure than a message. pub(crate) const MAX_SEGMENTS: usize = 1024; -/// One descriptor's worth of the weights buffer.+/// The most two neighbouring blocks overlap by: the reach of a window at the spec's guaranteed+/// 128 MiB range, so every op that loads on such a device already fits.+pub(crate) const BLOCK_OVERLAP: u64 = 96 << 20;++/// One descriptor's worth of one weights block. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Segment {- /// Byte offset of the descriptor. A multiple of the device's required alignment.+ /// The block, and so the `VkBuffer`, this descriptor points into.+ pub block: usize,+ /// Byte offset of the descriptor inside its block. 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.+/// One weights allocation and the windows over it.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub struct Block {+ /// Byte offset of the block in the uploaded weights.+ pub base: u64,+ /// Bytes in the block, never more than `max_memory_allocation_size`.+ pub len: u64,+ /// Index of the block's first segment in [`Segments::all`].+ pub(crate) first: usize,+ /// Distance between this block's window bases. Zero when it has one window.+ pub(crate) stride: u64,+ /// The longest span one of its windows is guaranteed to contain.+ pub(crate) reach: u64,+}++/// The weights as overlapping blocks of overlapping windows, one descriptor set per window. #[derive(Debug, PartialEq, Eq)] pub struct Segments { pub(crate) segments: Vec<Segment>,- /// Distance between window bases. Zero when there is only one window.- pub(crate) stride: u64,- /// The longest span a window is guaranteed to contain, `range - stride`.- pub(crate) reach: u64,+ pub(crate) blocks: Vec<Block>,+ /// Distance between block bases. Zero when there is only one block.+ pub(crate) block_stride: u64,+ /// The longest span a block is guaranteed to contain. Unbounded with one block.+ pub(crate) overlap: u64, } impl Segments {@@ -98,6 +124,11 @@ impl Segments { &self.segments } + /// The blocks, one `VkBuffer` each.+ pub fn blocks(&self) -> &[Block] {+ &self.blocks+ }+ /// 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.@@ -111,11 +142,31 @@ impl Segments { let Some((from, to)) = self.span(step, kind, push, tensors)? else { return Ok(None); };- if self.stride == 0 {- return Ok(Some(0));+ let block_index = match from.checked_div(self.block_stride) {+ None => 0,+ Some(index) => usize::try_from(index)+ .map_err(|_| "a block index overflowed")?+ .min(self.blocks.len().saturating_sub(1)),+ };+ let Some(block) = self.blocks.get(block_index) else {+ return Err(format!("step {step} reads at byte {from}, past the last block"));+ };+ if from < block.base || to > block.base + block.len {+ return Err(format!(+ "step {step} ({kind:?}) reads bytes {from}..{to} of the weights, a span of {} \+ against the {} one allocation is guaranteed to hold. Split the tensor in the \+ converter.",+ to - from,+ self.overlap+ ));+ }+ let (from, to) = (from - block.base, to - block.base);+ if block.stride == 0 {+ return Ok(Some(block.first)); }- let index = usize::try_from(from / self.stride).map_err(|_| "a segment index overflowed")?;- let Some(segment) = self.segments.get(index) else {+ let window = usize::try_from(from / block.stride).map_err(|_| "a segment index overflowed")?;+ let index = block.first + window;+ let Some(segment) = self.segments.get(index).filter(|s| s.block == block_index) else { return Err(format!("step {step} reads at byte {from}, past the last segment")); }; if to > segment.base + segment.len {@@ -124,7 +175,7 @@ impl Segments { against the {} one descriptor window is guaranteed to hold. Split the tensor in \ the converter.", to - from,- self.reach+ block.reach )); } Ok(Some(index))@@ -140,7 +191,10 @@ impl Segments { /// The kinds named below must stay in step with the word-unit arm of [`Kind::weight_reads`], /// which is the only place that decides what a `weight` offset counts in. pub fn rebase(&self, index: usize, kind: Kind, push: &Push) -> Push {- rebase_push(self.segments.get(index).map_or(0, |segment| segment.base), kind, push)+ let base = self.segments.get(index).map_or(0, |segment| {+ self.blocks.get(segment.block).map_or(0, |block| block.base) + segment.base+ });+ rebase_push(base, kind, push) } /// The `[from, to)` byte span of the weights one op reads, or `None` if it reads none.
library/ml/src/main/rust/src/vulkan/segment_extra.rs
diff --git a/library/ml/src/main/rust/src/vulkan/segment_extra.rs b/library/ml/src/main/rust/src/vulkan/segment_extra.rsindex 2408520b79..80e6a5a057 100644--- a/library/ml/src/main/rust/src/vulkan/segment_extra.rs+++ b/library/ml/src/main/rust/src/vulkan/segment_extra.rs@@ -1,19 +1,12 @@ use super::context::Limits;-use super::segment::{Segments, Segment, ALIGNMENT, MAX_SEGMENTS};+use super::segment::{Block, Segment, Segments, ALIGNMENT, BLOCK_OVERLAP, MAX_SEGMENTS}; impl Segments {- /// Window `total` bytes of weights so that every op's tensors land inside one descriptor.+ /// Lay `total` bytes of weights out as blocks of windows, so that every op's tensors land+ /// inside one block and 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 {@@ -22,30 +15,200 @@ impl Segments { {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 });+ let mut segments = Vec::new();+ if total <= limits.max_memory_allocation_size {+ // Every file before Gemma 4: one allocation, windowed exactly as it always was.+ let block = windows(0, 0, total, range, granularity, &mut segments)?;+ return Ok(Segments { segments, blocks: vec![block], block_stride: 0, overlap: u64::MAX }); }- // 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"));++ // Never more than a window on this device could reach, so a forced small range shrinks+ // it too and the parity fixtures can cross a block boundary at a few tens of MiB.+ let window_reach = range - ((range / 4) / granularity) * granularity;+ let overlap = (BLOCK_OVERLAP.min(window_reach) / granularity) * granularity;+ // Rounded down so `get_buffer_memory_requirements` padding cannot push a block past it.+ let cap = (limits.max_memory_allocation_size >> 20) << 20;+ if cap <= overlap {+ return Err(format!(+ "maxMemoryAllocationSize {} leaves no room past a {overlap}-byte block overlap",+ limits.max_memory_allocation_size+ )); }- let count = usize::try_from(total.div_ceil(stride)).map_err(|_| "too many segments")?;+ // Equal blocks rather than full ones and a tail: smaller allocations are likelier to+ // succeed on a heap shared with the rest of the system, and the overlap costs the same.+ let count = (total - overlap).div_ceil(cap - overlap);+ let block_stride = (total - overlap).div_ceil(count).div_ceil(granularity) * granularity;+ let count = usize::try_from(count).map_err(|_| "too many blocks")?; if count > MAX_SEGMENTS {+ return Err(format!("{total} bytes of weights need {count} allocations"));+ }+ let mut blocks = Vec::with_capacity(count);+ for index in 0..count {+ let base = index as u64 * block_stride;+ if base >= total {+ break;+ }+ let len = (block_stride + overlap).min(total - base);+ blocks.push(windows(index, base, len, range, granularity, &mut segments)?);+ }+ if segments.len() > MAX_SEGMENTS { return Err(format!(- "{total} bytes of weights need {count} descriptor windows at a \- maxStorageBufferRange of {range}, past the {MAX_SEGMENTS} this allows"+ "{total} bytes of weights need {} descriptor windows, past the {MAX_SEGMENTS} \+ this allows",+ segments.len() )); }- 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 })+ Ok(Segments { segments, blocks, block_stride, overlap })+ }+}++/// Window block `block`, `len` bytes at weights byte `base`, appending its segments.+fn windows(+ block: usize,+ base: u64,+ len: u64,+ range: u64,+ granularity: u64,+ segments: &mut Vec<Segment>,+) -> Result<Block, String> {+ let first = segments.len();+ if len <= range {+ // The overwhelmingly common case: one descriptor over the whole block, `base` zero, so+ // `rebase` moves only by the block's own offset.+ segments.push(Segment { block, base: 0, len });+ return Ok(Block { base, len, first, 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(len.div_ceil(stride)).map_err(|_| "too many segments")?;+ if count > MAX_SEGMENTS {+ return Err(format!(+ "{len} bytes of weights need {count} descriptor windows at a \+ maxStorageBufferRange of {range}, past the {MAX_SEGMENTS} this allows"+ ));+ }+ segments.extend((0..count).map(|index| {+ let at = index as u64 * stride;+ Segment { block, base: at, len: range.min(len - at) }+ }));+ Ok(Block { base, len, first, stride, reach: range - stride })+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::nets::{Kind, Push};+ use crate::weights::{Dtype, Tensor};++ const GIB: u64 = 1 << 30;+ const MIB: u64 = 1 << 20;+ const GEMMA4_TEXT: u64 = 1_101_558_320;++ fn limits(range: u64, allocation: u64) -> Limits {+ Limits {+ max_storage_buffer_range: range,+ min_storage_buffer_offset_alignment: 64,+ max_memory_allocation_size: allocation,+ timestamp_period: 1.0,+ timestamp_valid_bits: 0,+ }+ }++ fn f16(offset: u64, bytes: u64) -> Tensor {+ Tensor {+ rank: 1,+ dims: [(bytes / 2) as u32, 0, 0, 0],+ offset: offset as u32,+ len: (bytes / 2) as u32,+ dtype: Dtype::F16,+ }+ }++ /// An op reading only an fp16 `weight` at byte `at`.+ fn reading(at: u64) -> (Kind, Push) {+ (Kind::RmsNorm, Push { weight: (at / 2) as u32, ..Push::default() })+ }++ fn check_blocks(segments: &Segments, total: u64, cap: u64) {+ let blocks = segments.blocks();+ assert_eq!(blocks.first().map(|b| b.base), Some(0));+ assert_eq!(blocks.last().map(|b| b.base + b.len), Some(total));+ for pair in blocks.windows(2) {+ assert_eq!(pair[0].base + pair[0].len - pair[1].base, segments.overlap);+ }+ assert!(blocks.iter().all(|b| b.len <= cap && b.base % 64 == 0));+ for segment in segments.all() {+ let block = blocks[segment.block];+ assert!(segment.base + segment.len <= block.len);+ }+ }++ #[test]+ fn a_file_under_the_allocation_limit_is_one_block_as_before() {+ let segments = Segments::plan(318 * MIB, &limits(128 * MIB, GIB)).expect("plans");+ assert_eq!(segments.blocks().len(), 1);+ assert_eq!(segments.block_stride, 0);+ let all = segments.all();+ assert_eq!(all.len(), 318usize.div_ceil(32));+ assert!(all.iter().all(|s| s.block == 0 && s.len <= 128 * MIB));+ assert_eq!(all[1].base, 32 * MIB);+ }++ #[test]+ fn gemma4_text_splits_into_two_blocks_at_the_adreno_limit() {+ for range in [128 * MIB, 4 * GIB - 1] {+ let segments = Segments::plan(GEMMA4_TEXT, &limits(range, GIB)).expect("plans");+ assert_eq!(segments.blocks().len(), 2, "range {range}");+ assert_eq!(segments.overlap, 96 * MIB);+ check_blocks(&segments, GEMMA4_TEXT, GIB);+ }+ }++ #[test]+ fn a_span_resolves_to_the_block_it_starts_in() {+ let segments = Segments::plan(GEMMA4_TEXT, &limits(4 * GIB - 1, GIB)).expect("plans");+ let stride = segments.block_stride;+ let tensors = [f16(0, 8 * MIB), f16(stride - 4 * MIB, 64 * MIB), f16(stride + 8 * MIB, MIB)];+ let resolve = |at: u64| {+ let (kind, push) = reading(at);+ segments.for_op(0, kind, &push, &tensors).expect("fits").expect("reads weights")+ };+ assert_eq!(segments.all()[resolve(0)].block, 0);+ // Straddles the second block's base, but inside the overlap of the first.+ assert_eq!(segments.all()[resolve(stride - 4 * MIB)].block, 0);+ let later = resolve(stride + 8 * MIB);+ assert_eq!(segments.all()[later].block, 1);+ let (kind, push) = reading(stride + 8 * MIB);+ assert_eq!(segments.rebase(later, kind, &push).weight, (8 * MIB / 2) as u32);+ }++ #[test]+ fn a_span_longer_than_the_overlap_across_a_cut_is_refused() {+ let segments = Segments::plan(GEMMA4_TEXT, &limits(4 * GIB - 1, GIB)).expect("plans");+ let start = segments.block_stride - MIB;+ let tensors = [f16(start, 100 * MIB)];+ let (kind, push) = reading(start);+ assert!(segments.for_op(0, kind, &push, &tensors).is_err());+ }++ #[test]+ fn forced_small_limits_put_a_late_tensor_in_a_later_block() {+ // The shape `parity_part3`'s 44 MiB fixture takes under+ // MODELRUNNER_MAX_STORAGE_RANGE=MODELRUNNER_MAX_ALLOCATION=33554432.+ let total = 44 * MIB + 4096;+ let segments = Segments::plan(total, &limits(32 * MIB, 32 * MIB)).expect("plans");+ assert_eq!(segments.overlap, 24 * MIB);+ assert!(segments.blocks().len() >= 2);+ check_blocks(&segments, total, 32 * MIB);+ let tensors = [f16(44 * MIB, 4096)];+ let (kind, push) = reading(44 * MIB);+ let index = segments.for_op(0, kind, &push, &tensors).expect("fits").expect("reads");+ let block = segments.blocks()[segments.all()[index].block];+ assert!(block.base > 0);+ let rebased = segments.rebase(index, kind, &push).weight;+ assert_eq!(u64::from(rebased) * 2, 44 * MIB - block.base - segments.all()[index].base); } }