Skip to main content

cubek_test_utils/
tile_input.rs

1//! A clean, launchable [`Tile`] input for tests. Describe a tile as a [`Space`]
2//! with a stack of `.split`/`.tile` levels and get a launchable tile: the buffer
3//! is a plain `[grid…, tile…]` strided tensor (or `[grid…, level1…, …]` when
4//! recursively tiled), presented in its logical space via an explicit
5//! `tiled_view`. No `Tiler`, no semantic-view juggling.
6#![allow(dead_code)]
7
8use cubecl::prelude::{Numeric, Size};
9use cubecl::{
10    bytes::Bytes,
11    client::Client,
12    prelude::TensorArg,
13    prelude::TensorBinding,
14    quant::scheme::{QuantScheme, QuantValue},
15    zspace::Shape,
16};
17use cubecl::{
18    frontend::Scalar,
19    std::tensor::{
20        TensorHandle,
21        layout::tiled_view::{TileSpec, TiledViewLaunch, TiledViewLayout},
22    },
23};
24use cubek_tile::{Axis, Projection, Space, TileArgLaunch, TileSpec as CubekTileSpec, kind::Field};
25
26use crate::{TestInput, TestInputBuilder};
27
28/// A tile-shaped test input: the device buffer plus the logical [`Space`] it's
29/// viewed in. The sub-tile sizes live in the buffer's trailing dims, so the view
30/// reads them from there.
31pub struct TileInput {
32    handle: TensorHandle,
33    space: Space,
34    levels: usize,
35}
36
37impl TileInput {
38    /// Start building a tile over `space`. Stack tiling levels coarse→fine with
39    /// [`split`](TileInputBuilder::split) (by count) or
40    /// [`tile`](TileInputBuilder::tile) (by element edge): chain them for
41    /// recursion, or [`untiled`](TileInputBuilder::untiled) for none, then a data
42    /// finalizer ([`arange`](TileInputBuilder::arange) /
43    /// [`zeros`](TileInputBuilder::zeros)).
44    pub fn builder(client: &Client, space: Space) -> TileInputBuilder {
45        TileInputBuilder {
46            client: client.clone(),
47            space,
48            levels: None,
49        }
50    }
51
52    /// Launch arg for this tile's view: the buffer seen in its logical space.
53    /// Every logical axis is tiled (`num_tiled = space.rank()`), recursively for
54    /// `levels` nested tile levels.
55    pub fn view(&self) -> TiledViewLaunch {
56        TiledViewLaunch::new_tensor::<TiledViewLayout>(
57            self.handle.clone().binding().into_tensor_arg(),
58            TileSpec {
59                start_axis: 0,
60                num_tiled: self.space.rank(),
61                levels: self.levels,
62            },
63        )
64    }
65
66    /// Launch arg for this tile's view vectorized with line size `vector_size`
67    /// along the innermost (contiguous) axis. Same buffer; only the metadata is
68    /// reinterpreted in line units (innermost shape ÷ `S`, every other stride
69    /// ÷ `S`), so a kernel reading `Vector<E, S>` lands on contiguous lines.
70    /// `vector_size == 1` is exactly [`view`](Self::view).
71    pub fn view_vectorized(&self, vector_size: usize) -> TiledViewLaunch {
72        let shape = self.handle.shape();
73        let strides = self.handle.strides();
74        let inner = shape.len() - 1;
75        let new_shape: Vec<usize> = shape
76            .iter()
77            .enumerate()
78            .map(|(i, &s)| if i == inner { s / vector_size } else { s })
79            .collect();
80        let new_strides: Vec<usize> = strides
81            .iter()
82            .enumerate()
83            .map(|(i, &s)| if i == inner { s } else { s / vector_size })
84            .collect();
85        let lined = TensorHandle::new(
86            self.handle.handle.clone(),
87            new_shape,
88            new_strides,
89            self.handle.dtype,
90        );
91        TiledViewLaunch::new_tensor::<TiledViewLayout>(
92            lined.binding().into_tensor_arg(),
93            TileSpec {
94                start_axis: 0,
95                num_tiled: self.space.rank(),
96                levels: self.levels,
97            },
98        )
99    }
100
101    /// Launch arg for this tile's raw global buffer: a plain [`TensorArg`] over the
102    /// `[grid…, tile…]` buffer, optionally re-lined by `vector_size` along the inner
103    /// axis (so a kernel reading raw `Vector<E, S>` slices lands on contiguous lines).
104    /// `vector_size == 1` is the plain buffer. For `Tile::of` pass the plain buffer:
105    /// the kernel's element type carries the width and the metadata stays scalar-unit.
106    pub fn tensor_arg(&self, vector_size: usize) -> TensorArg {
107        if vector_size <= 1 {
108            return self.handle.clone().binding().into_tensor_arg();
109        }
110        let shape = self.handle.shape();
111        let strides = self.handle.strides();
112        let inner = shape.len() - 1;
113        let new_shape: Vec<usize> = shape
114            .iter()
115            .enumerate()
116            .map(|(i, &s)| if i == inner { s / vector_size } else { s })
117            .collect();
118        let new_strides: Vec<usize> = strides
119            .iter()
120            .enumerate()
121            .map(|(i, &s)| if i == inner { s } else { s / vector_size })
122            .collect();
123        TensorHandle::new(
124            self.handle.handle.clone(),
125            new_shape,
126            new_strides,
127            self.handle.dtype,
128        )
129        .binding()
130        .into_tensor_arg()
131    }
132
133    /// The tile as one launch argument: its scalar-unit tensor paired with its
134    /// [`spec`](Self::spec). The kernel's element type carries the width.
135    pub fn arg<E: Numeric, V: Size>(&self) -> TileArgLaunch<'static, E, V> {
136        TileArgLaunch::new(self.tensor_arg(1), self.spec())
137    }
138
139    /// The comptime [`CubekTileSpec`] a kernel feeds `Tile::of`: the axes this tile spans
140    /// (its own space's, in buffer order) paired with its derived storage.
141    pub fn spec(&self) -> CubekTileSpec {
142        let axes: Vec<_> = (0..self.space.rank())
143            .map(|i| self.space.axis_at(i))
144            .collect();
145        let levels = self.handle.shape().len() / self.space.rank() - 1;
146        // Every axis is stored at every level, so the dims name the axes once per level.
147        CubekTileSpec::new(Projection::tiled(&axes, &axes.repeat(levels + 1)))
148    }
149
150    /// The semantic space the tile lives in.
151    pub fn space(&self) -> Space {
152        self.space.clone()
153    }
154
155    /// The device handle, for reading an output back.
156    pub fn handle(&self) -> TensorHandle {
157        self.handle.clone()
158    }
159}
160
161/// One tiling level, added coarse→fine. [`Split`](TileLevel::Split) and
162/// [`Tile`](TileLevel::Tile) are duals against the running tile edge: `Tile(e)`
163/// sets the current tile to `e` elements; `Split(n)` divides it into `n`.
164enum TileLevel {
165    /// Divide the current tile into this many sub-tiles per axis.
166    Split(Vec<usize>),
167    /// Set the current tile to this many elements per axis.
168    Tile(Vec<usize>),
169}
170
171/// Fluent builder for a [`TileInput`]: a [`Space`], a coarse→fine stack of tiling
172/// levels (each a [`split`](Self::split) or [`tile`](Self::tile)), and a data
173/// finalizer that fills the `[grid…, level…, finest…]` buffer.
174pub struct TileInputBuilder {
175    client: Client,
176    space: Space,
177    levels: Option<Vec<TileLevel>>,
178}
179
180impl TileInputBuilder {
181    /// Divide the current tile into `counts[axis]` sub-tiles per axis: a finer
182    /// level. Chain for recursion: `.split(&[4, 4]).split(&[2, 2])`.
183    pub fn split(mut self, counts: &[usize]) -> Self {
184        self.levels
185            .get_or_insert_with(Vec::new)
186            .push(TileLevel::Split(counts.to_vec()));
187        self
188    }
189
190    /// Set the current tile to `edges[axis]` elements per axis: a finer level.
191    /// The dual of [`split`](Self::split) (it divides the current edge down to
192    /// `edges`), so `.tile(&[16, 16]).tile(&[8, 8])` ≡ `.tile(&[16, 16]).split(&[2, 2])`.
193    pub fn tile(mut self, edges: &[usize]) -> Self {
194        self.levels
195            .get_or_insert_with(Vec::new)
196            .push(TileLevel::Tile(edges.to_vec()));
197        self
198    }
199
200    /// No sub-tiling: the buffer is the logical shape itself, row-major (zero tile
201    /// levels: the view is the identity).
202    pub fn untiled(mut self) -> Self {
203        self.levels = Some(Vec::new());
204        self
205    }
206
207    /// Arange `0, 1, 2, …` written straight onto the physical buffer; the
208    /// `tiled_view` then presents it in logical coordinates.
209    pub fn arange(self) -> TileInput {
210        self.build(TestInputBuilder::arange)
211    }
212
213    /// All-zeros physical buffer: e.g. a matmul output.
214    pub fn zeros(self) -> TileInput {
215        self.build(TestInputBuilder::zeros)
216    }
217
218    /// Uniformly distributed random values in `[lo, hi)` range, seeded by `seed`.
219    pub fn uniform(self, seed: u64, lo: f32, hi: f32) -> TileInput {
220        self.build(|b: TestInputBuilder| b.uniform(seed, lo, hi))
221    }
222
223    /// Continue as a packed-u32 quantized input: a *container* step, like the tiling ones.
224    /// the tile will be declared **in values** (its shape and strides count them) while the
225    /// buffer holds the packed words, the binding convention the tile launch expects for a
226    /// packed operand. Content comes from the quantized builder's own finalizer (e.g.
227    /// [`arange`](QuantizedTileInputBuilder::arange)), which also mints the scales: a
228    /// quantized tensor is one thing (data + scales + scheme). Untiled only: packed storage
229    /// has no physically tiled layout.
230    ///
231    /// The kernel meets the three as operands of their own ([`values_arg`], [`scales_arg`],
232    /// [`table_arg`]) and states the decode where it happens: `w.lookup(&table).mul(&scales)`.
233    ///
234    /// [`values_arg`]: QuantizedTileInput::values_arg
235    /// [`scales_arg`]: QuantizedTileInput::scales_arg
236    /// [`table_arg`]: QuantizedTileInput::table_arg
237    pub fn packed(self, scheme: &QuantScheme) -> QuantizedTileInputBuilder {
238        let levels = self
239            .levels
240            .expect("TileInput: set .untiled() before .packed");
241        assert!(
242            levels.is_empty(),
243            "TileInput::packed: a packed input is untiled"
244        );
245        QuantizedTileInputBuilder {
246            client: self.client,
247            space: self.space,
248            scheme: *scheme,
249        }
250    }
251
252    /// Build the `[grid…, level…, finest…]` device buffer, filled by `fill` (a
253    /// `TestInput` finalizer like `arange`/`zeros`) in physical row-major order.
254    /// Walking coarse→fine, each level becomes one block of `rank` dims and the
255    /// leftover edge is the finest block: `(levels + 1) * rank` dims, the layout
256    /// the `tiled_view` reads back.
257    fn build(self, fill: impl FnOnce(TestInputBuilder) -> TestInput) -> TileInput {
258        let levels = self
259            .levels
260            .expect("TileInput: set .split/.tile(...) or .untiled() before a finalizer");
261        let rank = self.space.rank();
262
263        let mut current: Vec<usize> = (0..rank)
264            .map(|i| self.space.extent(self.space.axis_at(i)))
265            .collect();
266        let mut blocks: Vec<Vec<usize>> = Vec::with_capacity(levels.len() + 1);
267        for level in &levels {
268            let (values, is_split) = match level {
269                TileLevel::Split(values) => (values, true),
270                TileLevel::Tile(values) => (values, false),
271            };
272            assert_eq!(
273                values.len(),
274                rank,
275                "TileInput: a tile level needs one value per axis (rank {rank})"
276            );
277            let block: Vec<usize> = (0..rank)
278                .map(|i| {
279                    let (edge, value) = (current[i], values[i]);
280                    assert!(
281                        value != 0 && edge % value == 0,
282                        "TileInput: tile value {value} does not divide the current edge {edge} on axis {i}"
283                    );
284                    let (dim, next) = if is_split {
285                        (value, edge / value)
286                    } else {
287                        (edge / value, value)
288                    };
289                    current[i] = next;
290                    dim
291                })
292                .collect();
293            blocks.push(block);
294        }
295        blocks.push(current);
296
297        let mut dims = Vec::with_capacity(blocks.len() * rank);
298        for block in &blocks {
299            dims.extend_from_slice(block);
300        }
301        let builder = TestInput::builder(self.client, Shape::from(dims));
302        TileInput {
303            handle: fill(builder).generate_without_host_data(),
304            space: self.space,
305            levels: levels.len(),
306        }
307    }
308}
309
310/// The quantized continuation of a [`TileInputBuilder`]: the container is fixed
311/// (packed-u32, values-unit declaration, the scheme's block grid for scales); a content
312/// finalizer fills it and mints the values tile and its scales together: a quantized
313/// tensor is one thing (data, scales, scheme).
314pub struct QuantizedTileInputBuilder {
315    client: Client,
316    space: Space,
317    scheme: QuantScheme,
318}
319
320impl QuantizedTileInputBuilder {
321    /// `arange`, wrapped into the scheme's representable range: values run
322    /// `lo, lo+1, …, hi, lo, …`, so every representable value (and its sign extension)
323    /// appears. Scales are a distinct-per-block ramp (`0.05 · (block + 1)`) on the scheme's
324    /// block grid.
325    ///
326    /// Integer value types only. The walk is over whole numbers packed as two's complement, and
327    /// [`q`](QuantizedTileInput::q) is handed to tests as the magnitude each field stands for —
328    /// both of which hold only where a format's codes are its magnitudes. Under a minifloat the
329    /// fields would be codes, so a test folding `q · scale` would compare the kernel against the
330    /// integer grid the format exists to avoid.
331    pub fn arange(self) -> QuantizedTileInput {
332        assert!(
333            integer_valued(self.scheme.value),
334            "QuantizedTileInputBuilder::arange: {:?} is a minifloat, whose fields are codes rather \
335             than magnitudes; state the codes with `pack_q_values` and fold the format's grid into \
336             the test's own reference",
337            self.scheme.value
338        );
339
340        let rank = self.space.rank();
341        let shape: Vec<usize> = (0..rank)
342            .map(|i| self.space.extent(self.space.axis_at(i)))
343            .collect();
344
345        let (lo, hi) = self.scheme.value.range();
346        let (lo, hi) = (lo as i32, hi as i32);
347        let span = hi - lo + 1;
348        let q: Vec<i32> = (0..shape.iter().product())
349            .map(|i| lo + (i as i32 % span))
350            .collect();
351        let words = crate::stubs::quant::pack_q_values(&q, &self.scheme);
352        let handle = self.client.create(Bytes::from_elems(words));
353
354        let block = crate::stubs::quant::block_dims(&self.scheme, &shape);
355        let grid = crate::quant_layout::scales_grid(&shape, &block);
356        let scale_values: Vec<f32> = (0..grid.iter().product())
357            .map(|g| 0.05 * (g + 1) as f32)
358            .collect();
359        let scales = TestInput::builder(self.client, Shape::from(grid))
360            .custom(scale_values.clone())
361            .generate_without_host_data();
362
363        QuantizedTileInput {
364            tile: TileInput {
365                handle: TensorHandle::new_contiguous(shape, handle, u32::elem_type_native()),
366                space: self.space,
367                levels: 0,
368            },
369            scales,
370            scheme: self.scheme,
371            table: None,
372            q,
373            scale_values,
374            table_values: Vec::new(),
375        }
376    }
377
378    /// [`arange`](Self::arange) for a lookup scheme: the packed fields walk the table indices
379    /// **descending** (`2^bits - 1, …, 1, 0, 2^bits - 1, …`), so every entry is read *and* the
380    /// field is never the identity of its position: a decode that indexed the table by position
381    /// instead of by the unpacked field would pass an ascending walk. The scales are the same
382    /// distinct-per-block ramp, and `table` uploads beside them. Panics unless the scheme's mode
383    /// is lookup and the table holds exactly `2^bits` entries.
384    pub fn lookup_arange(self, table: &[f32]) -> QuantizedTileInput {
385        assert!(
386            matches!(self.scheme.mode, cubecl::quant::scheme::QuantMode::Lookup),
387            "lookup_arange: the scheme's mode is {:?}, not Lookup",
388            self.scheme.mode
389        );
390        let span = 1usize << self.scheme.size_bits_value();
391        assert_eq!(
392            table.len(),
393            span,
394            "lookup_arange: a {}-bit scheme indexes {span} entries",
395            self.scheme.size_bits_value()
396        );
397        let rank = self.space.rank();
398        let shape: Vec<usize> = (0..rank)
399            .map(|i| self.space.extent(self.space.axis_at(i)))
400            .collect();
401
402        let q: Vec<i32> = (0..shape.iter().product())
403            .map(|i| (span - 1 - (i % span)) as i32)
404            .collect();
405        let words = crate::stubs::quant::pack_q_values(&q, &self.scheme);
406        let handle = self.client.create(Bytes::from_elems(words));
407
408        let block = crate::stubs::quant::block_dims(&self.scheme, &shape);
409        let grid = crate::quant_layout::scales_grid(&shape, &block);
410        let scale_values: Vec<f32> = (0..grid.iter().product())
411            .map(|g| 0.05 * (g + 1) as f32)
412            .collect();
413        let scales = TestInput::builder(self.client.clone(), Shape::from(grid))
414            .custom(scale_values.clone())
415            .generate_without_host_data();
416        let table_handle = TestInput::builder(self.client, Shape::from(vec![span]))
417            .custom(table.to_vec())
418            .generate_without_host_data();
419
420        QuantizedTileInput {
421            tile: TileInput {
422                handle: TensorHandle::new_contiguous(shape, handle, u32::elem_type_native()),
423                space: self.space,
424                levels: 0,
425            },
426            scales,
427            scheme: self.scheme,
428            table: Some(table_handle),
429            q,
430            scale_values,
431            table_values: table.to_vec(),
432        }
433    }
434}
435
436/// Whether the format's codes are the integers they stand for, which is what makes an integer
437/// walk over the fields a walk over the values. Mirrors `rounds_to_integers` in the quant stub.
438fn integer_valued(value: QuantValue) -> bool {
439    match value {
440        QuantValue::Q8F
441        | QuantValue::Q8S
442        | QuantValue::Q4F
443        | QuantValue::Q4S
444        | QuantValue::Q2F
445        | QuantValue::Q2S => true,
446        QuantValue::E5M2 | QuantValue::E4M3 | QuantValue::E2M1 => false,
447    }
448}
449
450/// A packed-quantized input born whole: a quantized tensor is one thing (data, scales,
451/// scheme), so the [`quantized builder`](QuantizedTileInputBuilder) mints the pair together,
452/// plus the exact numbers behind both for host references.
453pub struct QuantizedTileInput {
454    pub tile: TileInput,
455    scales: TensorHandle,
456    scheme: QuantScheme,
457    /// A lookup scheme's table, present exactly under `QuantMode::Lookup`
458    /// ([`lookup_arange`](QuantizedTileInputBuilder::lookup_arange) mints it).
459    table: Option<TensorHandle>,
460    /// The quant values, row-major in the logical shape. Table indices under a lookup scheme.
461    pub q: Vec<i32>,
462    /// One scale per block, row-major over the scheme's block grid.
463    pub scale_values: Vec<f32>,
464    /// The lookup table's entries, empty for a non-lookup scheme.
465    pub table_values: Vec<f32>,
466}
467
468impl QuantizedTileInput {
469    /// Binding for the innermost level's scales tensor.
470    pub fn scales_binding(&self) -> TensorBinding {
471        self.scales.clone().binding()
472    }
473
474    /// The field each stored value occupies: the scheme's value, or under a lookup scheme an
475    /// index as wide, which names a table entry rather than a number.
476    pub fn field(&self) -> Field {
477        match self.scheme.mode {
478            cubecl::quant::scheme::QuantMode::Lookup => Field::Index {
479                bits: self.scheme.size_bits_value(),
480            },
481            _ => Field::Quant(self.scheme.value),
482        }
483    }
484
485    /// The packed values as an operand: `u32` words of [`field`](Self::field)s, addressed as
486    /// `spec` says (declared in values). What they decode to is the kernel's statement.
487    pub fn values_arg<V: Size>(&self, spec: CubekTileSpec) -> TileArgLaunch<'static, u32, V> {
488        TileArgLaunch::new(self.tile.tensor_arg(1), spec.packed(self.field()))
489    }
490
491    /// The innermost level's scales as an operand, addressed as `spec` says: one per block of
492    /// the scheme's grid, row-major.
493    pub fn scales_arg<V: Size>(&self, spec: CubekTileSpec) -> TileArgLaunch<'static, f32, V> {
494        TileArgLaunch::new(self.scales_binding().into_tensor_arg(), spec)
495    }
496
497    /// A lookup scheme's table as an operand over its one axis, the positions.
498    ///
499    /// # Panics
500    ///
501    /// Unless the scheme is a lookup one.
502    pub fn table_arg<V: Size>(&self, axis: Axis) -> TileArgLaunch<'static, f32, V> {
503        let table = self
504            .table
505            .as_ref()
506            .expect("QuantizedTileInput::table_arg: this scheme indexes no table");
507        TileArgLaunch::new(
508            table.clone().binding().into_tensor_arg(),
509            CubekTileSpec::direct(&[axis]),
510        )
511    }
512}