oxibonsai-kernels 0.1.2

1-bit Q1_0_g128 compute kernels (dequant, GEMV, GEMM) for OxiBonsai
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
//! Cache-line aligned memory allocations for SIMD kernel operations.
//!
//! Standard `Vec<f32>` alignment (4 bytes) is insufficient for optimal SIMD
//! loads and stores which require 32-byte (AVX) or 64-byte (AVX-512/cache line)
//! alignment. This module provides aligned buffer types that guarantee 64-byte
//! alignment for all allocations.

use std::alloc::Layout;

use oxibonsai_core::tensor::BlockQ1_0G128;

/// Alignment in bytes for all aligned allocations (cache line size).
pub const ALIGNMENT: usize = 64;

/// A cache-line aligned buffer of `f32` values.
///
/// Guarantees that the backing memory starts at a 64-byte boundary,
/// which is optimal for AVX-512 aligned loads and cache line prefetch.
///
/// # Example
///
/// ```
/// use oxibonsai_kernels::aligned::AlignedBuffer;
///
/// let buf = AlignedBuffer::new(256);
/// assert_eq!(buf.len(), 256);
/// assert_eq!(buf.as_ptr() as usize % 64, 0);
/// ```
pub struct AlignedBuffer {
    /// Raw pointer to the aligned allocation.
    ptr: *mut f32,
    /// Number of f32 elements.
    len: usize,
    /// Layout used for deallocation.
    layout: Layout,
}

// SAFETY: The buffer owns its allocation exclusively.
unsafe impl Send for AlignedBuffer {}
// SAFETY: Shared references to the buffer are read-only.
unsafe impl Sync for AlignedBuffer {}

impl AlignedBuffer {
    /// Allocate a new zero-initialized aligned buffer of `len` f32 elements.
    ///
    /// The returned buffer is guaranteed to have 64-byte alignment.
    /// A zero-length buffer produces a valid (dangling but aligned) pointer.
    pub fn new(len: usize) -> Self {
        if len == 0 {
            return Self {
                ptr: ALIGNMENT as *mut f32, // aligned dangling pointer
                len: 0,
                layout: Layout::from_size_align(0, ALIGNMENT)
                    .expect("zero-size layout should always be valid"),
            };
        }

        let byte_size = len * std::mem::size_of::<f32>();
        let layout = Layout::from_size_align(byte_size, ALIGNMENT)
            .expect("layout should be valid for reasonable buffer sizes");

        // SAFETY: layout has non-zero size and valid alignment.
        let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
        if ptr.is_null() {
            std::alloc::handle_alloc_error(layout);
        }

        Self {
            ptr: ptr.cast::<f32>(),
            len,
            layout,
        }
    }

    /// Returns the number of f32 elements in this buffer.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the buffer contains no elements.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the raw pointer to the start of the buffer.
    #[inline]
    pub fn as_ptr(&self) -> *const f32 {
        self.ptr
    }

    /// Returns a mutable raw pointer to the start of the buffer.
    #[inline]
    pub fn as_mut_ptr(&mut self) -> *mut f32 {
        self.ptr
    }

    /// View the buffer as an immutable slice.
    #[inline]
    pub fn as_slice(&self) -> &[f32] {
        if self.len == 0 {
            return &[];
        }
        // SAFETY: ptr is valid for len elements, properly aligned, and initialized to zero.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }

    /// View the buffer as a mutable slice.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [f32] {
        if self.len == 0 {
            return &mut [];
        }
        // SAFETY: ptr is valid for len elements, properly aligned, and we have exclusive access.
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
    }

    /// Copy data from a slice into this buffer.
    ///
    /// Panics if `src.len() > self.len()`.
    pub fn copy_from_slice(&mut self, src: &[f32]) {
        assert!(
            src.len() <= self.len,
            "source slice length ({}) exceeds buffer length ({})",
            src.len(),
            self.len
        );
        self.as_mut_slice()[..src.len()].copy_from_slice(src);
    }
}

impl Drop for AlignedBuffer {
    fn drop(&mut self) {
        if self.len > 0 {
            // SAFETY: ptr was allocated with this layout in `new`.
            unsafe {
                std::alloc::dealloc(self.ptr.cast::<u8>(), self.layout);
            }
        }
    }
}

impl std::fmt::Debug for AlignedBuffer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AlignedBuffer")
            .field("len", &self.len)
            .field("alignment", &ALIGNMENT)
            .field("aligned", &(self.as_ptr() as usize % ALIGNMENT == 0))
            .finish()
    }
}

/// A cache-line aligned buffer of `BlockQ1_0G128` values.
///
/// Same alignment guarantees as [`AlignedBuffer`] but for quantized weight blocks.
pub struct AlignedBlocks {
    /// Raw pointer to the aligned allocation.
    ptr: *mut BlockQ1_0G128,
    /// Number of block elements.
    len: usize,
    /// Layout used for deallocation.
    layout: Layout,
}

// SAFETY: The buffer owns its allocation exclusively.
unsafe impl Send for AlignedBlocks {}
// SAFETY: Shared references to the buffer are read-only.
unsafe impl Sync for AlignedBlocks {}

impl AlignedBlocks {
    /// Allocate a new zero-initialized aligned buffer of `len` blocks.
    pub fn new(len: usize) -> Self {
        if len == 0 {
            return Self {
                ptr: ALIGNMENT as *mut BlockQ1_0G128,
                len: 0,
                layout: Layout::from_size_align(0, ALIGNMENT)
                    .expect("zero-size layout should always be valid"),
            };
        }

        let byte_size = len * std::mem::size_of::<BlockQ1_0G128>();
        let layout = Layout::from_size_align(byte_size, ALIGNMENT)
            .expect("layout should be valid for reasonable buffer sizes");

        // SAFETY: layout has non-zero size and valid alignment.
        let ptr = unsafe { std::alloc::alloc_zeroed(layout) };
        if ptr.is_null() {
            std::alloc::handle_alloc_error(layout);
        }

        Self {
            ptr: ptr.cast::<BlockQ1_0G128>(),
            len,
            layout,
        }
    }

    /// Returns the number of blocks.
    #[inline]
    pub fn len(&self) -> usize {
        self.len
    }

    /// Returns `true` if the buffer contains no blocks.
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len == 0
    }

    /// Returns the raw pointer to the start of the buffer.
    #[inline]
    pub fn as_ptr(&self) -> *const BlockQ1_0G128 {
        self.ptr
    }

    /// View the buffer as an immutable slice.
    #[inline]
    pub fn as_slice(&self) -> &[BlockQ1_0G128] {
        if self.len == 0 {
            return &[];
        }
        // SAFETY: ptr is valid for len elements, properly aligned, and zero-initialized.
        unsafe { std::slice::from_raw_parts(self.ptr, self.len) }
    }

    /// View the buffer as a mutable slice.
    #[inline]
    pub fn as_mut_slice(&mut self) -> &mut [BlockQ1_0G128] {
        if self.len == 0 {
            return &mut [];
        }
        // SAFETY: ptr is valid for len elements, properly aligned, and we have exclusive access.
        unsafe { std::slice::from_raw_parts_mut(self.ptr, self.len) }
    }
}

impl Drop for AlignedBlocks {
    fn drop(&mut self) {
        if self.len > 0 {
            // SAFETY: ptr was allocated with this layout in `new`.
            unsafe {
                std::alloc::dealloc(self.ptr.cast::<u8>(), self.layout);
            }
        }
    }
}

impl std::fmt::Debug for AlignedBlocks {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("AlignedBlocks")
            .field("len", &self.len)
            .field("alignment", &ALIGNMENT)
            .finish()
    }
}

/// Split a slice at cache-line boundaries.
///
/// Returns `(prefix, aligned_middle, suffix)` where `aligned_middle` starts
/// at a 64-byte aligned address and has a 64-byte aligned length (in bytes).
///
/// If the input is already aligned, `prefix` will be empty.
/// If the input is too short to contain any aligned portion, the entire
/// slice is returned as `prefix` with empty `aligned_middle` and `suffix`.
pub fn align_to_cache_line(data: &[f32]) -> (&[f32], &[f32], &[f32]) {
    if data.is_empty() {
        return (&[], &[], &[]);
    }

    let ptr = data.as_ptr() as usize;
    let f32_size = std::mem::size_of::<f32>();

    // How many bytes past the last alignment boundary?
    let misalign_bytes = ptr % ALIGNMENT;

    // Number of f32s to skip to reach alignment
    let prefix_len = if misalign_bytes == 0 {
        0
    } else {
        let skip_bytes = ALIGNMENT - misalign_bytes;
        // Round up to whole f32s
        skip_bytes.div_ceil(f32_size)
    };

    if prefix_len >= data.len() {
        // Entire slice is in the prefix — no aligned middle
        return (data, &[], &[]);
    }

    let remaining = data.len() - prefix_len;

    // How many f32s fit in a cache-line-aligned chunk?
    let f32s_per_line = ALIGNMENT / f32_size; // 16
    let aligned_len = (remaining / f32s_per_line) * f32s_per_line;

    let prefix = &data[..prefix_len];
    let aligned = &data[prefix_len..prefix_len + aligned_len];
    let suffix = &data[prefix_len + aligned_len..];

    (prefix, aligned, suffix)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn aligned_buffer_new_and_access() {
        let buf = AlignedBuffer::new(128);
        assert_eq!(buf.len(), 128);
        assert!(!buf.is_empty());
        // All zeros
        for &v in buf.as_slice() {
            assert!((v - 0.0).abs() < f32::EPSILON);
        }
    }

    #[test]
    fn aligned_buffer_alignment() {
        let buf = AlignedBuffer::new(256);
        let ptr_val = buf.as_ptr() as usize;
        assert_eq!(
            ptr_val % ALIGNMENT,
            0,
            "buffer pointer {ptr_val:#x} is not 64-byte aligned"
        );
    }

    #[test]
    fn aligned_buffer_zero_length() {
        let buf = AlignedBuffer::new(0);
        assert_eq!(buf.len(), 0);
        assert!(buf.is_empty());
        assert_eq!(buf.as_slice().len(), 0);
    }

    #[test]
    fn aligned_buffer_large() {
        let buf = AlignedBuffer::new(10_000);
        assert_eq!(buf.len(), 10_000);
        assert_eq!(buf.as_ptr() as usize % ALIGNMENT, 0);
    }

    #[test]
    fn aligned_buffer_copy_from_slice() {
        let mut buf = AlignedBuffer::new(8);
        let src = [1.0f32, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
        buf.copy_from_slice(&src);
        assert_eq!(buf.as_slice(), &src);
    }

    #[test]
    fn aligned_buffer_mut_slice() {
        let mut buf = AlignedBuffer::new(4);
        {
            let s = buf.as_mut_slice();
            s[0] = 42.0;
            s[3] = -1.0;
        }
        assert!((buf.as_slice()[0] - 42.0).abs() < f32::EPSILON);
        assert!((buf.as_slice()[3] - (-1.0)).abs() < f32::EPSILON);
    }

    #[test]
    fn aligned_blocks_new_and_access() {
        let blocks = AlignedBlocks::new(16);
        assert_eq!(blocks.len(), 16);
        assert!(!blocks.is_empty());
        assert_eq!(blocks.as_ptr() as usize % ALIGNMENT, 0);
    }

    #[test]
    fn aligned_blocks_zero_length() {
        let blocks = AlignedBlocks::new(0);
        assert_eq!(blocks.len(), 0);
        assert!(blocks.is_empty());
        assert_eq!(blocks.as_slice().len(), 0);
    }

    #[test]
    fn align_to_cache_line_empty() {
        let data: &[f32] = &[];
        let (prefix, aligned, suffix) = align_to_cache_line(data);
        assert!(prefix.is_empty());
        assert!(aligned.is_empty());
        assert!(suffix.is_empty());
    }

    #[test]
    fn align_to_cache_line_already_aligned() {
        let buf = AlignedBuffer::new(64);
        let data = buf.as_slice();
        let (prefix, aligned, suffix) = align_to_cache_line(data);
        // Already aligned, so prefix should be empty
        assert!(
            prefix.is_empty(),
            "prefix should be empty for aligned buffer"
        );
        assert_eq!(aligned.len() + suffix.len(), data.len());
    }

    #[test]
    fn align_to_cache_line_preserves_data() {
        let buf = AlignedBuffer::new(128);
        let data = buf.as_slice();
        let (prefix, aligned, suffix) = align_to_cache_line(data);
        // Total length preserved
        assert_eq!(
            prefix.len() + aligned.len() + suffix.len(),
            data.len(),
            "split must preserve total length"
        );
    }

    #[test]
    fn aligned_buffer_debug() {
        let buf = AlignedBuffer::new(32);
        let dbg = format!("{buf:?}");
        assert!(dbg.contains("AlignedBuffer"));
        assert!(dbg.contains("32"));
    }

    #[test]
    fn aligned_blocks_debug() {
        let blocks = AlignedBlocks::new(8);
        let dbg = format!("{blocks:?}");
        assert!(dbg.contains("AlignedBlocks"));
    }
}