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

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

report_gemv_scaling.rs146 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::vulkan::context;
25use modelrunner::preprocess::RESCALE_ONLY;
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(
102 context: &Arc<context::Context>,
103 out: u32,
104 inputs: u32,
105) -> Result<(u64, f64), String> {
106 let source = Invented;
107 let mut builder = Builder::new(&source);
108 let input = builder.input(Shape::new(inputs, 1, 1));
109 let projected = builder.conv_int4(input, 0, out, Act::None);
110 let plan = builder.finish(&[projected])?;
111 // Int4 weights, a per-block scale table and a bias. The blob only has to be large enough
112 // and correctly shaped; the numbers in it do not matter to a bandwidth measurement.
113 let blocks = inputs.div_ceil(32);
114 let weight_bytes = (u64::from(out) * u64::from(inputs)) / 2;
115 let scale_bytes = u64::from(out) * u64::from(blocks) * 2;
116 let bias_bytes = u64::from(out) * 2;
117 // Every tensor starts at zero and spans the whole blob.
118 //
119 // They alias, which would be nonsense for inference and is exactly right here: the question
120 // is how fast `out * inputs / 2` bytes of weights can be pulled through, not what the
121 // numbers mean. Overlapping also sidesteps having to mirror `Invented`'s offset arithmetic
122 // in two places, which is the kind of duplication that has already caused trouble.
123 let total = weight_bytes + scale_bytes + bias_bytes + 4096;
124 let table = vec![
125 Tensor {
126 rank: 1,
127 dims: [(total / 2) as u32, 0, 0, 0],
128 offset: 0,
129 len: (total / 2) as u32,
130 dtype: Dtype::F16,
131 };
132 3
133 ];
134 let data = Filler { bytes: vec![0x11u8; total as usize], table };
135 let mut net = Net::new(Arc::clone(context), plan, &data, RESCALE_ONLY)?;
136 let feed = vec![0.5f32; inputs as usize];
137 // One warm pass, then the best of five: the first pays for any lazy allocation.
138 net.infer_raw(&feed)?;
139 let mut best = f64::MAX;
140 for _ in 0..5 {
141 let started = std::time::Instant::now();
142 net.infer_raw(&feed)?;
143 best = best.min(started.elapsed().as_secs_f64());
144 }
145 Ok((weight_bytes, weight_bytes as f64 / best))
146}