sp1-gpu-utils 6.2.2

Utility functions for SP1 GPU operations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
use std::collections::BTreeMap;
use std::ops::{Deref, DerefMut, Range};

use slop_algebra::Field;
use slop_alloc::{Backend, Buffer, CpuBackend, HasBackend};
use slop_tensor::{Dimensions, Tensor, TensorView};
use sp1_gpu_cudart::{DeviceBuffer, TaskScope};

use crate::jagged::JaggedMle;
use crate::{DenseData, DenseDataMut};

#[derive(Clone, Debug)]
pub struct TraceOffset {
    /// Dense data offset.
    pub dense_offset: Range<usize>,
    /// The size of each polynomial in this trace.
    pub poly_size: usize,
    /// Number of polynomials in this trace.
    pub num_polys: usize,
}

#[derive(Clone)]
pub struct JaggedTraceMle<F: Field, B: Backend>(pub JaggedMle<TraceDenseData<F, B>, B>);

impl<F: Field, B: Backend> HasBackend for JaggedTraceMle<F, B> {
    type Backend = B;
    fn backend(&self) -> &B {
        self.0.backend()
    }
}

impl<F: Field, B: Backend> Deref for JaggedTraceMle<F, B> {
    type Target = JaggedMle<TraceDenseData<F, B>, B>;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<F: Field, B: Backend> DerefMut for JaggedTraceMle<F, B> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

/// Jagged representation of the traces.
#[derive(Clone, Debug)]
pub struct TraceDenseData<F: Field, B: Backend> {
    /// The dense representation of the traces.
    pub dense: Buffer<F, B>,
    /// The dense offset of the preprocessed traces.
    pub preprocessed_offset: usize,
    /// The total number of columns in the preprocessed traces.
    pub preprocessed_cols: usize,
    /// The amount of preprocessed padding, to the next multiple of 2^log_stacking_height.
    pub preprocessed_padding: usize,
    /// The amount of main padding, to the next multiple of 2^log_stacking_height.
    pub main_padding: usize,
    /// A mapping from chip name to the range of dense data it occupies for preprocessed traces.
    pub preprocessed_table_index: BTreeMap<String, TraceOffset>,
    /// A mapping from chip name to the range of dense data it occupies for main traces.
    pub main_table_index: BTreeMap<String, TraceOffset>,
}

impl<F: Field, B: Backend> TraceDenseData<F, B> {
    pub fn main_virtual_tensor(&'_ self, log_stacking_height: u32) -> TensorView<'_, F, B> {
        let ptr = unsafe { self.dense.as_ptr().add(self.preprocessed_offset) };
        let sizes = Dimensions::try_from([
            self.main_size() / (1 << log_stacking_height),
            1 << log_stacking_height,
        ])
        .unwrap();
        // This is safe because we inherit the lifetime of self and the offset should be valid.
        unsafe { TensorView::from_raw_parts(ptr, sizes, self.backend().clone()) }
    }

    /// Copies the correct data from dense to a new tensor for main traces.
    pub fn main_tensor(&self, log_stacking_height: u32) -> Tensor<F, B> {
        let mut tensor = Tensor::with_sizes_in(
            [self.main_size() / (1 << log_stacking_height), 1 << log_stacking_height],
            self.backend().clone(),
        );
        let backend = self.dense.backend();
        unsafe {
            tensor.assume_init();
            tensor
                .as_mut_buffer()
                .copy_from_slice(&self.dense[self.preprocessed_offset..], backend)
                .unwrap();
        }
        tensor
    }

    pub fn preprocessed_virtual_tensor(&'_ self, log_stacking_height: u32) -> TensorView<'_, F, B> {
        let ptr = self.dense.as_ptr();
        let sizes = Dimensions::try_from([
            self.preprocessed_offset / (1 << log_stacking_height),
            1 << log_stacking_height,
        ])
        .unwrap();
        unsafe { TensorView::from_raw_parts(ptr, sizes, self.backend().clone()) }
    }

    /// Copies the correct data from dense to a new tensor for preprocessed traces.
    pub fn preprocessed_tensor(&self, log_stacking_height: u32) -> Tensor<F, B> {
        let mut tensor = Tensor::with_sizes_in(
            [self.preprocessed_offset / (1 << log_stacking_height), 1 << log_stacking_height],
            self.backend().clone(),
        );
        let backend = self.dense.backend();
        unsafe {
            tensor.assume_init();
            tensor
                .as_mut_buffer()
                .copy_from_slice(&self.dense[..self.preprocessed_offset], backend)
                .unwrap();
        }
        tensor
    }

    /// The size of the main polynomial.
    #[inline]
    pub fn main_poly_height(&self, name: &str) -> Option<usize> {
        self.main_table_index.get(name).map(|offset| offset.poly_size)
    }

    /// The size of the preprocessed polynomial.
    #[inline]
    pub fn preprocessed_poly_height(&self, name: &str) -> Option<usize> {
        self.preprocessed_table_index.get(name).map(|offset| offset.poly_size)
    }

    /// The number of polynomials in the main trace.
    #[inline]
    pub fn main_num_polys(&self, name: &str) -> Option<usize> {
        self.main_table_index.get(name).map(|offset| offset.num_polys)
    }

    /// The size of the main trace dense data, including padding.
    #[inline]
    pub fn main_size(&self) -> usize {
        self.dense.len() - self.preprocessed_offset
    }

    /// The number of polynomials in the preprocessed trace.
    #[inline]
    pub fn preprocessed_num_polys(&self, name: &str) -> Option<usize> {
        self.preprocessed_table_index.get(name).map(|offset| offset.num_polys)
    }
}

/// Abstract description of a chip layout used to build [`TraceDenseData`] / [`JaggedTraceMle`].
/// Each tuple is`(chip_name, preprocessed_width, main_width)` for one chip;
pub struct AbstractChipLayout(Vec<(String, usize, usize)>);

impl AbstractChipLayout {
    pub fn new(entries: Vec<(String, usize, usize)>) -> Self {
        Self(entries)
    }

    pub fn entries(&self) -> &[(String, usize, usize)] {
        &self.0
    }
}

/// Like [`AbstractChipLayout`], but with a per-chip row count attached to each entry.
/// Each tuple is `(chip_name, preprocessed_width, main_width, height)` for one chip.
pub struct AbstractChipLayoutWithHeights(Vec<(String, usize, usize, usize)>);

impl AbstractChipLayoutWithHeights {
    pub fn new(entries: Vec<(String, usize, usize, usize)>) -> Self {
        Self(entries)
    }

    pub fn entries(&self) -> &[(String, usize, usize, usize)] {
        &self.0
    }

    /// Chip names in layout order.
    pub fn chip_names(&self) -> impl Iterator<Item = &str> {
        self.0.iter().map(|(name, _, _, _)| name.as_str())
    }
}

impl<F: Field> TraceDenseData<F, CpuBackend> {
    /// Build a `TraceDenseData` over a pre-allocated `dense` buffer using an
    /// [`AbstractChipLayoutWithHeights`].
    ///
    /// The `dense` buffer must be sized as `padded_preprocessed + padded_main`, where
    /// each section is the unpadded total rounded up to the next multiple of
    /// `2^log_stacking_height`.
    pub fn from_chip_layout(
        dense: Buffer<F, CpuBackend>,
        layout: &AbstractChipLayoutWithHeights,
        log_stacking_height: u32,
    ) -> Self {
        let stacking = 1usize << log_stacking_height;

        let total_preprocessed: usize = layout.0.iter().map(|(_, p, _, h)| p * h).sum();
        let total_main: usize = layout.0.iter().map(|(_, _, m, h)| m * h).sum();

        // note that this makes sure there is always at least one main and one preprocessed column
        let padded_preprocessed = total_preprocessed.next_multiple_of(stacking).max(stacking);
        let padded_main = total_main.next_multiple_of(stacking).max(stacking);

        assert_eq!(
            dense.len(),
            padded_preprocessed + padded_main,
            "dense buffer length must equal padded_preprocessed + padded_main",
        );

        let preprocessed_cols: usize = layout.0.iter().map(|(_, p, _, _)| p).sum();

        let mut preprocessed_table_index = BTreeMap::new();
        let mut main_table_index = BTreeMap::new();
        let mut preprocessed_ptr = 0usize;
        let mut main_ptr = padded_preprocessed;
        for (name, prep_w, main_w, h) in layout.0.iter() {
            let prep_lo = preprocessed_ptr;
            let prep_hi = prep_lo + h * prep_w;
            preprocessed_table_index.insert(
                name.clone(),
                TraceOffset { dense_offset: prep_lo..prep_hi, poly_size: *h, num_polys: *prep_w },
            );
            preprocessed_ptr = prep_hi;

            let main_lo = main_ptr;
            let main_hi = main_lo + h * main_w;
            main_table_index.insert(
                name.clone(),
                TraceOffset { dense_offset: main_lo..main_hi, poly_size: *h, num_polys: *main_w },
            );
            main_ptr = main_hi;
        }

        TraceDenseData {
            dense,
            preprocessed_offset: padded_preprocessed,
            preprocessed_cols,
            preprocessed_padding: padded_preprocessed - total_preprocessed,
            main_padding: padded_main - total_main,
            preprocessed_table_index,
            main_table_index,
        }
    }
}

impl<F: Field, B: Backend> HasBackend for TraceDenseData<F, B> {
    type Backend = B;
    fn backend(&self) -> &B {
        self.dense.backend()
    }
}

impl<F: Field, B: Backend> JaggedTraceMle<F, B> {
    pub fn new(
        dense_data: TraceDenseData<F, B>,
        col_index: Buffer<u32, B>,
        start_indices: Buffer<u32, B>,
        column_heights: Vec<u32>,
    ) -> Self {
        JaggedTraceMle(JaggedMle::new(dense_data, col_index, start_indices, column_heights))
    }
}

impl<F: Field> JaggedTraceMle<F, CpuBackend> {
    /// Build a `JaggedTraceMle` over a pre-allocated `dense` buffer using a chip-layout
    /// description as parallel slices. Constructs the inner [`TraceDenseData`] with the
    /// same layout as [`TraceDenseData::from_chip_layout`], plus the jagged column
    /// metadata: one logical column per chip column for both preprocessed and main,
    /// plus one padding column per section that has nonzero padding.
    ///
    /// All heights must be even, since column heights and column-index entries
    /// are stored at half-element granularity.
    pub fn from_chip_layout(
        dense: Buffer<F, CpuBackend>,
        layout: &AbstractChipLayoutWithHeights,
        log_stacking_height: u32,
    ) -> Self {
        assert!(layout.0.iter().all(|(_, _, _, h)| h % 2 == 0), "heights must be even");

        let dense_data = TraceDenseData::from_chip_layout(dense, layout, log_stacking_height);

        let total_dense = dense_data.dense.len();
        let preprocessed_padding = dense_data.preprocessed_padding;
        let main_padding = dense_data.main_padding;

        let num_data_cols: usize = layout.0.iter().map(|(_, p, m, _)| p + m).sum();
        let num_cols =
            num_data_cols + (preprocessed_padding > 0) as usize + (main_padding > 0) as usize;

        let mut col_index = vec![0u32; total_dense / 2];
        let mut start_idx = vec![0u32; num_cols + 1];
        let mut column_heights: Vec<u32> = Vec::with_capacity(num_cols);

        let mut col: u32 = 0;
        let mut cnt: usize = 0;

        let mut emit = |w: usize, h: usize, col: &mut u32, cnt: &mut usize| {
            let half = h / 2;
            for _ in 0..w {
                col_index[*cnt..*cnt + half].fill(*col);
                *cnt += half;
                start_idx[*col as usize + 1] = start_idx[*col as usize] + half as u32;
                column_heights.push(half as u32);
                *col += 1;
            }
        };

        for (_, prep_w, _, h) in layout.0.iter() {
            emit(*prep_w, *h, &mut col, &mut cnt);
        }
        if preprocessed_padding > 0 {
            emit(1, preprocessed_padding, &mut col, &mut cnt);
        }
        for (_, _, main_w, h) in layout.0.iter() {
            emit(*main_w, *h, &mut col, &mut cnt);
        }
        if main_padding > 0 {
            emit(1, main_padding, &mut col, &mut cnt);
        }

        debug_assert_eq!(cnt, total_dense / 2);
        debug_assert_eq!(col as usize, num_cols);

        Self::new(dense_data, Buffer::from(col_index), Buffer::from(start_idx), column_heights)
    }
}

impl<F: Field> JaggedTraceMle<F, TaskScope> {
    pub fn preprocessed_virtual_tensor(
        &'_ self,
        log_stacking_height: u32,
    ) -> TensorView<'_, F, TaskScope> {
        self.dense_data.preprocessed_virtual_tensor(log_stacking_height)
    }

    pub fn main_virtual_tensor(&'_ self, log_stacking_height: u32) -> TensorView<'_, F, TaskScope> {
        self.dense_data.main_virtual_tensor(log_stacking_height)
    }

    pub fn main_poly_height(&self, name: &str) -> Option<usize> {
        self.dense_data.main_poly_height(name)
    }

    pub fn preprocessed_poly_height(&self, name: &str) -> Option<usize> {
        self.dense_data.preprocessed_poly_height(name)
    }

    pub fn main_num_polys(&self, name: &str) -> Option<usize> {
        self.dense_data.main_num_polys(name)
    }

    pub fn main_size(&self) -> usize {
        self.dense_data.main_size()
    }

    pub fn preprocessed_num_polys(&self, name: &str) -> Option<usize> {
        self.dense_data.preprocessed_num_polys(name)
    }
}

/// The raw pointer to the dense data, for use in CUDA FFI calls.
#[repr(C)]
pub struct TraceDenseDataRaw<F> {
    dense: *const F,
}

/// The raw pointer to the dense data, for use in CUDA FFI calls.
#[repr(C)]
pub struct TraceDenseDataMutRaw<F> {
    dense: *mut F,
}

impl<F: Field, B: Backend> DenseData<B> for TraceDenseData<F, B> {
    type DenseDataRaw = TraceDenseDataRaw<F>;

    fn as_ptr(&self) -> TraceDenseDataRaw<F> {
        TraceDenseDataRaw { dense: self.dense.as_ptr() }
    }
}

impl<F: Field, B: Backend> DenseDataMut<B> for TraceDenseData<F, B> {
    type DenseDataMutRaw = TraceDenseDataMutRaw<F>;

    fn as_mut_ptr(&mut self) -> TraceDenseDataMutRaw<F> {
        TraceDenseDataMutRaw { dense: self.dense.as_mut_ptr() }
    }
}

impl<F: Field> JaggedTraceMle<F, CpuBackend> {
    pub fn into_device(self, t: &TaskScope) -> JaggedTraceMle<F, TaskScope> {
        let JaggedMle { col_index, start_indices, column_heights, dense_data } = self.0;
        JaggedTraceMle::new(
            dense_data.into_device_in(t),
            DeviceBuffer::from_host(&col_index, t).unwrap().into_inner(),
            DeviceBuffer::from_host(&start_indices, t).unwrap().into_inner(),
            column_heights,
        )
    }
}

impl<F: Field> TraceDenseData<F, CpuBackend> {
    pub fn into_device_in(self, t: &TaskScope) -> TraceDenseData<F, TaskScope> {
        TraceDenseData {
            dense: DeviceBuffer::from_host(&self.dense, t).unwrap().into_inner(),
            preprocessed_offset: self.preprocessed_offset,
            preprocessed_cols: self.preprocessed_cols,
            preprocessed_table_index: self.preprocessed_table_index,
            main_table_index: self.main_table_index,
            preprocessed_padding: self.preprocessed_padding,
            main_padding: self.main_padding,
        }
    }
}

impl<F: Field> JaggedTraceMle<F, TaskScope> {
    pub fn into_host(self) -> JaggedTraceMle<F, CpuBackend> {
        let JaggedMle { col_index, start_indices, column_heights, dense_data } = self.0;
        let host_dense = dense_data.into_host();
        // Convert device buffers to host using DeviceBuffer wrapper
        let col_index_host = DeviceBuffer::from_raw(col_index).to_host().unwrap().into();
        let start_indices_host = DeviceBuffer::from_raw(start_indices).to_host().unwrap().into();
        JaggedTraceMle::new(host_dense, col_index_host, start_indices_host, column_heights)
    }
}

impl<F: Field> TraceDenseData<F, TaskScope> {
    pub fn into_host(self) -> TraceDenseData<F, CpuBackend> {
        let host_dense = DeviceBuffer::from_raw(self.dense).to_host().unwrap().into();
        TraceDenseData {
            dense: host_dense,
            preprocessed_offset: self.preprocessed_offset,
            preprocessed_cols: self.preprocessed_cols,
            preprocessed_table_index: self.preprocessed_table_index,
            main_table_index: self.main_table_index,
            preprocessed_padding: self.preprocessed_padding,
            main_padding: self.main_padding,
        }
    }
}