Modern-Apps.git
Publicgit clone https://git.maproj.org/Modern-Apps.gitModern-Apps.git / library / ml / src / main / rust / examples / report_gemv_inc.rs
report_gemv_inc.rs148 lines · 5.4 KiBRaw
| 1 | //! Does `in_c` - and so the gemv loop's trip count - change the rate? |
| 2 | //! |
| 3 | //! ```text |
| 4 | //! cargo run --offline --release -p modelrunner --example report_gemv_inc |
| 5 | //! ``` |
| 6 | //! |
| 7 | //! # Why this shape sweep and not another |
| 8 | //! |
| 9 | //! Every sweep taken so far holds `in = 1536` and varies `out`. At `I4_BLOCK` 32 the loop in |
| 10 | //! `conv_vec_int4.comp:75` strides 2048 taps, so `in = 1536` pins the trip count at **one** and |
| 11 | //! the active lanes at **48 of 64** in every row of every one of those tables. The variable |
| 12 | //! nobody has moved is the one the loop actually depends on. |
| 13 | //! |
| 14 | //! `down_proj` is `[1536, 6144]` and `[1536, 12288]` in this model - 22% of the weight bytes - |
| 15 | //! and those run the loop three and six times with all 64 lanes busy. So the model already |
| 16 | //! contains both regimes; only the measurements are missing. |
| 17 | //! |
| 18 | //! # The discriminator |
| 19 | //! |
| 20 | //! Rows are grouped so that `out * in` - and hence weight bytes and total multiply-adds - is |
| 21 | //! held constant while the trip count moves. Same work, same traffic, different loop: |
| 22 | //! |
| 23 | //! * if the degenerate loop is what costs us, the long-`in` rows are markedly faster; |
| 24 | //! * if the dequant arithmetic is what costs us, every row in a group reads the same, because |
| 25 | //! each does the same number of unpacks either way. |
| 26 | //! |
| 27 | //! The two hypotheses differ in sign here, which no sweep of `out` can do. |
| 28 | use std::sync::Arc; |
| 29 | |
| 30 | use modelrunner::nets::{Act, Builder, Shape, WeightSource}; |
| 31 | use modelrunner::preprocess::RESCALE_ONLY; |
| 32 | use modelrunner::vulkan::context; |
| 33 | use modelrunner::vulkan::run::Net; |
| 34 | use modelrunner::weights::{Blob, Dtype, Tensor}; |
| 35 | |
| 36 | /// A blob of identical bytes with a matching tensor table. As `report_gemv_scaling`. |
| 37 | struct Filler { |
| 38 | bytes: Vec<u8>, |
| 39 | table: Vec<Tensor>, |
| 40 | } |
| 41 | |
| 42 | impl Blob for Filler { |
| 43 | fn data_len(&self) -> u64 { |
| 44 | self.bytes.len() as u64 |
| 45 | } |
| 46 | fn tensors(&self) -> &[Tensor] { |
| 47 | &self.table |
| 48 | } |
| 49 | fn read_at(&self, offset: u64, into: &mut [u8]) -> Result<(), String> { |
| 50 | let from = offset as usize; |
| 51 | let span = self.bytes.get(from..from + into.len()).ok_or_else(|| { |
| 52 | format!("a read of {} at {offset} past {}", into.len(), self.bytes.len()) |
| 53 | })?; |
| 54 | into.copy_from_slice(span); |
| 55 | Ok(()) |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | struct Invented; |
| 60 | |
| 61 | impl 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 | 3 |
| 70 | } |
| 71 | } |
| 72 | |
| 73 | /// Trip count and active lanes for a given `in_c`, mirroring `conv_vec_int4.comp:75`. |
| 74 | fn loop_shape(inputs: u32) -> (u32, u32) { |
| 75 | let stride = 64 * 32; |
| 76 | let iterations = inputs.div_ceil(stride); |
| 77 | let active = (inputs.div_ceil(32)).min(64); |
| 78 | (iterations, active) |
| 79 | } |
| 80 | |
| 81 | fn main() { |
| 82 | let context = match context::shared() { |
| 83 | Ok(context) => context, |
| 84 | Err(why) => return println!("no Vulkan device: {why}"), |
| 85 | }; |
| 86 | println!(" constant-bytes groups: only in_c moves, so weight bytes and total MACs are fixed"); |
| 87 | println!( |
| 88 | " {:>7} {:>7} {:>7} {:>6} {:>6} {:>9}", |
| 89 | "out", "in", "MB", "iters", "lanes", "GB/s" |
| 90 | ); |
| 91 | let groups: [&[(u32, u32)]; 3] = [ |
| 92 | // ~9.4 MB of weights each. |
| 93 | &[(12288, 1536), (3072, 6144), (1536, 12288)], |
| 94 | // ~4.7 MB each. |
| 95 | &[(6144, 1536), (1536, 6144)], |
| 96 | // The real down_proj pair beside the projection shape they share an output width with. |
| 97 | &[(1536, 1536), (1536, 6144), (1536, 12288)], |
| 98 | ]; |
| 99 | for (index, group) in groups.iter().enumerate() { |
| 100 | println!(" --- group {} ---", index + 1); |
| 101 | for &(out, inputs) in group.iter() { |
| 102 | let (iterations, active) = loop_shape(inputs); |
| 103 | match measure(&context, out, inputs) { |
| 104 | Ok((bytes, rate)) => println!( |
| 105 | " {out:>7} {inputs:>7} {:>7.1} {iterations:>6} {active:>6} {:>9.2}", |
| 106 | bytes as f64 / 1e6, |
| 107 | rate / 1e9 |
| 108 | ), |
| 109 | Err(why) => println!(" {out:>7} {inputs:>7} {why}"), |
| 110 | } |
| 111 | } |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | /// Time one int4 gemv of `out` by `inputs`, returning its weight bytes and the rate reached. |
| 116 | fn measure(context: &Arc<context::Context>, out: u32, inputs: u32) -> Result<(u64, f64), String> { |
| 117 | let source = Invented; |
| 118 | let mut builder = Builder::new(&source); |
| 119 | let input = builder.input(Shape::new(inputs, 1, 1)); |
| 120 | let projected = builder.conv_int4(input, 0, out, Act::None); |
| 121 | let plan = builder.finish(&[projected])?; |
| 122 | let blocks = inputs.div_ceil(32); |
| 123 | let weight_bytes = (u64::from(out) * u64::from(inputs)) / 2; |
| 124 | let scale_bytes = u64::from(out) * u64::from(blocks) * 2; |
| 125 | let bias_bytes = u64::from(out) * 2; |
| 126 | let total = weight_bytes + scale_bytes + bias_bytes + 4096; |
| 127 | let table = vec![ |
| 128 | Tensor { |
| 129 | rank: 1, |
| 130 | dims: [(total / 2) as u32, 0, 0, 0], |
| 131 | offset: 0, |
| 132 | len: (total / 2) as u32, |
| 133 | dtype: Dtype::F16, |
| 134 | }; |
| 135 | 3 |
| 136 | ]; |
| 137 | let data = Filler { bytes: vec![0x11u8; total as usize], table }; |
| 138 | let mut net = Net::new(Arc::clone(context), plan, &data, RESCALE_ONLY)?; |
| 139 | let feed = vec![0.5f32; inputs as usize]; |
| 140 | net.infer_raw(&feed)?; |
| 141 | let mut best = f64::MAX; |
| 142 | for _ in 0..7 { |
| 143 | let started = std::time::Instant::now(); |
| 144 | net.infer_raw(&feed)?; |
| 145 | best = best.min(started.elapsed().as_secs_f64()); |
| 146 | } |
| 147 | Ok((weight_bytes, weight_bytes as f64 / best)) |
| 148 | } |