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

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

report_gemv_scaling.rs142 lines · 5.4 KiBRaw
1//! Does a gemv reach the same bandwidth at every matrix size?
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example report_gemv_scaling
5//! ```
6//!
7//! # The question
8//!
9//! On a Tensor G4 the logits head reads its 201 MB of int4 weights at about 9.6 GB/s while the
10//! per-layer projections manage 4.9, using the *same shader*. The only difference is shape: the
11//! head is four `[65536, 1536]` matrices and a projection is `[1536, 1536]` or thereabouts.
12//!
13//! If a dispatch needs a while to reach streaming speed - filling the pipeline, warming the
14//! caches, getting enough workgroups in flight - then small dispatches never get there and the
15//! achieved bandwidth rises with size. That would make merging independent projections into one
16//! dispatch worth doing, and would explain why removing dispatches did nothing while making them
17//! *bigger* might.
18//!
19//! If instead every size reaches the same rate, shape is not the story and the difference lies
20//! somewhere else.
21use std::sync::Arc;
22
23use modelrunner::nets::{Act, Builder, Shape, WeightSource};
24use modelrunner::preprocess::RESCALE_ONLY;
25use modelrunner::vulkan::context;
26use modelrunner::vulkan::run::Net;
27use modelrunner::weights::{Blob, Dtype, Tensor};
28
29/// A blob of identical bytes with a matching tensor table.
30///
31/// The table is not decoration: `vulkan::segment` uses it to bound what each op may read, and
32/// refuses a plan whose reads fall outside it.
33struct Filler {
34 bytes: Vec<u8>,
35 table: Vec<Tensor>,
36}
37
38impl Blob for Filler {
39 fn data_len(&self) -> u64 {
40 self.bytes.len() as u64
41 }
42 fn tensors(&self) -> &[Tensor] {
43 &self.table
44 }
45 fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> {
46 let from = offset as usize;
47 let span = self.bytes.get(from..from + into.len()).ok_or_else(|| {
48 format!("a read of {} at {offset} past {}", into.len(), self.bytes.len())
49 })?;
50 into.copy_from_slice(span);
51 Ok(())
52 }
53}
54
55/// Lays tensors out back to back in the order they are asked for, so no model file is needed.
56///
57/// A bandwidth measurement does not care what the numbers are, only that the reads land inside
58/// the blob and cover the right span.
59struct Invented;
60
61impl WeightSource for Invented {
62 fn shaped(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> {
63 Ok(0)
64 }
65 fn shaped_words(&self, _index: usize, _dims: &[u32]) -> Result<u32, String> {
66 Ok(0)
67 }
68 fn count(&self) -> usize {
69 // Exactly what one int4 convolution reads: weights, per-block scales, bias.
70 3
71 }
72}
73
74fn main() {
75 let context = match context::shared() {
76 Ok(context) => context,
77 Err(why) => return println!("no Vulkan device: {why}"),
78 };
79 println!(" {:>7} {:>7} {:>9} {:>9}", "out", "in", "MB", "GB/s");
80 // Square-ish shapes spanning a projection through to a logits split.
81 for (out, inputs) in [
82 (1536u32, 1536u32),
83 (3072, 1536),
84 (6144, 1536),
85 (12288, 1536),
86 (24576, 1536),
87 (65536, 1536),
88 ] {
89 match measure(&context, out, inputs) {
90 Ok((bytes, rate)) => println!(
91 " {out:>7} {inputs:>7} {:>9.1} {:>9.2}",
92 bytes as f64 / 1e6,
93 rate / 1e9
94 ),
95 Err(why) => println!(" {out:>7} {inputs:>7} {why}"),
96 }
97 }
98}
99
100/// Time one int4 gemv of `out` by `inputs`, returning its weight bytes and the rate reached.
101fn measure(context: &Arc<context::Context>, out: u32, inputs: u32) -> Result<(u64, f64), String> {
102 let source = Invented;
103 let mut builder = Builder::new(&source);
104 let input = builder.input(Shape::new(inputs, 1, 1));
105 let projected = builder.conv_int4(input, 0, out, Act::None);
106 let plan = builder.finish(&[projected])?;
107 // Int4 weights, a per-block scale table and a bias. The blob only has to be large enough
108 // and correctly shaped; the numbers in it do not matter to a bandwidth measurement.
109 let blocks = inputs.div_ceil(32);
110 let weight_bytes = (u64::from(out) * u64::from(inputs)) / 2;
111 let scale_bytes = u64::from(out) * u64::from(blocks) * 2;
112 let bias_bytes = u64::from(out) * 2;
113 // Every tensor starts at zero and spans the whole blob.
114 //
115 // They alias, which would be nonsense for inference and is exactly right here: the question
116 // is how fast `out * inputs / 2` bytes of weights can be pulled through, not what the
117 // numbers mean. Overlapping also sidesteps having to mirror `Invented`'s offset arithmetic
118 // in two places, which is the kind of duplication that has already caused trouble.
119 let total = weight_bytes + scale_bytes + bias_bytes + 4096;
120 let table = vec![
121 Tensor {
122 rank: 1,
123 dims: [(total / 2) as u32, 0, 0, 0],
124 offset: 0,
125 len: (total / 2) as u32,
126 dtype: Dtype::F16,
127 };
128 3
129 ];
130 let data = Filler { bytes: vec![0x11u8; total as usize], table };
131 let mut net = Net::new(Arc::clone(context), plan, &data, RESCALE_ONLY)?;
132 let feed = vec![0.5f32; inputs as usize];
133 // One warm pass, then the best of five: the first pays for any lazy allocation.
134 net.infer_raw(&feed)?;
135 let mut best = f64::MAX;
136 for _ in 0..5 {
137 let started = std::time::Instant::now();
138 net.infer_raw(&feed)?;
139 best = best.min(started.elapsed().as_secs_f64());
140 }
141 Ok((weight_bytes, weight_bytes as f64 / best))
142}