Skip to main content

cubecl_std/throughput/runners/
memory_read.rs

1use cubecl::prelude::*;
2use cubecl_core as cubecl;
3use cubecl_runtime::throughput::{KernelConfig, MemoryAccess, ThroughputKey};
4
5use crate::throughput::{
6    LaunchConfig,
7    memory_probe::{self, MemoryProbe},
8};
9
10/// Builds the read-only streaming kernel, moving `working_set` bytes per pass,
11/// all of them read.
12///
13/// This is [`memory_direct`](super::memory_direct) with the store removed. The
14/// copy kernel moves a line in and a line back out, and counts both directions
15/// in `ops_count`, so what it reports is total traffic across the memory
16/// interface. That is the right ceiling for a kernel that also writes what it
17/// reads, and the wrong one for a kernel that only reads — a weight stream, a
18/// reduction, a gather. Those legitimately exceed the copy figure, because half
19/// of the copy's traffic is a direction they never use.
20///
21/// Reported `ops_count` is the read count alone. Exactly one line is written,
22/// by one thread, to keep the loads from being eliminated (see the kernel); at
23/// hundreds of megabytes read that is not worth counting and is deliberately
24/// left out of `ops_count` rather than approximated.
25pub fn build_kernel<R: Runtime>(
26    client: &ComputeClient<R>,
27    key: ThroughputKey,
28    config: LaunchConfig,
29    working_set: usize,
30) -> KernelConfig {
31    let client = client.clone();
32    let dtype = key.dtype();
33
34    let line_bytes = config.vector_size * dtype.size();
35    let probe = MemoryProbe::new(&client, config, line_bytes, MemoryAccess::Read, working_set);
36
37    let in_handle = client.empty(probe.buffer_bytes);
38    memory_probe::prime(&client, &in_handle, probe.pool_lines, config, dtype);
39    // One line: the kernel writes from a single thread, only to anchor the reads.
40    let out_handle = client.empty(line_bytes);
41
42    let sample = Box::new(move |iterations: usize| {
43        let start = cubecl_common::profile::Instant::now();
44        unsafe {
45            memory_read_throughput::launch_unchecked(
46                &client,
47                CubeCount::Static(probe.cube_count as u32, 1, 1),
48                CubeDim::new(&client, config.cube_dim),
49                config.vector_size,
50                BufferArg::from_raw_parts(in_handle.clone(), probe.pool_lines),
51                BufferArg::from_raw_parts(out_handle.clone(), 1),
52                probe.window_lines,
53                iterations,
54                probe.blocked,
55                dtype,
56            )
57        };
58        let _ = cubecl_core::future::block_on(client.sync());
59        start.elapsed()
60    });
61
62    // Reads only — no `2 *`. That factor is the whole difference from the copy.
63    let ops_count = probe.window_lines * config.vector_size;
64
65    KernelConfig { sample, ops_count }
66}
67
68#[cube(launch_unchecked)]
69pub fn memory_read_throughput<I: Numeric, N: Size>(
70    input: &[Vector<I, N>],
71    output: &mut [Vector<I, N>],
72    window: usize,
73    n_iter: usize,
74    #[comptime] blocked: bool,
75    #[define(I)] _dtype: ElemType,
76) {
77    let len = input.len();
78    let stride = CUBE_DIM as usize * CUBE_COUNT;
79
80    // From `window` alone rather than from `window - ABSOLUTE_POS`, which
81    // underflows for a thread past the end of a window smaller than the launch.
82    // High threads get one step too many and the bounds check drops it.
83    let steps = window.div_ceil(stride).max(1);
84
85    // Sum what is read. A load whose result is never used is dead code, and a
86    // compiler that removes it turns this into a launch-overhead measurement
87    // reporting an absurd bandwidth — so the reads have to reach an observable.
88    let mut acc = Vector::<I, N>::empty();
89    let lanes = acc.vector_size();
90    #[unroll]
91    for lane in 0..lanes {
92        acc.insert(lane, I::cast_from(0));
93    }
94
95    // One accumulator, unlike `compute_direct`'s four. That kernel needs
96    // independent chains because it is ALU-bound and would otherwise stall on
97    // add latency; here the adds are free next to memory latency, and the
98    // hiding comes from thread-level parallelism — `cube_count * cube_dim`
99    // threads each with an independent address.
100    //
101    // Each pass reads the *next* window of the buffer, not the same one again.
102    // A window read repeatedly would be served from cache after the first pass,
103    // and every working set below the cache would report cache bandwidth
104    // instead of what a kernel of that size moves; coming back to a window only
105    // after a whole buffer of traffic keeps it cold.
106    //
107    // It also keeps the addresses moving. A window small enough that every
108    // thread reads a single line would otherwise be loop-invariant, and the
109    // compiler is free to hoist such a load out of the loop — leaving the probe
110    // reporting the speed of adding a register to itself.
111    let mut start = 0;
112    let mut wrap = 0;
113
114    for _ in 0..n_iter {
115        for step in 0..steps {
116            // Coalesced spreads one step's addresses across adjacent threads,
117            // which is only fast where those threads share a real plane. A
118            // CPU worker has no such neighbour, so it instead gets a run of
119            // `steps` lines entirely its own.
120            let base = if blocked {
121                ABSOLUTE_POS * steps + step
122            } else {
123                ABSOLUTE_POS + (step * stride)
124            };
125
126            if base < window {
127                let mut idx = start + base;
128                if idx >= len {
129                    idx -= len;
130                }
131
132                acc += input[idx];
133            }
134        }
135
136        start += window;
137        // Back to the beginning, one line further along each time round, so a
138        // window that fills the whole buffer still moves between passes.
139        if start + window > len {
140            wrap += 1;
141            if wrap >= window {
142                wrap = 0;
143            }
144            start = wrap;
145        }
146    }
147
148    // Guarded so the store cannot be hoisted out of the loop, and so the write
149    // traffic is one line rather than one per thread. The compiler cannot prove
150    // any given thread is not thread 0, so no thread's loads are dead.
151    if ABSOLUTE_POS == 0 {
152        output[0] = acc;
153    }
154}