Modern Apps git

← Modern-Apps.git

ml: per-op device timestamps behind MODELRUNNER_TIMESTAMPS

Commit
51887e60a6b8b81b49ffe62a8c3b57172c6a13e4
Author
vayun-mathur <[email protected]>
When
2026-09-30 00:01 UTC (2 months ago)
Parents
9fcf232

Diff

library/ml/src/main/rust/examples/check_gemma4_parity.rs
diff --git a/library/ml/src/main/rust/examples/check_gemma4_parity.rs b/library/ml/src/main/rust/examples/check_gemma4_parity.rsindex 8f03fa000c..9d9e7c7420 100644--- a/library/ml/src/main/rust/examples/check_gemma4_parity.rs+++ b/library/ml/src/main/rust/examples/check_gemma4_parity.rs@@ -297,7 +297,17 @@ fn time_decode(     let reader = embed.reader();     let rotary = weights.reader();     let repeats = repeats.max(1);+    // Per-op device times, read once from the last step's submit when the+    // timestamps knob is set. Hoisted: a property lookup per step would be+    // noise in what is being timed.+    let stamps = modelrunner::knobs::is_set("timestamps");+    let mut op_report: Option<Vec<(String, f64, f64)>> = None;     let mut steady: Vec<f64> = Vec::new();+    // Host-side split: gather+rotary file reads vs device infer per step.+    // Accumulated over steady-state passes only, reported once.+    let mut host_ms = 0.0;+    let mut infer_ms = 0.0;+    let mut host_steps = 0usize;     for pass in 0..repeats {         let mut step_ms: Vec<f64> = Vec::with_capacity(tokens.len());         for (step, &token) in tokens.iter().enumerate() {@@ -306,6 +316,7 @@ fn time_decode(                 Ok(p) => p,                 Err(_) => return println!("a step past u32"),             };+            let host_tick = Instant::now();             let Ok((hidden_in, per_layer)) = gemma4::gather(&reader, token) else {                 return println!("gather failed at step {step}");             };@@ -319,6 +330,7 @@ fn time_decode(             else {                 return println!("rotary global failed at step {step}");             };+            let host_done = host_tick.elapsed().as_secs_f64() * 1000.0;             let at = match net.at(gemma4::Mode::DecodeStep.at(TIER)) {                 Ok(at) => at,                 Err(why) => return println!("the net does not bind at step {step}: {why}"),@@ -332,10 +344,24 @@ fn time_decode(             {                 return println!("params failed at step {step}");             }+            let infer_tick = Instant::now();             match at.infer_raw_many(&[&hidden_in, &per_layer, &angles_local, &angles_global]) {                 Ok(_) => {}                 Err(why) => return println!("step {step} failed: {why}"),             }+            if pass > 0 {+                host_ms += host_done;+                infer_ms += infer_tick.elapsed().as_secs_f64() * 1000.0;+                host_steps += 1;+            }+            // The query pool holds this submit's timestamps once the fence+            // waited above returns; the last step's is the steady-state plan.+            if stamps && pass + 1 == repeats && step + 1 == tokens.len() {+                match at.op_times() {+                    Ok(report) => op_report = Some(report),+                    Err(why) => println!("timestamps unreadable: {why}"),+                }+            }             step_ms.push(tick.elapsed().as_secs_f64() * 1000.0);         }         let mean = step_ms.iter().sum::<f64>() / step_ms.len().max(1) as f64;@@ -351,6 +377,53 @@ fn time_decode(         let mean = steady.iter().sum::<f64>() / steady.len() as f64;         println!("steady-state: {mean:.1} ms/token = {:.2} tok/s", 1000.0 / mean.max(1e-9));     }+    if host_steps > 0 {+        println!(+            "host split per step: gather+rotary {:.1} ms, infer {:.1} ms ({} steps)",+            host_ms / host_steps as f64,+            infer_ms / host_steps as f64,+            host_steps+        );+    }+    // Per-op device times, hottest first, then aggregated by Kind. The table+    // that splits a step into kernel execution: it answers whether GEMV ALU,+    // occupancy-shaped small dispatches, or barriers own the 574 ms.+    if let Some(report) = op_report {+        println!();+        println!("{:>6} {:>10} {:>10}  {}", "step", "us", "gap-us", "kind");+        let mut per_kind: Vec<(String, usize, f64, f64)> = Vec::new();+        let mut total = 0.0;+        let mut gaps = 0.0;+        for (label, us, gap) in &report {+            println!("{label:>6} {us:>10.1} {gap:>10.1}");+            total += us;+            gaps += gap;+            let kind = label.split(':').nth(1).unwrap_or("?").trim().to_string();+            match per_kind.iter_mut().find(|(k, _, _, _)| *k == kind) {+                Some((_, n, t, g)) => {+                    *n += 1;+                    *t += us;+                    *g += gap;+                }+                None => per_kind.push((kind, 1, *us, *gap)),+            }+        }+        per_kind.sort_by(|a, b| b.2.partial_cmp(&a.2).unwrap_or(std::cmp::Ordering::Equal));+        println!();+        println!("{:>6} {:>10} {:>10} {:>10}  {}", "count", "total-ms", "mean-us", "gap-ms", "kind");+        for (kind, n, us, gap) in &per_kind {+            println!(+                "{n:>6} {:>10.1} {:>10.1} {:>10.1}  {kind}",+                us / 1000.0,+                us / *n as f64,+                gap / 1000.0+            );+        }+        println!();+        println!("timestamped device total: {:.1} ms against the step mean above", total / 1000.0);+        println!("barrier/bind gaps total: {:.1} ms", gaps / 1000.0);+        println!("(copies and host work are not timestamped)");+    } }  /// Feed every token in order and return the last step's logits.
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 a8ca4cb1f7..88a1c195db 100644--- a/library/ml/src/main/rust/src/vulkan/context.rs+++ b/library/ml/src/main/rust/src/vulkan/context.rs@@ -121,6 +121,19 @@ pub struct Limits {     pub min_storage_buffer_offset_alignment: u64,     /// `VkPhysicalDeviceMaintenance3Properties::maxMemoryAllocationSize`. At least 1 GiB.     pub max_memory_allocation_size: u64,+    /// `VkPhysicalDeviceLimits::timestampPeriod`. Nanoseconds per timestamp tick.+    ///+    /// Always present: every device has a timestamp counter. Read by+    /// [`Net::op_times`](super::run::Net::op_times).+    pub timestamp_period: f32,+    /// Timestamp bits of the compute queue family, or zero when timestamps+    /// are not implemented there.+    ///+    /// Vulkan 1.3 moved `timestampValidBits` from the device limits to+    /// [`VkQueueFamilyProperties`](ash::vk::QueueFamilyProperties): validity+    /// is per queue family, not per device. Zero means the query pool must+    /// stay uncreated and `op_times` refuses.+    pub timestamp_valid_bits: u32, }  /// Forces [`Limits::max_storage_buffer_range`] down, so the segmented path can be exercised.@@ -142,12 +155,27 @@ 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());+        // 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.+        //+        // SAFETY: a plain property query; the returned vec is owned.+        let families =+            unsafe { instance.get_physical_device_queue_family_properties(physical_device) };+        let timestamp_valid_bits = families+            .iter()+            .filter(|f| f.queue_flags.contains(vk::QueueFlags::COMPUTE))+            .map(|f| f.timestamp_valid_bits)+            .max()+            .unwrap_or(0);         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,+            timestamp_period: device.timestamp_period,+            timestamp_valid_bits,         }     } }
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 d41def018f..1a5ae33206 100644--- a/library/ml/src/main/rust/src/vulkan/run.rs+++ b/library/ml/src/main/rust/src/vulkan/run.rs@@ -69,6 +69,19 @@ use crate::timing; /// floor of 2%. Cost is also not proportional to the byte range — [`Formulation::Global`] names no /// range at all and [`Formulation::Whole`] names the entire arena, and they land 4 ms apart. The /// knob is kept so the sweep can be re-run on a new device, not because a winner is expected.+/// Whether per-op timestamp queries are recorded, read once.+///+/// `MODELRUNNER_TIMESTAMPS` or `debug.modelrunner.timestamps`, defaulting to+/// off. When on, `record` brackets every dispatch with timestamp writes and+/// [`Net::op_times`] reports each op's device time; when off, no pool exists+/// and the recording is byte-identical to what it always was. Same run-time+/// knob rationale as [`Formulation::selected`]: comparing two builds is how an+/// earlier attempt attributed a shader regression to the barrier.+fn timestamps_enabled() -> bool {+    static ON: OnceLock<bool> = OnceLock::new();+    *ON.get_or_init(|| crate::knobs::is_set("timestamps"))+}+ #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum Formulation {     /// A buffer barrier over the op's own output range. The default and the historical behaviour.@@ -272,6 +285,17 @@ pub struct Net {     command_pool: vk::CommandPool,     command_buffer: vk::CommandBuffer,     fence: vk::Fence,+    /// Timestamp query pool for per-op timings, or null when disabled.+    ///+    /// Created in [`Net::new`] and [`Net::rebuild`] when [`timestamps_enabled`]+    /// holds and the device reports timestamp bits; sized at two queries per+    /// dispatch op. `record` writes a timestamp before and after every dispatch+    /// into it, and [`Net::op_times`] reads the pairs back after a submit.+    /// Null means no timestamps were recorded and `op_times` refuses.+    query_pool: vk::QueryPool,+    /// Dispatch ops the pool was sized for. A rebuild with a different plan+    /// recreates the pool; anything else reuses it.+    query_count: u32,     /// Set when a submission was left pending, or a recording left part-written, after which     /// this net is unusable.     ///@@ -291,4 +315,5 @@ pub struct Net {  include!("run_part1.rs"); include!("run_part2.rs");-include!("run_part3.rs");\ No newline at end of file+include!("run_part3.rs");+include!("run_part4.rs");\ No newline at end of file
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 a15a1362d8..bf4b1454ed 100644--- a/library/ml/src/main/rust/src/vulkan/run_part1.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part1.rs@@ -74,6 +74,8 @@ impl Net {             command_pool,             command_buffer: vk::CommandBuffer::null(),             fence: vk::Fence::null(),+            query_pool: vk::QueryPool::null(),+            query_count: 0,             poisoned: false,             input_scratch: vec![0u16; input_elems],             output_scratch: vec![0u16; output_elems],@@ -91,6 +93,7 @@ impl Net {         // Written before the first record so a shader reading it never sees uninitialised         // memory, even on a plan that never calls `set_params`.         net.set_params(StepParams::default())?;+        net.reset_query_pool()?;         let staged = std::time::Instant::now();         net.record()?;         timing!(@@ -190,6 +193,7 @@ impl Net {         self.input_scratch.resize(input_elems, 0);         self.output_scratch.resize(output_elems, 0);         self.plan = plan;+        self.reset_query_pool()?;          // A `record` that fails leaves the command buffer part-written, and submitting that is         // not something a later caller may be allowed to do. There is no way back — both of its@@ -331,4 +335,54 @@ impl Net {                 .map_err(|e| format!("create_fence {e:?}"))         }     }++    /// Size the timestamp query pool to this plan, or leave it uncreated.+    ///+    /// Called before every `record`: a rebuild may have changed the dispatch+    /// count, and a pool sized for another plan would overrun or waste. When+    /// timestamps are disabled — or the device reports no timestamp bits —+    /// any existing pool is destroyed and the recording stays exactly what it+    /// always was. Idempotent for repeated records of one plan.+    fn reset_query_pool(&mut self) -> Result<(), String> {+        // SAFETY: plain object creation/destruction on this net's device, with+        // nothing in flight: `new` has submitted nothing yet, and `rebuild`+        // waited for idle before reaching here.+        unsafe {+            let device = &self.context.device;+            if self.query_pool != vk::QueryPool::null() {+                device.destroy_query_pool(self.query_pool, None);+                self.query_pool = vk::QueryPool::null();+                self.query_count = 0;+            }+            if !timestamps_enabled() {+                return Ok(());+            }+            if self.context.limits.timestamp_valid_bits == 0 {+                timing!(+                    "timestamps requested but the compute family reports no timestamp bits"+                );+                return Ok(());+            }+            let dispatches = self+                .plan+                .ops+                .iter()+                .filter(|op| matches!(op, Op::Dispatch { .. }))+                .count();+            let count = match u32::try_from(dispatches) {+                Ok(n) => n.checked_mul(2).ok_or_else(|| "a query count overflowed".to_string())?,+                Err(_) => return Err("a plan with more dispatches than u32".to_string()),+            };+            if count == 0 {+                return Ok(());+            }+            let info = vk::QueryPoolCreateInfo::default()+                .query_type(vk::QueryType::TIMESTAMP)+                .query_count(count);+            self.query_pool =+                device.create_query_pool(&info, None).map_err(|e| format!("create_query_pool {e:?}"))?;+            self.query_count = count;+            Ok(())+        }+    } }\ No newline at end of file
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 bf6e63b946..d8d07f85d5 100644--- a/library/ml/src/main/rust/src/vulkan/run_part2.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part2.rs@@ -34,6 +34,13 @@ impl Net {                 std::slice::from_ref(&weights_visible),                 &[],             );+            // Timestamps start clean: a query pool left over from an earlier+            // recording would otherwise report a previous submit's times.+            // A null pool is the disabled path, and nothing below is recorded.+            let stamps = self.query_pool != vk::QueryPool::null();+            if stamps {+                device.cmd_reset_query_pool(buffer, self.query_pool, 0, self.query_count);+            }              // One copy per input, packed end to end in the staging buffer in declaration             // order. Both shipping nets have exactly one; SCRFD's nine outputs come back@@ -55,9 +62,28 @@ impl Net {             }             self.barrier(buffer); +            let mut stamp_next = 0u32;             for (step, op) in self.plan.ops.iter().enumerate() {+                // Timestamp pairs count dispatches, not ops: copies take no+                // queries, so the pair index is separate from the step.                 match *op {                     Op::Dispatch { kind, push, invocations } => {+                        // Bracket the dispatch: query 2i before the bind, 2i+1+                        // after the dispatch returns, both at COMPUTE_SHADER so+                        // the delta is the dispatch's device time.+                        let stamp = if stamps {+                            let n = stamp_next;+                            stamp_next += 1;+                            device.cmd_write_timestamp(+                                buffer,+                                vk::PipelineStageFlags::COMPUTE_SHADER,+                                self.query_pool,+                                2 * n,+                            );+                            Some(n)+                        } else {+                            None+                        };                         device.cmd_bind_pipeline(                             buffer,                             vk::PipelineBindPoint::COMPUTE,@@ -100,6 +126,17 @@ impl Net {                             groups.div_ceil(MAX_WORKGROUPS_PER_DIM),                             1,                         );+                        // Close the bracket opened above, before the barrier:+                        // with the barrier between every op, the delta covers+                        // the dispatch's execution and nothing else's.+                        if let Some(n) = stamp {+                            device.cmd_write_timestamp(+                                buffer,+                                vk::PipelineStageFlags::COMPUTE_SHADER,+                                self.query_pool,+                                2 * n + 1,+                            );+                        }                     }                     Op::Copy { src, dst, elems } => {                         // Same buffer for source and destination. The spec allows that as
library/ml/src/main/rust/src/vulkan/run_part3.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part3.rs b/library/ml/src/main/rust/src/vulkan/run_part3.rsindex f26b9e18aa..47a6387cb7 100644--- a/library/ml/src/main/rust/src/vulkan/run_part3.rs+++ b/library/ml/src/main/rust/src/vulkan/run_part3.rs@@ -371,6 +371,9 @@ impl Drop for Net {             drop(guard);             device.destroy_fence(self.fence, None);             device.destroy_command_pool(self.command_pool, None);+            if self.query_pool != vk::QueryPool::null() {+                device.destroy_query_pool(self.query_pool, None);+            }             self.pipelines.destroy(device);         }     }
library/ml/src/main/rust/src/vulkan/run_part4.rs
diff --git a/library/ml/src/main/rust/src/vulkan/run_part4.rs b/library/ml/src/main/rust/src/vulkan/run_part4.rsnew file mode 100644index 0000000000..fd5a3e7bd3--- /dev/null+++ b/library/ml/src/main/rust/src/vulkan/run_part4.rs@@ -0,0 +1,77 @@+impl Net {+    /// Per-dispatch device times in microseconds, in plan order, plus the+    /// gap after each op.+    ///+    /// Reads back the timestamp pairs `record` bracketed every dispatch with,+    /// when [`timestamps_enabled`] held at record time. Each entry names the+    /// op (`"{step}: {Kind:?}"`), its COMPUTE_SHADER-stage delta converted by+    /// `timestampPeriod`, and the gap to the next dispatch's start stamp —+    /// which is the barrier (plus bind/push/dispatch issue) between them.+    /// Entries cover dispatch ops only — copies take no queries.+    ///+    /// Call after an inference returns: the fence wait guarantees the results+    /// are available, and `WAIT` covers the gap anyway. Returns an error when+    /// no timestamps were recorded rather than rows of zeros that would read+    /// as impossibly fast dispatches.+    pub fn op_times(&self) -> Result<Vec<(String, f64, f64)>, String> {+        if self.query_pool == vk::QueryPool::null() {+            return Err("no timestamps recorded: set MODELRUNNER_TIMESTAMPS=1".into());+        }+        let dispatches = self+            .plan+            .ops+            .iter()+            .filter(|op| matches!(op, Op::Dispatch { .. }))+            .count();+        if dispatches == 0 {+            return Ok(Vec::new());+        }+        let mut raw = vec![0u64; dispatches * 2];+        // SAFETY: the pool was created for exactly this many queries, the last+        // submit's fence was waited on before `infer` returned, and `WAIT`+        // covers any remaining gap. ash derives the count and stride from the+        // slice: one u64 per query.+        unsafe {+            self.context+                .device+                .get_query_pool_results(+                    self.query_pool,+                    0,+                    &mut raw,+                    vk::QueryResultFlags::TYPE_64 | vk::QueryResultFlags::WAIT,+                )+                .map_err(|e| format!("get_query_pool_results {e:?}"))?;+        }+        let period = f64::from(self.context.limits.timestamp_period);+        // Raw starts and ends per dispatch, to attribute the gaps between+        // them (barriers + bind/push/issue) as well as the deltas.+        let mut stamps: Vec<(u64, u64)> = Vec::with_capacity(dispatches);+        for pair in 0..dispatches {+            match (raw.get(2 * pair), raw.get(2 * pair + 1)) {+                (Some(&b), Some(&a)) => stamps.push((b, a)),+                _ => return Err(format!("timestamp pair {pair} missing")),+            }+        }+        let mut out = Vec::with_capacity(dispatches);+        let mut dispatch = 0usize;+        for (step, op) in self.plan.ops.iter().enumerate() {+            let Op::Dispatch { kind, .. } = op else { continue };+            let (before, after) = stamps[dispatch];+            // Wrapping subtraction: the counter is only `timestampValidBits`+            // wide and wraps within a long submit.+            let ticks = after.wrapping_sub(before);+            let gap = if dispatch + 1 < dispatches {+                stamps[dispatch + 1].0.wrapping_sub(after)+            } else {+                0+            };+            dispatch += 1;+            out.push((+                format!("{step}: {kind:?}"),+                ticks as f64 * period / 1000.0,+                gap as f64 * period / 1000.0,+            ));+        }+        Ok(out)+    }+}