pire_gemm_s8u8s32/
lib.rs

1#[cfg(target_arch = "aarch64")]
2pub(crate) mod arm64;
3#[cfg(target_arch = "x86_64")]
4pub(crate) mod x86_64_arch;
5#[cfg(target_arch = "x86")]
6pub(crate) mod x86_arch;
7
8#[cfg(target_arch = "x86_64")]
9use x86_64_arch::{
10    get_mcnckc_simd, packa_fn_simd, packb_fn_simd, pire_gemm, round_k_simd, round_m_simd, KernelDispatcher,
11};
12
13#[cfg(target_arch = "x86")]
14use x86_arch::{
15    get_mcnckc_simd, packa_fn_simd, packb_fn_simd, pire_gemm, round_k_simd, round_m_simd, KernelDispatcher,
16};
17
18#[cfg(target_arch = "aarch64")]
19use arm64::{get_mcnckc_simd, packa_fn_simd, packb_fn_simd, pire_gemm, round_k_simd, round_m_simd, KernelDispatcher};
20
21pub(crate) mod reference;
22
23use core::mem::size_of;
24
25pub(crate) type TA = i8;
26pub(crate) type TB = u8;
27pub(crate) type TC = i32;
28#[allow(unused)]
29const TC_SIZE: usize = size_of::<TC>();
30
31use reference::{packa_fn_ref, packb_fn_ref, round_k_ref, round_m_ref, RefGemm};
32
33use pire_base::{
34    get_cache_params, has_i8i32_compute, Array, ArrayMut, GemmCache, IdentityFn, PirePar, UnaryFn, AB_ALIGN,
35};
36
37pub trait UnaryFnC: UnaryFn<TC> {}
38impl<F: UnaryFn<TC>> UnaryFnC for F {}
39
40pub(crate) unsafe fn pire_gemm_s8u8s32_fused<F: UnaryFnC>(
41    m: usize,
42    n: usize,
43    k: usize,
44    alpha: f32,
45    a: Array<TA>,
46    b: Array<TB>,
47    beta: f32,
48    c: ArrayMut<TC>,
49    f: F,
50) {
51    let par = PirePar::default(m, n);
52    if has_i8i32_compute() {
53        #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))]
54        {
55            let hw_config = KernelDispatcher::new(f);
56            pire_gemm(&hw_config, m, n, k, alpha, a, b, beta, c, &par);
57            return;
58        }
59    }
60    // if none of the optimized paths are available, use reference implementation
61    let hw_config = RefGemm::new(f);
62    reference::pire_gemm(&hw_config, m, n, k, alpha, a, b, beta, c, &par);
63}
64
65pub unsafe fn pire_gemm_s8u8s32(
66    m: usize,
67    n: usize,
68    k: usize,
69    alpha: f32,
70    a: *const TA,
71    a_rs: usize,
72    a_cs: usize,
73    b: *const TB,
74    b_rs: usize,
75    b_cs: usize,
76    beta: f32,
77    c: *mut TC,
78    c_rs: usize,
79    c_cs: usize,
80) {
81    // transpose if c is row strided i.e. c_cs == 1 and c_rs != 1
82    // let (m, n, a_rs, a_cs, b_rs, b_cs, c_rs, c_cs, a, b) = if c_cs == 1 && c_rs != 1 {
83    // 	(n, m, b_rs, b_cs, a_rs, a_cs, c_cs, c_rs, b, a)
84    // } else {
85    // 	(m, n, a_rs, a_cs, b_rs, b_cs, c_rs, c_cs, a, b)
86    // };
87    let a = Array::strided_matrix(a, a_rs, a_cs);
88    let b = Array::strided_matrix(b, b_rs, b_cs);
89    let c = ArrayMut::strided_matrix(c, c_rs, c_cs);
90    let identity_fn = IdentityFn {};
91    pire_gemm_s8u8s32_fused(m, n, k, alpha, a, b, beta, c, identity_fn);
92}
93
94#[cfg(feature = "fuse")]
95pub unsafe fn pire_gemm_s8u8s32_fn_ptr(
96    m: usize,
97    n: usize,
98    k: usize,
99    alpha: f32,
100    a: *const TA,
101    a_rs: usize,
102    a_cs: usize,
103    b: *const TB,
104    b_rs: usize,
105    b_cs: usize,
106    beta: f32,
107    c: *mut TC,
108    c_rs: usize,
109    c_cs: usize,
110    unary: unsafe fn(*mut TC, usize),
111) {
112    // transpose if c is row strided i.e. c_cs == 1 and c_rs != 1
113    // let (m, n, a_rs, a_cs, b_rs, b_cs, c_rs, c_cs, a, b) = if c_cs == 1 && c_rs != 1 {
114    //     (n, m, b_rs, b_cs, a_rs, a_cs, c_cs, c_rs, b, a)
115    // } else {
116    //     (m, n, a_rs, a_cs, b_rs, b_cs, c_rs, c_cs, a, b)
117    // };
118    let a = Array::strided_matrix(a, a_rs, a_cs);
119    let b = Array::strided_matrix(b, b_rs, b_cs);
120    let c = ArrayMut::strided_matrix(c, c_rs, c_cs);
121    pire_gemm_s8u8s32_fused(m, n, k, alpha, a, b, beta, c, unary);
122}
123
124fn dispatch_round_m() -> fn(usize) -> usize {
125    #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))]
126    {
127        if has_i8i32_compute() {
128            return round_m_simd;
129        }
130    }
131    round_m_ref
132}
133fn dispatch_round_k() -> fn(usize) -> usize {
134    #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))]
135    {
136        if has_i8i32_compute() {
137            return round_k_simd;
138        }
139    }
140    round_k_ref
141}
142
143fn dispatch_pack_a() -> unsafe fn(*const TA, *mut TA, usize, usize, usize, usize) {
144    #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))]
145    {
146        if has_i8i32_compute() {
147            return packa_fn_simd;
148        }
149    }
150    packa_fn_ref
151}
152
153fn dispatch_pack_b() -> unsafe fn(*const TB, *mut TB, usize, usize, usize, usize) {
154    #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))]
155    {
156        if has_i8i32_compute() {
157            return packb_fn_simd;
158        }
159    }
160    packb_fn_ref
161}
162
163fn dispatch_get_mcnckc() -> (usize, usize, usize) {
164    #[cfg(any(target_arch = "x86_64", target_arch = "x86", target_arch = "aarch64"))]
165    {
166        if has_i8i32_compute() {
167            return get_mcnckc_simd();
168        }
169    }
170    get_cache_params()
171}
172
173pire_base::packing_api!(TA, TB);
174
175#[cfg(test)]
176mod tests {
177    use super::*;
178    use pire_base::{get_cache_params, matrix_size};
179    use pire_dev::{
180        check_gemm_s8u8s32, generate_k_dims, generate_m_dims, generate_n_dims, layout_to_strides,
181        random_matrix_uniform, ABLayout,
182    };
183    #[test]
184    fn test_pack_a() {
185        let a_stride_scale = 1;
186        let (mc, _, kc) = get_mcnckc();
187        let (mr, _, kr) = (48, 8, 8);
188        let m_dims = generate_m_dims(mc, mr);
189        let k_dims = generate_k_dims(kc, kr);
190
191        for &m in &m_dims {
192            for &k in &k_dims {
193                let a_rs = 1 * a_stride_scale;
194                let a_cs = m * a_stride_scale;
195                let a_size = a_size_packed(m, k);
196                let a = vec![0i8; m * k * a_stride_scale];
197                let mut ap = vec![0i8; a_size + AB_ALIGN];
198                let ap_align_offset = ap.as_ptr().align_offset(AB_ALIGN);
199                // random_matrix_uniform(&mut a);
200                let ap_array = pack_a(m, k, &a, a_rs, a_cs, &mut ap[ap_align_offset..]);
201                assert!(!ap_array.is_strided() || m == 1);
202            }
203        }
204    }
205
206    #[test]
207    fn test_pack_b() {
208        let b_stride_scale = 1;
209        let (_, nc, kc) = get_mcnckc();
210        let (_, nr, kr) = (48, 8, 8);
211        let n_dims = generate_n_dims(nc, nr);
212        let k_dims = generate_k_dims(kc, kr);
213
214        for &n in &n_dims {
215            for &k in &k_dims {
216                let b_rs = 1 * b_stride_scale;
217                let b_cs = k * b_stride_scale;
218                let b_size = b_size_packed(n, k);
219                let b = vec![0u8; n * k * b_stride_scale];
220                let mut bp = vec![0u8; b_size + AB_ALIGN];
221                let bp_align_offset = bp.as_ptr().align_offset(AB_ALIGN);
222                let bp_array = pack_b(n, k, &b, b_rs, b_cs, &mut bp[bp_align_offset..]);
223                assert!(!bp_array.is_strided() || n == 1);
224            }
225        }
226    }
227
228    #[allow(unreachable_code)]
229    pub(crate) fn get_mcnckc() -> (usize, usize, usize) {
230        #[cfg(target_arch = "x86_64")]
231        {
232            return x86_64_arch::get_mcnckc_simd();
233        }
234        get_cache_params()
235    }
236
237    unsafe fn unary_fn_test(c: *mut TC, m: usize) {
238        for i in 0..m {
239            *c.add(i) *= 2;
240        }
241    }
242
243    const EPS: f64 = 1e-1;
244
245    static ALPHA_ARR: [f32; 1] = [2.0];
246    static BETA_ARR: [f32; 1] = [3.0];
247
248    fn test_gemm(layout: &ABLayout, is_a_packed: bool, is_b_packed: bool) {
249        let a_stride_scale = 1;
250        let b_stride_scale = 1;
251        let c_stride_scale = 2;
252        let (mc, nc, kc) = get_mcnckc();
253        let (mr, nr, kr) = (48, 8, 8);
254        let m_dims = generate_m_dims(mc, mr);
255        let n_dims = generate_n_dims(nc, nr);
256        let k_dims = generate_k_dims(kc, kr);
257        let unary_fn: unsafe fn(*mut TC, usize) = unary_fn_test;
258        let m_max = *m_dims.iter().max().unwrap();
259        let n_max = *n_dims.iter().max().unwrap();
260        let k_max = *k_dims.iter().max().unwrap();
261        let a_size = matrix_size(m_max, k_max) * a_stride_scale;
262        let b_size = matrix_size(k_max, n_max) * b_stride_scale;
263        let c_size = matrix_size(m_max, n_max) * c_stride_scale;
264        let mut a = vec![0i8; a_size];
265        let mut b = vec![0u8; b_size];
266        random_matrix_uniform(&mut a);
267        random_matrix_uniform(&mut b);
268        let mut c = vec![0i32; c_size];
269        let mut c_ref = vec![0i32; c_size];
270
271        let ap_size = if is_a_packed { a_size_packed(m_max, k_max) } else { 0 };
272        let mut ap = vec![0i8; ap_size + AB_ALIGN];
273        let ap_align_offset = ap.as_ptr().align_offset(AB_ALIGN);
274        let ap_mut_ref = &mut ap[ap_align_offset..];
275
276        let bp_size = if is_b_packed { b_size_packed(n_max, k_max) } else { 0 };
277        let mut bp = vec![0u8; bp_size + AB_ALIGN];
278        let bp_align_offset = bp.as_ptr().align_offset(AB_ALIGN);
279        let bp_mut_ref = &mut bp[bp_align_offset..];
280        for &m in &m_dims {
281            for &n in &n_dims {
282                for &k in &k_dims {
283                    let (a_rs, a_cs, b_rs, b_cs, c_rs, c_cs) = layout_to_strides(&layout, m, n, k);
284                    let (a_rs, a_cs, b_rs, b_cs, c_rs, c_cs) = (
285                        a_rs * a_stride_scale,
286                        a_cs * a_stride_scale,
287                        b_rs * b_stride_scale,
288                        b_cs * b_stride_scale,
289                        c_rs * c_stride_scale,
290                        c_cs * c_stride_scale,
291                    );
292                    let a_matrix = if is_a_packed {
293                        pack_a(m, k, &a, a_rs, a_cs, ap_mut_ref)
294                    } else {
295                        Array::strided_matrix(a.as_ptr(), a_rs, a_cs)
296                    };
297                    let b_matrix = if is_b_packed {
298                        pack_b(n, k, &b, b_rs, b_cs, bp_mut_ref)
299                    } else {
300                        Array::strided_matrix(b.as_ptr(), b_rs, b_cs)
301                    };
302                    for alpha in ALPHA_ARR {
303                        for beta in BETA_ARR {
304                            random_matrix_uniform(&mut c);
305                            c_ref.copy_from_slice(&c);
306                            let c_matrix = ArrayMut::strided_matrix(c.as_mut_ptr(), c_rs, c_cs);
307                            unsafe {
308                                pire_gemm_s8u8s32_fused(m, n, k, alpha, a_matrix, b_matrix, beta, c_matrix, unary_fn);
309                            }
310                            let diff_max = unsafe {
311                                check_gemm_s8u8s32(
312                                    m,
313                                    n,
314                                    k,
315                                    alpha,
316                                    a.as_ptr(),
317                                    a_rs,
318                                    a_cs,
319                                    b.as_ptr(),
320                                    b_rs,
321                                    b_cs,
322                                    beta,
323                                    &mut c,
324                                    c_rs,
325                                    c_cs,
326                                    &mut c_ref,
327                                    unary_fn,
328                                    EPS,
329                                )
330                            };
331                            // if diff_max >= EPS {
332                            // 	println!("a: {:?}", a);
333                            // 	println!("b: {:?}", b);
334                            // 	println!("c:     {:?}", c);
335                            // 	println!("c_ref: {:?}", c_ref);
336                            // }
337                            assert!(
338                                diff_max < EPS,
339                                "diff_max: {}, m: {}, n: {}, k: {}, alpha: {}, beta: {}",
340                                diff_max,
341                                m,
342                                n,
343                                k,
344                                alpha,
345                                beta
346                            );
347                        }
348                    }
349                }
350            }
351        }
352    }
353    #[test]
354    fn test_nn_col() {
355        test_gemm(&ABLayout::NN, false, false);
356    }
357
358    #[test]
359    fn test_nt_col() {
360        test_gemm(&ABLayout::NT, false, false);
361    }
362
363    #[test]
364    fn test_tn_col() {
365        test_gemm(&ABLayout::TN, false, false);
366    }
367
368    #[test]
369    fn test_tt_col() {
370        test_gemm(&ABLayout::TT, false, false);
371    }
372    #[test]
373    fn test_nn_col_ap() {
374        test_gemm(&ABLayout::NN, true, false);
375    }
376    #[test]
377    fn test_nt_col_ap() {
378        test_gemm(&ABLayout::NT, true, false);
379    }
380    #[test]
381    fn test_tn_col_ap() {
382        test_gemm(&ABLayout::TN, true, false);
383    }
384    #[test]
385    fn test_tt_col_ap() {
386        test_gemm(&ABLayout::TT, true, false);
387    }
388    #[test]
389    fn test_nn_col_bp() {
390        test_gemm(&ABLayout::NN, false, true);
391    }
392    #[test]
393    fn test_nt_col_bp() {
394        test_gemm(&ABLayout::NT, false, true);
395    }
396    #[test]
397    fn test_tn_col_bp() {
398        test_gemm(&ABLayout::TN, false, true);
399    }
400    #[test]
401    fn test_tt_col_bp() {
402        test_gemm(&ABLayout::TT, false, true);
403    }
404
405    #[test]
406    fn test_nn_col_apbp() {
407        test_gemm(&ABLayout::NN, true, true);
408    }
409    #[test]
410    fn test_nt_col_apbp() {
411        test_gemm(&ABLayout::NT, true, true);
412    }
413    #[test]
414    fn test_tn_col_apbp() {
415        test_gemm(&ABLayout::TN, true, true);
416    }
417    #[test]
418    fn test_tt_col_apbp() {
419        test_gemm(&ABLayout::TT, true, true);
420    }
421}