Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
translate ▾

Modern-Apps.git / library / ml / src / main / rust / examples / probe_limits.rs

probe_limits.rs217 lines · 8.2 KiBRaw
1//! Reports the three device limits a `.maml` file has to fit inside, and finds the largest
2//! single device-local allocation that actually succeeds.
3//!
4//! ```text
5//! cargo run --offline -p modelrunner --example probe_limits
6//! ```
7//!
8//! # Why this exists
9//!
10//! `modelrunner::vulkan::run` splits the weights into blocks of at most `maxMemoryAllocationSize`
11//! (see `modelrunner::vulkan::segment`), so the reported limit decides how many allocations a
12//! model takes. What it cannot decide is whether each one actually succeeds.
13//!
14//! A reported limit and a limit that works are different things — a driver may advertise a
15//! number it cannot honour once the heap is shared with a compositor — so this asks the device
16//! for the number *and* then tries the allocation.
17//!
18//! # Reading the result on a desktop GPU
19//!
20//! A discrete card with its own VRAM will report and satisfy allocations far beyond anything a
21//! phone will. This probe can therefore **rule a model out** but never rule one in: a failure
22//! here is conclusive, a success here says nothing about an Adreno or Mali part sharing system
23//! RAM with the rest of Android. Run it on the target handset before believing it.
24use std::sync::Arc;
25
26use ash::vk;
27use modelrunner::vulkan::buffers::Buffer;
28use modelrunner::vulkan::context::{self, Context};
29
30/// Sizes worth naming in the output, largest last.
31///
32/// The first is the spec's guaranteed floor for `maxMemoryAllocationSize`; the rest are the
33/// weights sizes of models the runtime either loads today or has been proposed for.
34const LANDMARKS: &[(&str, u64)] = &[
35 ("NLLB-200 600M distilled, int8 (ships today)", 617 << 20),
36 ("Vulkan guaranteed maxMemoryAllocationSize floor", 1 << 30),
37 ("Gemma 3n E2B, per-block int4 BLOCK=64 (~4.25 bpw)", 2_660_000_000),
38 ("Gemma 3n E2B, per-block int4 BLOCK=32 (~4.5 bpw)", 2_800_000_000),
39];
40
41fn main() {
42 let context = match context::shared() {
43 Ok(context) => context,
44 Err(why) => {
45 println!("no usable Vulkan device: {why}");
46 println!();
47 println!("This runtime requires VK_KHR_shader_float16_int8. A device without it");
48 println!("reports itself unavailable rather than falling back to the CPU.");
49 return;
50 }
51 };
52
53 describe_device(&context);
54 describe_limits(&context);
55 describe_heaps(&context);
56 probe_allocations(&context);
57}
58
59/// Name and driver of the device the runtime actually chose.
60fn describe_device(context: &Arc<Context>) {
61 // SAFETY: a plain property query on the physical device the context already selected and
62 // holds alive. No pointers are retained past the call.
63 let properties =
64 unsafe { context.instance.get_physical_device_properties(context.physical_device) };
65 let name = properties
66 .device_name_as_c_str()
67 .map(|name| name.to_string_lossy().into_owned())
68 .unwrap_or_else(|_| "<unnamed>".to_owned());
69 let api = properties.api_version;
70 println!("device {name}");
71 println!(
72 "type {}, Vulkan {}.{}.{}",
73 device_type(properties.device_type),
74 vk::api_version_major(api),
75 vk::api_version_minor(api),
76 vk::api_version_patch(api),
77 );
78 println!();
79}
80
81/// `VkPhysicalDeviceType` as a word.
82///
83/// Spelled out because `ash` is built with `default-features = false`, which drops the `debug`
84/// feature and with it every `Debug` impl on its enums.
85fn device_type(kind: vk::PhysicalDeviceType) -> &'static str {
86 match kind {
87 vk::PhysicalDeviceType::INTEGRATED_GPU => "integrated GPU",
88 vk::PhysicalDeviceType::DISCRETE_GPU => "discrete GPU",
89 vk::PhysicalDeviceType::VIRTUAL_GPU => "virtual GPU",
90 vk::PhysicalDeviceType::CPU => "CPU",
91 _ => "other",
92 }
93}
94
95/// The three limits, each against the floor the spec guarantees.
96fn describe_limits(context: &Arc<Context>) {
97 let limits = context.limits;
98 println!("limits");
99 println!(
100 " maxMemoryAllocationSize {:>14} (spec floor {})",
101 bytes(limits.max_memory_allocation_size),
102 bytes(1 << 30),
103 );
104 println!(
105 " maxStorageBufferRange {:>14} (spec floor {})",
106 bytes(limits.max_storage_buffer_range),
107 bytes(128 << 20),
108 );
109 println!(
110 " minStorageBufferOffsetAlignment {:>14}",
111 limits.min_storage_buffer_offset_alignment,
112 );
113 if std::env::var("MODELRUNNER_MAX_STORAGE_RANGE").is_ok() {
114 println!(" (MODELRUNNER_MAX_STORAGE_RANGE is set, so the range above is forced)");
115 }
116 if std::env::var("MODELRUNNER_MAX_ALLOCATION").is_ok() {
117 println!(" (MODELRUNNER_MAX_ALLOCATION is set, so the allocation limit above is forced)");
118 }
119 println!();
120}
121
122/// Every memory heap, flagging the device-local ones an allocation can come from.
123fn describe_heaps(context: &Arc<Context>) {
124 // SAFETY: as `describe_device`. The returned struct is plain data, copied out by value.
125 let memory =
126 unsafe { context.instance.get_physical_device_memory_properties(context.physical_device) };
127 println!("heaps");
128 for index in 0..memory.memory_heap_count as usize {
129 let heap = memory.memory_heaps[index];
130 let local = heap.flags.contains(vk::MemoryHeapFlags::DEVICE_LOCAL);
131 println!(
132 " {index} {:>12} {}",
133 bytes(heap.size),
134 if local { "DEVICE_LOCAL" } else { "host" },
135 );
136 }
137 println!();
138}
139
140/// Try the named sizes, then bisect for the true ceiling.
141fn probe_allocations(context: &Arc<Context>) {
142 println!("allocations (one Buffer::device_local, as run.rs makes for the weights)");
143 let mut largest_ok = 0u64;
144 for &(what, size) in LANDMARKS {
145 let ok = try_allocate(context, size);
146 if ok {
147 largest_ok = largest_ok.max(size);
148 }
149 println!(" {:>12} {} {what}", bytes(size), if ok { "ok " } else { "FAIL" });
150 }
151 println!();
152
153 let reported = context.limits.max_memory_allocation_size;
154 let ceiling = if try_allocate(context, reported) {
155 println!(
156 "largest successful single allocation {} (the reported limit, honoured)",
157 bytes(reported)
158 );
159 reported
160 } else {
161 // Bisect between the largest size known to work and the smallest known to fail.
162 // Starting the upper bound at the reported limit keeps this to ~30 probes.
163 let mut low = largest_ok;
164 let mut high = reported;
165 while low + (1 << 20) < high {
166 let mid = low + (high - low) / 2;
167 if try_allocate(context, mid) {
168 low = mid;
169 } else {
170 high = mid;
171 }
172 }
173 println!("largest successful single allocation {}", bytes(low));
174 println!(
175 " the reported {} is not backed by memory; this is the heap talking",
176 bytes(reported)
177 );
178 low
179 };
180 println!();
181
182 let needed = 2_800_000_000u64;
183 if ceiling >= needed {
184 println!("verdict fits Gemma 3n E2B at int4 ({}) in one buffer", bytes(needed));
185 } else {
186 println!("verdict does NOT fit Gemma 3n E2B at int4 ({}) in one buffer", bytes(needed));
187 println!(" the runtime will split its weights across several blocks");
188 }
189 println!();
190 println!("A desktop GPU passing this says nothing about a phone. See the module docs.");
191}
192
193/// Whether one device-local allocation of `size` succeeds. The buffer is freed immediately.
194fn try_allocate(context: &Arc<Context>, size: u64) -> bool {
195 if size == 0 || size > context.limits.max_memory_allocation_size {
196 return false;
197 }
198 Buffer::device_local(context, size as vk::DeviceSize).is_ok()
199}
200
201/// A byte count as the unit a human would read it in.
202///
203/// `u64::MAX` is called out rather than rendered: a driver reporting it means "no limit beyond
204/// the heap", and printing 16 billion GiB reads as a bug in the probe.
205fn bytes(value: u64) -> String {
206 if value == u64::MAX {
207 return "unbounded".to_owned();
208 }
209 const UNITS: [(&str, u64); 4] =
210 [("TiB", 1 << 40), ("GiB", 1 << 30), ("MiB", 1 << 20), ("KiB", 1 << 10)];
211 for (unit, scale) in UNITS {
212 if value >= scale {
213 return format!("{:.2} {unit}", value as f64 / scale as f64);
214 }
215 }
216 format!("{value} B")
217}