diff --git a/crates/native-cpu-expert/src/rust_ggml.rs b/crates/native-cpu-expert/src/rust_ggml.rs index 1f03bd2f..51af4911 100644 --- a/crates/native-cpu-expert/src/rust_ggml.rs +++ b/crates/native-cpu-expert/src/rust_ggml.rs @@ -78,33 +78,30 @@ mod tests { use std::panic::{AssertUnwindSafe, catch_unwind}; #[repr(C, align(8))] struct Aligned([u8; 512]); - // quantize_raw reinterprets `dst` as Q8Zero / Q8K / u16: a short or misaligned destination must be refused, not written through. + // quantize_raw reinterprets `dst` as Q8Zero / Q8K / u16: a short or misaligned destination must be refused, not + // written through. #[test] fn quantize_raw_refuses_a_short_or_misaligned_destination() { let x = [0.5f32; 64]; let k = [0.5f32; 256]; let mut a = Aligned([0; 512]); - // SAFETY (all calls): the destination checks are the asserts under test; no CPU leaf runs unless they pass (last block, avx2_ok()). - assert!( - catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q8Zero, &x, &mut a.0[..67]) })).is_err(), - "67 < 68 bytes" - ); - assert!( - catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q8Zero, &x, &mut a.0[1..69]) })).is_err(), - "odd address" - ); - assert!( - catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(Kind::Q4K, &k, &mut a.0[2..2 + 292]) })).is_err(), - "Q8K needs 4-byte alignment" - ); + assert!(quantize_is_refused(Kind::Q8Zero, &x, &mut a.0[..67]), "67 < 68 bytes"); + assert!(quantize_is_refused(Kind::Q8Zero, &x, &mut a.0[1..69]), "odd address"); + assert!(quantize_is_refused(Kind::Q4K, &k, &mut a.0[2..2 + 292]), "Q8K needs 4-byte alignment"); if super::super::rust_simd::avx2_ok() { + // SAFETY: avx2_ok() above; the destination holds the 68 bytes of two Q8Zero blocks and is 8-byte aligned. unsafe { quantize_raw(Kind::Q8Zero, &x, &mut a.0[..68]); } assert_ne!(&a.0[..2], &[0, 0], "FP16 block scale written"); } } - // The generic float dot reads `row` through raw 256-bit loads sized by the activation: a row shorter than 4 bytes per f32 is refused. + fn quantize_is_refused(kind: Kind, x: &[f32], dst: &mut [u8]) -> bool { + // SAFETY: the destination checks are the asserts under test; no CPU leaf runs unless they pass. + catch_unwind(AssertUnwindSafe(|| unsafe { quantize_raw(kind, x, dst) })).is_err() + } + // The generic float dot reads `row` through raw 256-bit loads sized by the activation: a row shorter than 4 bytes + // per f32 is refused. #[test] fn float_dot_refuses_a_row_shorter_than_the_activation() { if !super::super::rust_simd::avx2_ok() { @@ -122,12 +119,19 @@ mod tests { } mod impl_kind; +mod kind_table; #[allow(unused_imports)] use impl_kind::alloc; +#[allow(unused_imports)] +use impl_kind::round_bf16_scalar; mod impl_nativeformat; #[allow(unused_imports)] pub use impl_nativeformat::dot; #[allow(unused_imports)] +use impl_nativeformat::dot_k_blocks; +#[allow(unused_imports)] +use impl_nativeformat::dot_zero_blocks; +#[allow(unused_imports)] use impl_nativeformat::float_dot; #[allow(unused_imports)] use impl_nativeformat::q1_dot; diff --git a/crates/native-cpu-expert/src/rust_ggml/impl_kind.rs b/crates/native-cpu-expert/src/rust_ggml/impl_kind.rs index f105c37d..a1eb5bd2 100644 --- a/crates/native-cpu-expert/src/rust_ggml/impl_kind.rs +++ b/crates/native-cpu-expert/src/rust_ggml/impl_kind.rs @@ -1,101 +1,19 @@ //! Moved out of the parent module by STRA-338: impl Kind, impl ActKind, fn alloc, impl Activation. +use super::kind_table::KIND_TABLE; #[allow(unused_imports)] use super::*; impl Kind { pub fn from_original(type_id: i32) -> Result { - Ok(match type_id { - 0 => Self::F32, - 1 => Self::F16, - 2 => Self::Q4Zero, - 3 => Self::Q4One, - 6 => Self::Q5Zero, - 7 => Self::Q5One, - 8 => Self::Q8Zero, - 10 => Self::Q2K, - 11 => Self::Q3K, - 12 => Self::Q4K, - 13 => Self::Q5K, - 14 => Self::Q6K, - 16 => Self::Iq2Xxs, - 17 => Self::Iq2Xs, - 18 => Self::Iq3Xxs, - 19 => Self::Iq1S, - 20 => Self::Iq4Nl, - 21 => Self::Iq3S, - 22 => Self::Iq2S, - 23 => Self::Iq4Xs, - 29 => Self::Iq1M, - 30 => Self::Bf16, - 34 => Self::Tq1, - 35 => Self::Tq2, - 39 => Self::MxFp4, - 40 => Self::NvFp4, - 41 => Self::Q1Zero, - 42 => Self::Q2Zero, - _ => return Err(Error::Unsupported), - }) + KIND_TABLE.iter().find(|row| row.id == type_id).map(|row| row.kind).ok_or(Error::Unsupported) } pub fn original_id(self) -> i32 { - match self { - Self::F32 => 0, - Self::F16 => 1, - Self::Q4Zero => 2, - Self::Q4One => 3, - Self::Q5Zero => 6, - Self::Q5One => 7, - Self::Q8Zero => 8, - Self::Q2K => 10, - Self::Q3K => 11, - Self::Q4K => 12, - Self::Q5K => 13, - Self::Q6K => 14, - Self::Iq2Xxs => 16, - Self::Iq2Xs => 17, - Self::Iq3Xxs => 18, - Self::Iq1S => 19, - Self::Iq4Nl => 20, - Self::Iq3S => 21, - Self::Iq2S => 22, - Self::Iq4Xs => 23, - Self::Iq1M => 29, - Self::Bf16 => 30, - Self::Tq1 => 34, - Self::Tq2 => 35, - Self::MxFp4 => 39, - Self::NvFp4 => 40, - Self::Q1Zero => 41, - Self::Q2Zero => 42, - } + self.info().id } pub fn block(self) -> (usize, usize) { - match self { - Self::F32 => (1, 4), - Self::F16 | Self::Bf16 => (1, 2), - Self::Q4Zero | Self::Iq4Nl => (32, 18), - Self::Q4One => (32, 20), - Self::Q5Zero => (32, 22), - Self::Q5One => (32, 24), - Self::Q8Zero => (32, 34), - Self::Q2K => (256, 84), - Self::Q3K | Self::Iq3S => (256, 110), - Self::Q4K => (256, 144), - Self::Q5K => (256, 176), - Self::Q6K => (256, 210), - Self::Iq2Xxs | Self::Tq2 => (256, 66), - Self::Iq2Xs => (256, 74), - Self::Iq3Xxs => (256, 98), - Self::Iq1S => (256, 50), - Self::Iq2S => (256, 82), - Self::Iq4Xs => (256, 136), - Self::Iq1M => (256, 56), - Self::Tq1 => (256, 54), - Self::MxFp4 => (32, 17), - Self::NvFp4 => (64, 36), - Self::Q1Zero => (128, 18), - Self::Q2Zero => (64, 18), - } + let row = self.info(); + (row.block_elems, row.block_bytes) } pub fn row_bytes(self, n: usize) -> Result { let (q, b) = self.block(); @@ -160,60 +78,84 @@ impl Activation { pub fn quantize(weight_kind: Kind, input: &[f32]) -> Result { if !super::super::rust_simd::avx2_ok() { return Err(Error::Unsupported); - } /* SAFETY (every unsafe block below): avx2_ok() above proved AVX2+FMA+F16C; all vector lengths derive from kind.bytes(n) (n % block == 0) and each callee asserts its own slice lengths. */ + } let kind = weight_kind.act(); kind.bytes(input.len())?; let n = input.len(); - let data = match kind { - ActKind::F32 => { - let mut v = alloc(n)?; - v.copy_from_slice(input); - Storage::F32(v) - } - ActKind::F16 => { - let mut v = alloc(n)?; - for (&x, v) in input.iter().zip(&mut v) { - *v = unsafe { to_half(x) }; - } - Storage::Half(v) - } - ActKind::Bf16 => { - let mut v = alloc(n)?; - if !unsafe { super::super::rust_ggml_native::convert_bf16(input, &mut v) } { - for (&x, v) in input.iter().zip(&mut v) { - let b = x.to_bits(); - *v = if b & 0x7fffffff > 0x7f800000 { - ((b >> 16) | 64) as u16 - } else { - (b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16 - }; - } - } - Storage::Half(v) - } - ActKind::Zero => { - let mut v = alloc(n / 32)?; - unsafe { - super::super::rust_quant::q8_zero(input, &mut v); - } - Storage::Zero(v) - } - ActKind::One => { - let mut v = alloc(n / 32)?; - unsafe { - super::super::rust_kq::quant_one(input, &mut v); - } - Storage::One(v) - } - ActKind::K => { - let mut v = alloc(n / 256)?; - super::super::rust_quant::q8_k(input, &mut v); - Storage::K(v) - } - }; + let data = Self::encode(kind, input)?; Ok(Self { kind, n, data }) } + // Only called from quantize() after avx2_ok() proved AVX2+FMA+F16C and `kind.bytes(input.len())` proved the block + // geometry (n % block == 0); the encoders below rely on both. + fn encode(kind: ActKind, input: &[f32]) -> Result { + match kind { + ActKind::F32 => Self::encode_f32(input), + ActKind::F16 => Self::encode_f16(input), + ActKind::Bf16 => Self::encode_bf16(input), + ActKind::Zero => Self::encode_zero(input), + ActKind::One => Self::encode_one(input), + ActKind::K => Self::encode_k(input), + } + } + fn encode_f32(input: &[f32]) -> Result { + let mut v = alloc(input.len())?; + v.copy_from_slice(input); + Ok(Storage::F32(v)) + } + fn encode_f16(input: &[f32]) -> Result { + let mut v = alloc(input.len())?; + for (&x, v) in input.iter().zip(&mut v) { + // SAFETY: encode() runs after quantize() proved F16C with avx2_ok(). + *v = unsafe { to_half(x) }; + } + Ok(Storage::Half(v)) + } + fn encode_bf16(input: &[f32]) -> Result { + let mut v = alloc(input.len())?; + // SAFETY: encode() runs after quantize() proved AVX2 with avx2_ok(); `v` has `input.len()` elements. + if !unsafe { super::super::rust_ggml_native::convert_bf16(input, &mut v) } { + round_bf16_scalar(input, &mut v); + } + Ok(Storage::Half(v)) + } + fn encode_zero(input: &[f32]) -> Result { + let mut v = alloc(input.len() / 32)?; + // SAFETY: encode() runs after quantize() proved AVX2+FMA+F16C (avx2_ok()); `v` holds one Q8Zero per 32 inputs. + unsafe { + super::super::rust_quant::q8_zero(input, &mut v); + } + Ok(Storage::Zero(v)) + } + fn encode_one(input: &[f32]) -> Result { + let mut v = alloc(input.len() / 32)?; + // SAFETY: encode() runs after quantize() proved AVX2+FMA+F16C (avx2_ok()); `v` holds one Q8One per 32 inputs. + unsafe { + super::super::rust_kq::quant_one(input, &mut v); + } + Ok(Storage::One(v)) + } + fn encode_k(input: &[f32]) -> Result { + let mut v = alloc(input.len() / 256)?; + super::super::rust_quant::q8_k(input, &mut v); + Ok(Storage::K(v)) + } pub fn encoded_bytes(&self) -> Result { self.kind.bytes(self.n) } } +/// Round one f32 to its BF16 bits (round to nearest even; a NaN keeps a quiet payload bit). +#[inline] +fn bf16_bits(x: f32) -> u16 { + let b = x.to_bits(); + if b & 0x7fffffff > 0x7f800000 { + ((b >> 16) | 64) as u16 + } else { + (b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16 + } +} +/// Round `src` into `dst` element by element (`zip` stops at the shorter slice). +pub(super) fn round_bf16_scalar(src: &[f32], dst: &mut [u16]) { + for (&x, v) in src.iter().zip(dst) { + *v = bf16_bits(x); + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs b/crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs index 1bb1be1f..dc9f7e93 100644 --- a/crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs +++ b/crates/native-cpu-expert/src/rust_ggml/impl_nativeformat.rs @@ -10,14 +10,8 @@ impl NativeFormat { } let gu_row = gu.row_bytes(n_embd)?; let down_row = down.row_bytes(n_ff)?; - let activation_bytes = gu.act().bytes(n_embd)?; - let hidden_bytes = down.act().bytes(n_ff)?; - if activation_bytes > 4096 || hidden_bytes > 1024 { - return Err(Error::Shape); - } - let up_offset = gu_row.checked_mul(n_ff).ok_or(Error::Shape)?; - let down_offset = up_offset.checked_mul(2).ok_or(Error::Shape)?; - let bytes = down_row.checked_mul(n_embd).and_then(|b| b.checked_add(down_offset)).ok_or(Error::Shape)?; + let (activation_bytes, hidden_bytes) = Self::activation_sizes(gu, down, n_embd, n_ff)?; + let (up_offset, down_offset, bytes) = Self::bank_layout(gu_row, down_row, n_embd, n_ff)?; Ok(Self { gu, down, @@ -32,6 +26,22 @@ impl NativeFormat { hidden_bytes, }) } + // The encoded input (`gu` side) and hidden (`down` side) sizes, refused when they exceed the pool's fixed buffers. + fn activation_sizes(gu: Kind, down: Kind, n_embd: usize, n_ff: usize) -> Result<(usize, usize)> { + let activation_bytes = gu.act().bytes(n_embd)?; + let hidden_bytes = down.act().bytes(n_ff)?; + if activation_bytes > 4096 || hidden_bytes > 1024 { + return Err(Error::Shape); + } + Ok((activation_bytes, hidden_bytes)) + } + // The (up_offset, down_offset, total bytes) of one expert bank: gate rows, up rows, then down rows. + fn bank_layout(gu_row: usize, down_row: usize, n_embd: usize, n_ff: usize) -> Result<(usize, usize, usize)> { + let up_offset = gu_row.checked_mul(n_ff).ok_or(Error::Shape)?; + let down_offset = up_offset.checked_mul(2).ok_or(Error::Shape)?; + let bytes = down_row.checked_mul(n_embd).and_then(|b| b.checked_add(down_offset)).ok_or(Error::Shape)?; + Ok((up_offset, down_offset, bytes)) + } pub fn validate(&self) -> Result<()> { let f = Self::new(self.gu, self.down, self.n_embd, self.n_ff)?; if self.gu_row != f.gu_row @@ -54,59 +64,101 @@ pub fn dot(kind: Kind, row: &[u8], activation: &Activation) -> Result { if !super::super::rust_simd::avx2_ok() { return Err(Error::Unsupported); } - /* SAFETY: avx2_ok() above; `row.len() == row_bytes(n)` and `activation.kind == kind.act()` were checked, and `activation.data` was built by quantize() for exactly n elements of that encoding, so every kernel below gets whole, equal-count blocks. */ + // SAFETY: avx2_ok() above; `row.len() == row_bytes(n)` and `activation.kind == kind.act()` were checked, and + // `activation.data` was built by quantize() for exactly n elements of that encoding, so every kernel gets whole, + // equal-count blocks. + unsafe { dot_storage(kind, row, &activation.data) } +} +/// # Safety +/// The CPU gate (avx2_ok()); `row` is a whole weight row of `kind` and `data` its activation encoded with `kind.act()` +/// for the same element count. +unsafe fn dot_storage(kind: Kind, row: &[u8], data: &Storage) -> Result { unsafe { - match &activation.data { + match data { Storage::F32(v) => Ok(float_dot(kind, row, v, &[])), Storage::Half(v) => Ok(float_dot(kind, row, &[], v)), - Storage::Zero(v) => match kind { - Kind::Iq4Nl => { - let paired = v.len() / 2 * 2; - let mut out = [0.0]; - super::super::rust_iq::iq4nl(&row[..paired * 18], &[&v[..paired]], &mut out, true); - if paired < v.len() { - let b = &row[paired * 18..]; - let y = v[paired]; - let values = &super::super::rust_codebooks::KVALUES_IQ4NL; - let mut a = 0i32; - let mut c = 0i32; - for j in 0..16 { - a += y.qs[j] as i32 * values[(b[2 + j] & 15) as usize] as i32; - c += y.qs[j + 16] as i32 * values[(b[2 + j] >> 4) as usize] as i32; - } - out[0] += (half(y.d) * half(u16::from_le_bytes([b[0], b[1]]))) * (a + c) as f32; - } - Ok(out[0]) - } - Kind::Q2Zero => Ok(q2_generic(row, v)), - Kind::Q1Zero => Ok(q1_dot(row, v)), - Kind::MxFp4 => Ok(super::super::rust_ggml_extra::mxfp4(row, v)), - Kind::NvFp4 => Ok(super::super::rust_ggml_extra::nvfp4(row, v)), - Kind::Q4Zero | Kind::Q5Zero | Kind::Q8Zero => { - Ok(super::super::rust_kq::small_dot(kind.original_id(), row, Some(v), None)) - } - _ => Err(Error::Unsupported), - }, + Storage::Zero(v) => dot_zero_blocks(kind, row, v).ok_or(Error::Unsupported), Storage::One(v) => Ok(super::super::rust_kq::small_dot(kind.original_id(), row, None, Some(v))), - Storage::K(v) => match kind { - Kind::Iq1S | Kind::Iq1M => Ok(super::super::rust_ggml_extra::iq1(kind.original_id(), row, v)), - Kind::Tq1 | Kind::Tq2 => Ok(super::super::rust_ggml_extra::ternary(kind.original_id(), row, v)), - Kind::Q4K => { - let mut out = [0.0]; - super::super::rust_kq::q4_k_dot(row, &[v], &mut out); - Ok(out[0]) - } - Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => { - Ok(super::super::rust_k_blocks::dot(kind.original_id(), row, v)) - } - Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq3Xxs | Kind::Iq3S | Kind::Iq2S | Kind::Iq4Xs => { - Ok(super::super::rust_iq::dot_single(kind.original_id(), row, v)) - } - _ => Err(Error::Unsupported), - }, + Storage::K(v) => dot_k_blocks(kind, row, v).ok_or(Error::Unsupported), } } } +/// The row product of a `Zero`-encoded activation; `None` for a kind that is not stored with it. +/// +/// # Safety +/// The CPU gate (avx2_ok()); `row` is a whole weight row of `kind` and `y` its activation, one block per 32 elements. +pub(super) unsafe fn dot_zero_blocks(kind: Kind, row: &[u8], y: &[Q8Zero]) -> Option { + unsafe { + Some(match kind { + Kind::Iq4Nl => iq4nl_dot(row, y), + Kind::Q2Zero => q2_generic(row, y), + Kind::Q1Zero => q1_dot(row, y), + Kind::MxFp4 => super::super::rust_ggml_extra::mxfp4(row, y), + Kind::NvFp4 => super::super::rust_ggml_extra::nvfp4(row, y), + Kind::Q4Zero | Kind::Q5Zero | Kind::Q8Zero => { + super::super::rust_kq::small_dot(kind.original_id(), row, Some(y), None) + } + _ => return None, + }) + } +} +/// The row product of a `K`-encoded activation; `None` for a kind that is not stored with it. +/// +/// # Safety +/// The CPU gate (avx2_ok()); `row` is a whole weight row of `kind` and `y` its activation, one block per 256 elements. +pub(super) unsafe fn dot_k_blocks(kind: Kind, row: &[u8], y: &[Q8K]) -> Option { + unsafe { + Some(match kind { + Kind::Iq1S | Kind::Iq1M => super::super::rust_ggml_extra::iq1(kind.original_id(), row, y), + Kind::Tq1 | Kind::Tq2 => super::super::rust_ggml_extra::ternary(kind.original_id(), row, y), + Kind::Q4K => { + let mut out = [0.0]; + super::super::rust_kq::q4_k_dot(row, &[y], &mut out); + out[0] + } + Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => { + super::super::rust_k_blocks::dot(kind.original_id(), row, y) + } + Kind::Iq2Xxs | Kind::Iq2Xs | Kind::Iq3Xxs | Kind::Iq3S | Kind::Iq2S | Kind::Iq4Xs => { + super::super::rust_iq::dot_single(kind.original_id(), row, y) + } + _ => return None, + }) + } +} +/// IQ4_NL row product: whole block pairs through the vector kernel, an odd last block through the scalar tail. +/// +/// # Safety +/// The CPU gate (avx2_ok()); `row` holds `y.len()` IQ4_NL blocks of 18 bytes. +#[inline(always)] +unsafe fn iq4nl_dot(row: &[u8], y: &[Q8Zero]) -> f32 { + unsafe { + let paired = y.len() / 2 * 2; + let mut out = [0.0]; + super::super::rust_iq::iq4nl(&row[..paired * 18], &[&y[..paired]], &mut out, true); + if paired < y.len() { + out[0] += iq4nl_tail(&row[paired * 18..], y[paired]); + } + out[0] + } +} +/// The product of one IQ4_NL block `b` (2 scale bytes, 16 nibble bytes) with the activation block `y`. +/// +/// # Safety +/// The CPU gate (avx2_ok(), F16C for `half`); `b` holds at least 18 bytes. +#[inline(always)] +unsafe fn iq4nl_tail(b: &[u8], y: Q8Zero) -> f32 { + unsafe { + let values = &super::super::rust_codebooks::KVALUES_IQ4NL; + let mut a = 0i32; + let mut c = 0i32; + for j in 0..16 { + a += y.qs[j] as i32 * values[(b[2 + j] & 15) as usize] as i32; + c += y.qs[j + 16] as i32 * values[(b[2 + j] >> 4) as usize] as i32; + } + (half(y.d) * half(u16::from_le_bytes([b[0], b[1]]))) * (a + c) as f32 + } +} #[target_feature(enable = "avx2,fma,f16c")] pub(super) unsafe fn float_dot(kind: Kind, row: &[u8], f: &[f32], h: &[u16]) -> f32 { unsafe { @@ -116,55 +168,101 @@ pub(super) unsafe fn float_dot(kind: Kind, row: &[u8], f: &[f32], h: &[u16]) -> return value; } let np = n & !31; + let sum = float_vector_sum(kind, row, f, h, np); + if kind == Kind::F32 { float_tail_f32(row, f, sum, np, n) } else { float_tail_half(kind, row, h, sum, np, n) } + } +} +/// The eight-lane partial sums of the first `np` elements (a multiple of 32): four accumulators, combined (0+2)+(1+3). +/// +/// # Safety +/// AVX2+FMA+F16C; `row` holds `np` elements of `kind` and the matching activation slice (`f` for F32, else `h`) too. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn float_vector_sum(kind: Kind, row: &[u8], f: &[f32], h: &[u16], np: usize) -> __m256 { + unsafe { let mut acc = [_mm256_setzero_ps(); 4]; for at in (0..np).step_by(32) { for j in 0..4 { - let i = at + j * 8; - let (x, y) = match kind { - Kind::F32 => (_mm256_loadu_ps(row.as_ptr().add(i * 4).cast()), _mm256_loadu_ps(f.as_ptr().add(i))), - Kind::F16 => ( - _mm256_cvtph_ps(_mm_loadu_si128(row.as_ptr().add(i * 2).cast())), - _mm256_cvtph_ps(_mm_loadu_si128(h.as_ptr().add(i).cast())), - ), - Kind::Bf16 => ( - _mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128( - row.as_ptr().add(i * 2).cast(), - )))), - _mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128( - h.as_ptr().add(i).cast(), - )))), - ), - _ => unreachable!(), - }; - acc[j] = if kind == Kind::Bf16 { - _mm256_add_ps(_mm256_mul_ps(x, y), acc[j]) - } else { - _mm256_fmadd_ps(x, y, acc[j]) - }; + let (x, y) = float_load_pair(kind, row, f, h, at + j * 8); + acc[j] = float_accumulate(kind, x, y, acc[j]); } } - let sum = _mm256_add_ps(_mm256_add_ps(acc[0], acc[2]), _mm256_add_ps(acc[1], acc[3])); - if kind == Kind::F32 { - let mut s = hsum_original(sum); - for i in np..n { - s += f32::from_le_bytes(row[i * 4..i * 4 + 4].try_into().unwrap()) * f[i]; - } - s - } else { - let mut s = if kind == Kind::Bf16 { hsum_ggml(sum) } else { hsum_original(sum) } as f64; - for i in np..n { - let a = u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]); - let (a, b) = if kind == Kind::Bf16 { - (f32::from_bits((a as u32) << 16), f32::from_bits((h[i] as u32) << 16)) - } else { - (half(a), half(h[i])) - }; - s += (a * b) as f64; - } - s as f32 + _mm256_add_ps(_mm256_add_ps(acc[0], acc[2]), _mm256_add_ps(acc[1], acc[3])) + } +} +/// Eight weights and the eight matching activations starting at element `i`. +/// +/// # Safety +/// AVX2+FMA+F16C; elements `i..i + 8` exist in `row` and in `f` (F32) or `h` (F16/BF16); `kind` is F32, F16 or BF16. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn float_load_pair(kind: Kind, row: &[u8], f: &[f32], h: &[u16], i: usize) -> (__m256, __m256) { + unsafe { + match kind { + Kind::F32 => (_mm256_loadu_ps(row.as_ptr().add(i * 4).cast()), _mm256_loadu_ps(f.as_ptr().add(i))), + Kind::F16 => ( + _mm256_cvtph_ps(_mm_loadu_si128(row.as_ptr().add(i * 2).cast())), + _mm256_cvtph_ps(_mm_loadu_si128(h.as_ptr().add(i).cast())), + ), + Kind::Bf16 => (bf16_widen(row.as_ptr().add(i * 2).cast()), bf16_widen(h.as_ptr().add(i).cast())), + _ => unreachable!(), } } } +/// Eight BF16 values widened to f32 lanes (a BF16 is the high half of its f32). +/// +/// # Safety +/// AVX2; `p` points at 16 readable bytes. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn bf16_widen(p: *const __m128i) -> __m256 { + unsafe { _mm256_castsi256_ps(_mm256_slli_epi32::<16>(_mm256_cvtepu16_epi32(_mm_loadu_si128(p)))) } +} +/// `acc + x * y`: a separate multiply and add for BF16, a fused multiply-add otherwise. +/// +/// # Safety +/// AVX2+FMA. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn float_accumulate(kind: Kind, x: __m256, y: __m256, acc: __m256) -> __m256 { + if kind == Kind::Bf16 { _mm256_add_ps(_mm256_mul_ps(x, y), acc) } else { _mm256_fmadd_ps(x, y, acc) } +} +/// The F32 dot of the vector sum plus the scalar elements `np..n`, accumulated in f32. +/// +/// # Safety +/// AVX2; `row` holds `n` f32 values and `f` has `n` elements. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn float_tail_f32(row: &[u8], f: &[f32], sum: __m256, np: usize, n: usize) -> f32 { + unsafe { + let mut s = hsum_original(sum); + for i in np..n { + s += f32::from_le_bytes(row[i * 4..i * 4 + 4].try_into().unwrap()) * f[i]; + } + s + } +} +/// The F16 / BF16 dot of the vector sum plus the scalar elements `np..n`, accumulated in f64. +/// +/// # Safety +/// AVX2+F16C; `row` holds `n` 16-bit values of `kind` and `h` has `n` elements. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn float_tail_half(kind: Kind, row: &[u8], h: &[u16], sum: __m256, np: usize, n: usize) -> f32 { + unsafe { + let mut s = if kind == Kind::Bf16 { hsum_ggml(sum) } else { hsum_original(sum) } as f64; + for i in np..n { + let a = u16::from_le_bytes([row[i * 2], row[i * 2 + 1]]); + let (a, b) = if kind == Kind::Bf16 { + (f32::from_bits((a as u32) << 16), f32::from_bits((h[i] as u32) << 16)) + } else { + (half(a), half(h[i])) + }; + s += (a * b) as f64; + } + s as f32 + } +} // SAFETY (the two `unsafe{half(..)}` below): private; reached only from dot()/dot_raw() after avx2_ok() proved F16C. pub(super) fn q2_generic(row: &[u8], y: &[Q8Zero]) -> f32 { let mut total = 0.0; @@ -190,25 +288,55 @@ pub(super) unsafe fn q1_dot(row: &[u8], y: &[Q8Zero]) -> f32 { unsafe { let mut acc = _mm256_setzero_ps(); for (ib, x) in row.chunks_exact(18).enumerate() { - let mut block = _mm256_setzero_ps(); - for k in 0..4 { - let mut signs = [0i8; 32]; - for j in 0..32 { - signs[j] = if x[2 + k * 4 + j / 8] & (1 << (j % 8)) == 0 { -1 } else { 0 }; - } - let mask = _mm256_loadu_si256(signs.as_ptr().cast()); - let q = _mm256_loadu_si256(y[ib * 4 + k].qs.as_ptr().cast()); - let sy = _mm256_sub_epi8(_mm256_xor_si256(q, mask), mask); - let p = _mm256_madd_epi16(_mm256_maddubs_epi16(_mm256_set1_epi8(1), sy), _mm256_set1_epi16(1)); - let d = _mm256_set1_ps(half(y[ib * 4 + k].d)); - block = if k == 0 { - _mm256_mul_ps(d, _mm256_cvtepi32_ps(p)) - } else { - _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(p), block) - }; - } + let block = q1_block_sum(x, y, ib); acc = _mm256_fmadd_ps(_mm256_set1_ps(half(u16::from_le_bytes([x[0], x[1]]))), block, acc); } hsum_ggml(acc) } } +/// The scaled integer products of one 128-element block `x` with its four activation blocks `y[ib * 4..ib * 4 + 4]`. +/// +/// # Safety +/// AVX2+FMA+F16C; `x` holds 18 bytes and `y` has the four blocks of block `ib`. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn q1_block_sum(x: &[u8], y: &[Q8Zero], ib: usize) -> __m256 { + unsafe { + let mut block = _mm256_setzero_ps(); + for k in 0..4 { + block = q1_accumulate(block, x, &y[ib * 4 + k], k); + } + block + } +} +/// Adds sub-block `k` of `x` times the activation block `yk` to `block`: a plain product for `k == 0`, else fused. +/// +/// # Safety +/// AVX2+FMA+F16C; `x` holds 18 bytes and `k < 4`. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn q1_accumulate(block: __m256, x: &[u8], yk: &Q8Zero, k: usize) -> __m256 { + unsafe { + let mask = q1_sign_mask(x, k); + let q = _mm256_loadu_si256(yk.qs.as_ptr().cast()); + let sy = _mm256_sub_epi8(_mm256_xor_si256(q, mask), mask); + let p = _mm256_madd_epi16(_mm256_maddubs_epi16(_mm256_set1_epi8(1), sy), _mm256_set1_epi16(1)); + let d = _mm256_set1_ps(half(yk.d)); + if k == 0 { _mm256_mul_ps(d, _mm256_cvtepi32_ps(p)) } else { _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(p), block) } + } +} +/// The 32 sign bytes of sub-block `k` (-1 for a clear bit, 0 for a set one) as one vector. +/// +/// # Safety +/// AVX2; `x` holds 18 bytes and `k < 4`. +#[inline] +#[target_feature(enable = "avx2,fma,f16c")] +unsafe fn q1_sign_mask(x: &[u8], k: usize) -> __m256i { + unsafe { + let mut signs = [0i8; 32]; + for j in 0..32 { + signs[j] = if x[2 + k * 4 + j / 8] & (1 << (j % 8)) == 0 { -1 } else { 0 }; + } + _mm256_loadu_si256(signs.as_ptr().cast()) + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml/kind_table.rs b/crates/native-cpu-expert/src/rust_ggml/kind_table.rs new file mode 100644 index 00000000..8b13ebdc --- /dev/null +++ b/crates/native-cpu-expert/src/rust_ggml/kind_table.rs @@ -0,0 +1,66 @@ +//! The GGML type table of `Kind`: Original type id and `(elements, bytes)` per block, one row per variant. +use super::Kind; + +/// One row per `Kind` variant, in declaration order. +pub(super) struct KindInfo { + pub(super) kind: Kind, + /// The Original (ggml) type id. + pub(super) id: i32, + /// Elements per block. + pub(super) block_elems: usize, + /// Bytes per block. + pub(super) block_bytes: usize, +} + +const fn row(kind: Kind, id: i32, block_elems: usize, block_bytes: usize) -> KindInfo { + KindInfo { kind, id, block_elems, block_bytes } +} + +pub(super) const KIND_COUNT: usize = 28; + +pub(super) static KIND_TABLE: [KindInfo; KIND_COUNT] = [ + row(Kind::F32, 0, 1, 4), + row(Kind::F16, 1, 1, 2), + row(Kind::Q4Zero, 2, 32, 18), + row(Kind::Q4One, 3, 32, 20), + row(Kind::Q5Zero, 6, 32, 22), + row(Kind::Q5One, 7, 32, 24), + row(Kind::Q8Zero, 8, 32, 34), + row(Kind::Q2K, 10, 256, 84), + row(Kind::Q3K, 11, 256, 110), + row(Kind::Q4K, 12, 256, 144), + row(Kind::Q5K, 13, 256, 176), + row(Kind::Q6K, 14, 256, 210), + row(Kind::Iq2Xxs, 16, 256, 66), + row(Kind::Iq2Xs, 17, 256, 74), + row(Kind::Iq3Xxs, 18, 256, 98), + row(Kind::Iq1S, 19, 256, 50), + row(Kind::Iq4Nl, 20, 32, 18), + row(Kind::Iq3S, 21, 256, 110), + row(Kind::Iq2S, 22, 256, 82), + row(Kind::Iq4Xs, 23, 256, 136), + row(Kind::Iq1M, 29, 256, 56), + row(Kind::Bf16, 30, 1, 2), + row(Kind::Tq1, 34, 256, 54), + row(Kind::Tq2, 35, 256, 66), + row(Kind::MxFp4, 39, 32, 17), + row(Kind::NvFp4, 40, 64, 36), + row(Kind::Q1Zero, 41, 128, 18), + row(Kind::Q2Zero, 42, 64, 18), +]; + +// `Kind::info` indexes the table by discriminant: every row must sit at its variant's discriminant. +const _: () = { + let mut i = 0; + while i < KIND_COUNT { + assert!(KIND_TABLE[i].kind as usize == i); + i += 1; + } +}; + +impl Kind { + /// The table row of this variant. + pub(super) fn info(self) -> &'static KindInfo { + &KIND_TABLE[self as usize] + } +} diff --git a/crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs b/crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs index 2bd6c39b..dc37bf8f 100644 --- a/crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs +++ b/crates/native-cpu-expert/src/rust_ggml/quantize_raw_fn.rs @@ -5,38 +5,16 @@ use super::*; // Callers own initialized aligned banks and admit geometry before this private leaf. /// # Safety -/// The CPU gate (avx2_ok()). `dst` extent and alignment are asserted here: it must hold `activation_bytes(x.len())` bytes and be -/// aligned for the element it is reinterpreted as (2 for u16/Q8Zero/Q8One, 4 for Q8K). Callers: NativeActivation (bytes at -/// offset 0 of a repr(C, align(64)) struct) and Split.hq rows (offset pinned by the const assert in rust_general_pool). +/// The CPU gate (avx2_ok()). `dst` extent and alignment are asserted here: it must hold `activation_bytes(x.len())` +/// bytes and be aligned for the element it is reinterpreted as (2 for u16/Q8Zero/Q8One, 4 for Q8K). Callers: +/// NativeActivation (bytes at offset 0 of a repr(C, align(64)) struct) and Split.hq rows (offset pinned by the const +/// assert in rust_general_pool). pub(in super::super) unsafe fn quantize_raw(kind: Kind, x: &[f32], dst: &mut [u8]) { unsafe { - let need = kind.activation_bytes(x.len()).expect("admitted activation geometry"); - let align = match kind.act() { - ActKind::F32 => 1, - ActKind::K => std::mem::align_of::(), - _ => std::mem::align_of::(), - }; - assert!(dst.len() >= need && dst.as_ptr().align_offset(align) == 0); + assert_destination(kind, x.len(), dst); match kind.act() { ActKind::F32 => std::ptr::copy_nonoverlapping(x.as_ptr().cast::(), dst.as_mut_ptr(), x.len() * 4), - ActKind::F16 | ActKind::Bf16 => { - let v = std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(), x.len()); - if kind.act() == ActKind::Bf16 && super::super::rust_ggml_native::convert_bf16(x, v) { - return; - } - for (&x, v) in x.iter().zip(v) { - *v = if kind.act() == ActKind::F16 { - to_half(x) - } else { - let b = x.to_bits(); - if b & 0x7fffffff > 0x7f800000 { - ((b >> 16) | 64) as u16 - } else { - (b.wrapping_add(0x7fff + ((b >> 16) & 1)) >> 16) as u16 - } - }; - } - } + ActKind::F16 | ActKind::Bf16 => write_half(kind.act(), x, dst), ActKind::Zero => super::super::rust_quant::q8_zero( x, std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(), x.len() / 32), @@ -52,11 +30,40 @@ pub(in super::super) unsafe fn quantize_raw(kind: Kind, x: &[f32], dst: &mut [u8 } } } +// Refuses (panics) a destination shorter than the encoded activation of `n` inputs or misaligned for its element type. +fn assert_destination(kind: Kind, n: usize, dst: &[u8]) { + let need = kind.activation_bytes(n).expect("admitted activation geometry"); + let align = match kind.act() { + ActKind::F32 => 1, + ActKind::K => std::mem::align_of::(), + _ => std::mem::align_of::(), + }; + assert!(dst.len() >= need && dst.as_ptr().align_offset(align) == 0); +} +/// Writes `x` into `dst` as 16-bit values: F16 (`act` is `F16`) or BF16 (`act` is `Bf16`). +/// /// # Safety -/// The CPU gate (avx2_ok()). `raw` must hold the encoded activation of `n` elements of `kind.act()` (>= activation_bytes(n)), -/// aligned for its element type, and `row` must be a whole weight row (>= row_bytes(n)). Every caller derives both from a -/// NativeActivation (quantize() enforces bytes <= BYTES; check() pins n) and a NativeFormat::validate()d row slice; the -/// 4096/1024-byte caps of NativeFormat::new keep the pool's `hq` rows (1024 B) large enough for Zero/One encodings. +/// The CPU gate (avx2_ok()); `dst` holds `x.len()` 16-bit elements and is 2-byte aligned (assert_destination()). +unsafe fn write_half(act: ActKind, x: &[f32], dst: &mut [u8]) { + unsafe { + let v = std::slice::from_raw_parts_mut(dst.as_mut_ptr().cast::(), x.len()); + if act == ActKind::Bf16 { + if !super::super::rust_ggml_native::convert_bf16(x, v) { + round_bf16_scalar(x, v); + } + } else { + for (&x, v) in x.iter().zip(v) { + *v = to_half(x); + } + } + } +} +/// # Safety +/// The CPU gate (avx2_ok()). `raw` must hold the encoded activation of `n` elements of `kind.act()` (>= +/// activation_bytes(n)), aligned for its element type, and `row` must be a whole weight row (>= row_bytes(n)). Every +/// caller derives both from a NativeActivation (quantize() enforces bytes <= BYTES; check() pins n) and a +/// NativeFormat::validate()d row slice; the 4096/1024-byte caps of NativeFormat::new keep the pool's `hq` rows +/// (1024 B) large enough for Zero/One encodings. pub(in super::super) unsafe fn dot_raw(kind: Kind, row: &[u8], n: usize, raw: &[u8]) -> f32 { unsafe { debug_assert!( @@ -75,48 +82,11 @@ pub(in super::super) unsafe fn dot_raw(kind: Kind, row: &[u8], n: usize, raw: &[ ), ActKind::Zero => { let y = std::slice::from_raw_parts(raw.as_ptr().cast::(), n / 32); - match kind { - Kind::Q2Zero => q2_generic(row, y), - Kind::Q1Zero => q1_dot(row, y), - Kind::MxFp4 => super::super::rust_ggml_extra::mxfp4(row, y), - Kind::NvFp4 => super::super::rust_ggml_extra::nvfp4(row, y), - Kind::Iq4Nl => { - let paired = y.len() / 2 * 2; - let mut out = [0.0]; - super::super::rust_iq::iq4nl(&row[..paired * 18], &[&y[..paired]], &mut out, true); - if paired < y.len() { - let b = &row[paired * 18..]; - let yy = y[paired]; - let mut a = 0i32; - let mut c = 0i32; - for j in 0..16 { - a += yy.qs[j] as i32 - * super::super::rust_codebooks::KVALUES_IQ4NL[(b[2 + j] & 15) as usize] as i32; - c += yy.qs[j + 16] as i32 - * super::super::rust_codebooks::KVALUES_IQ4NL[(b[2 + j] >> 4) as usize] as i32; - } - out[0] += (half(yy.d) * half(u16::from_le_bytes([b[0], b[1]]))) * (a + c) as f32; - } - out[0] - } - _ => super::super::rust_kq::small_dot(kind.original_id(), row, Some(y), None), - } + dot_zero_blocks(kind, row, y).expect("a Zero-encoded kind") } ActKind::K => { let y = std::slice::from_raw_parts(raw.as_ptr().cast::(), n / 256); - match kind { - Kind::Iq1S | Kind::Iq1M => super::super::rust_ggml_extra::iq1(kind.original_id(), row, y), - Kind::Tq1 | Kind::Tq2 => super::super::rust_ggml_extra::ternary(kind.original_id(), row, y), - Kind::Q4K => { - let mut out = [0.0]; - super::super::rust_kq::q4_k_dot(row, &[y], &mut out); - out[0] - } - Kind::Q2K | Kind::Q3K | Kind::Q5K | Kind::Q6K => { - super::super::rust_k_blocks::dot(kind.original_id(), row, y) - } - _ => super::super::rust_iq::dot_single(kind.original_id(), row, y), - } + dot_k_blocks(kind, row, y).expect("a K-encoded kind") } } }