ml: persist the pipeline cache and reuse built plans across reshapes
- Commit
03a24803b89cdb1ccec9dd55a718800821daa990- Author
- vayun-mathur <[email protected]>
- When
- 2026-10-25 20:28 UTC (1 month ago)
- Parents
bce1e8b
Diff
library/ml/src/main/rust/src/nets/mod_part2.rs
diff --git a/library/ml/src/main/rust/src/nets/mod_part2.rs b/library/ml/src/main/rust/src/nets/mod_part2.rsindex 7a86a91eca..fb232ea2f8 100644--- a/library/ml/src/main/rust/src/nets/mod_part2.rs+++ b/library/ml/src/main/rust/src/nets/mod_part2.rs@@ -36,7 +36,7 @@ pub struct Binding { } /// A compiled forward pass: what to run, and how much scratch it needs.-#[derive(Debug, PartialEq, Eq)]+#[derive(Clone, Debug, PartialEq, Eq)] pub struct Plan { /// In order. Each depends on the results of the ones before it. pub ops: Vec<Op>,
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 8a14b299c4..d64eefaf82 100644--- a/library/ml/src/main/rust/src/vulkan/mod.rs+++ b/library/ml/src/main/rust/src/vulkan/mod.rs@@ -22,6 +22,7 @@ pub mod context; pub mod imageprobe; pub mod pipeline; pub mod pipeline_extra;+mod pipeline_cache; pub mod reshape; pub mod run; pub mod segment;
library/ml/src/main/rust/src/vulkan/pipeline_cache.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline_cache.rs b/library/ml/src/main/rust/src/vulkan/pipeline_cache.rsnew file mode 100644index 0000000000..d6f8631070--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/pipeline_cache.rs@@ -0,0 +1,96 @@+//! A `VkPipelineCache` kept on disk, so compiling every compute shader is paid once per install+//! rather than once per process.+//!+//! Building the ~46 pipelines took 918 ms on a Pixel 8 every time a process first used a model:+//! the translator's first sentence, the dictation's first word. The driver can serialise what it+//! compiled and accept it back next time, and validates the blob's header (vendor, device, driver+//! UUID) itself, so a stale or foreign file is ignored rather than trusted.+//!+//! # Where the file goes+//!+//! `MODELRUNNER_CACHE_DIR` when set - the cross-compiled test binaries set it. Otherwise, on+//! Android, the app's own `code_cache` directory, derived from the process name and the user id so+//! no Kotlin has to hand a path down: `/data/user/<uid / 100000>/<package>/code_cache`. Anything+//! that fails along the way means no cache, never an error: the pipelines are built exactly as+//! before.++use std::path::PathBuf;++use ash::vk;++/// The file name inside the cache directory.+const FILE: &str = "modelrunner_pipelines.bin";++/// Where the cache file lives, or `None` to run without one.+fn path() -> Option<PathBuf> {+ if let Some(dir) = crate::knobs::get("cache_dir") {+ return Some(PathBuf::from(dir).join(FILE));+ }+ android_code_cache().map(|dir| dir.join(FILE))+}++#[cfg(target_os = "android")]+fn android_code_cache() -> Option<PathBuf> {+ extern "C" {+ fn getuid() -> u32;+ }+ let cmdline = std::fs::read("/proc/self/cmdline").ok()?;+ let name = cmdline.split(|&b| b == 0).next()?;+ let name = std::str::from_utf8(name).ok()?;+ // A secondary process is `package:name`; its files are the package's.+ let package = name.split(':').next()?;+ if package.is_empty() || package.contains('/') {+ // A shell-launched binary, whose "name" is a path.+ return None;+ }+ // SAFETY: `getuid` takes nothing and cannot fail.+ let user = unsafe { getuid() } / 100_000;+ let dir = PathBuf::from(format!("/data/user/{user}/{package}/code_cache"));+ dir.is_dir().then_some(dir)+}++#[cfg(not(target_os = "android"))]+fn android_code_cache() -> Option<PathBuf> {+ None+}++/// A pipeline cache seeded from disk, or an empty one when there is nothing usable to seed it.+///+/// # Safety+///+/// `device` must be live; the returned cache must be destroyed with it.+pub(crate) unsafe fn open(device: &ash::Device) -> (vk::PipelineCache, Vec<u8>) {+ let seed = path().and_then(|p| std::fs::read(p).ok()).unwrap_or_default();+ let info = vk::PipelineCacheCreateInfo::default().initial_data(&seed);+ match device.create_pipeline_cache(&info, None) {+ Ok(cache) => (cache, seed),+ // A driver that rejects the seed outright rather than ignoring it: start empty.+ Err(_) => match device.create_pipeline_cache(&vk::PipelineCacheCreateInfo::default(), None) {+ Ok(cache) => (cache, Vec::new()),+ Err(_) => (vk::PipelineCache::null(), Vec::new()),+ },+ }+}++/// Write the cache back if it holds anything the seed did not, then destroy it.+///+/// Written to a temporary name and renamed, so a process killed mid-write leaves the old file or+/// none - never half of one for the next launch to hand the driver.+///+/// # Safety+///+/// `cache` must come from [`open`] on `device`, and no pipeline creation may be using it.+pub(crate) unsafe fn close(device: &ash::Device, cache: vk::PipelineCache, seed: &[u8]) {+ if cache == vk::PipelineCache::null() {+ return;+ }+ if let (Some(path), Ok(data)) = (path(), device.get_pipeline_cache_data(cache)) {+ if !data.is_empty() && data != seed {+ let staging = path.with_extension("tmp");+ if std::fs::write(&staging, &data).is_ok() {+ let _ = std::fs::rename(&staging, &path);+ }+ }+ }+ device.destroy_pipeline_cache(cache, None);+}
library/ml/src/main/rust/src/vulkan/pipeline_extra.rs
diff --git a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rsindex 2d4498aaf4..e3ba1ea032 100644--- a/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs+++ b/library/ml/src/main/rust/src/vulkan/pipeline_extra.rs@@ -96,17 +96,29 @@ impl Shaders { cleanup.layout = Some(layout); let mut built = Vec::new();+ // Seeded from the previous launch's compile, if the driver accepts it. See+ // `pipeline_cache`.+ let (cache, seed) = super::pipeline_cache::open(device);+ let started = std::time::Instant::now(); for spirv in SPIRV {- match compute_pipeline(device, layout, spirv) {+ match compute_pipeline(device, layout, cache, spirv) { Ok(pipeline) => built.push(pipeline), Err(e) => { for pipeline in built { device.destroy_pipeline(pipeline, None); }+ super::pipeline_cache::close(device, cache, &seed); return Err(e); } } }+ crate::timing!(+ "compiled {} pipelines in {:.0} ms ({} cached bytes in)",+ SPIRV.len(),+ started.elapsed().as_secs_f64() * 1000.0,+ seed.len()+ );+ super::pipeline_cache::close(device, cache, &seed); // A fixed-size array rather than a slice pattern of thirteen bindings, so // adding a shader is one entry in `SPIRV` and one name here. let [@@ -336,6 +348,7 @@ impl Shaders { pub(crate) unsafe fn compute_pipeline( device: &ash::Device, layout: vk::PipelineLayout,+ cache: vk::PipelineCache, spirv: &[u8], ) -> Result<vk::Pipeline, String> { let module = shader_module(device, spirv)?;@@ -345,7 +358,7 @@ pub(crate) unsafe fn compute_pipeline( .name(c"main"); let info = vk::ComputePipelineCreateInfo::default().stage(stage).layout(layout); let result = device- .create_compute_pipelines(vk::PipelineCache::null(), std::slice::from_ref(&info), None)+ .create_compute_pipelines(cache, std::slice::from_ref(&info), None) .map_err(|(_, e)| format!("create_compute_pipelines {e:?}")) .and_then(|pipelines| { pipelines
library/ml/src/main/rust/src/vulkan/reshape.rs
diff --git a/library/ml/src/main/rust/src/vulkan/reshape.rs b/library/ml/src/main/rust/src/vulkan/reshape.rsindex bc34094eb0..5d1310bd9a 100644--- a/library/ml/src/main/rust/src/vulkan/reshape.rs+++ b/library/ml/src/main/rust/src/vulkan/reshape.rs@@ -31,8 +31,19 @@ pub struct Reshaped<S> { offsets: Offsets, at: S, plan: fn(&Offsets, S) -> Result<Plan, String>,+ /// The most recently built plans, newest last, so a shape seen again skips the build.+ ///+ /// Building a plan is pure CPU work over the graph and costs more than recording it: on a+ /// Pixel 8, 17-39 ms for NLLB's two passes against 5-8 ms to record. A translation switches+ /// between the same two shapes for every sentence of the same length, so this turns the+ /// re-record into a clone of an already-built plan. Keyed by `S` because the plan is a pure+ /// function of the shape and the table.+ built: Vec<(S, Plan)>, } +/// Plans [`Reshaped`] keeps. Enough for an encoder and a decoder at a couple of lengths.+const BUILT_PLANS: usize = 4;+ impl<S: Copy + PartialEq> Reshaped<S> { /// Upload `weights`, record at `shape`, and keep only the table. ///@@ -65,8 +76,10 @@ impl<S: Copy + PartialEq> Reshaped<S> { shape: S, plan: fn(&Offsets, S) -> Result<Plan, String>, ) -> Result<Reshaped<S>, String> {- let net = Net::new(context, plan(&offsets, shape)?, data, RESCALE_ONLY)?;- Ok(Reshaped { net, offsets, at: shape, plan })+ let first = plan(&offsets, shape)?;+ let built = vec![(shape, first.clone())];+ let net = Net::new(context, first, data, RESCALE_ONLY)?;+ Ok(Reshaped { net, offsets, at: shape, plan, built }) } /// The net recorded at `shape`, re-recording it first if it is not already.@@ -77,7 +90,31 @@ impl<S: Copy + PartialEq> Reshaped<S> { /// where one is needed. pub fn at(&mut self, shape: S) -> Result<&mut Net, String> { if shape != self.at {- self.net.rebuild((self.plan)(&self.offsets, shape)?)?;+ let started = std::time::Instant::now();+ let plan = match self.built.iter().position(|(key, _)| *key == shape) {+ Some(index) => {+ let entry = self.built.remove(index);+ let plan = entry.1.clone();+ self.built.push(entry);+ plan+ }+ None => {+ let plan = (self.plan)(&self.offsets, shape)?;+ if self.built.len() == BUILT_PLANS {+ self.built.remove(0);+ }+ self.built.push((shape, plan.clone()));+ plan+ }+ };+ let built = started.elapsed();+ self.net.rebuild(plan)?;+ crate::timing!(+ "reshape {:.1} ms: plan {:.1} ms, rebuild {:.1} ms",+ started.elapsed().as_secs_f64() * 1e3,+ built.as_secs_f64() * 1e3,+ (started.elapsed() - built).as_secs_f64() * 1e3+ ); self.at = shape; } Ok(&mut self.net)