Files
leleka/crates/native-cpu-expert/src/rust_dequant/plain.rs
T

80 lines
2.7 KiB
Rust

//! Moved out of the parent module by STRA-338: the legacy, 4/5/8-bit and FP4 block formats.
use super::{FP4, e8_half, h, u16at, u32at, ue4};
use crate::rust_ggml::Kind;
pub(super) fn block(kind: Kind, x: &[u8], y: &mut [f32]) {
match kind {
Kind::F32 => y[0] = f32::from_le_bytes(x.try_into().unwrap()),
Kind::F16 => y[0] = h(x, 0),
Kind::Bf16 => y[0] = f32::from_bits((u16at(x, 0) as u32) << 16),
Kind::Q1Zero => q1_zero(x, y),
Kind::Q2Zero => q2_zero(x, y),
Kind::Q4Zero | Kind::Q4One | Kind::Q5Zero | Kind::Q5One | Kind::Q8Zero => q458(kind, x, y),
Kind::MxFp4 => mxfp4(x, y),
Kind::NvFp4 => nvfp4(x, y),
_ => unreachable!(),
}
}
fn q1_zero(x: &[u8], y: &mut [f32]) {
let d = h(x, 0);
let negative = -d;
for j in 0..128 {
y[j] = if x[2 + j / 8] & (1 << (j % 8)) != 0 { d } else { negative };
}
}
fn q2_zero(x: &[u8], y: &mut [f32]) {
let d = h(x, 0);
for j in 0..64 {
y[j] = (((x[2 + j / 4] >> (2 * (j % 4))) & 3) as i32 - 1) as f32 * d;
}
}
fn q458(kind: Kind, x: &[u8], y: &mut [f32]) {
let d = h(x, 0);
if kind == Kind::Q8Zero {
for j in 0..32 {
y[j] = x[j + 2] as i8 as f32 * d;
}
} else {
q45(kind, d, x, y);
}
}
fn q45(kind: Kind, d: f32, x: &[u8], y: &mut [f32]) {
let min = if matches!(kind, Kind::Q4One | Kind::Q5One) { h(x, 2) } else { 0.0 };
let head = match kind {
Kind::Q4Zero => 2,
Kind::Q4One => 4,
Kind::Q5Zero => 6,
_ => 8,
};
let high = if matches!(kind, Kind::Q5Zero | Kind::Q5One) { u32at(x, head - 4) } else { 0 };
for j in 0..16 {
let low = x[head + j];
let a = (low & 15) as i32 | ((((high >> j) & 1) as i32) << 4);
let c = (low >> 4) as i32 | ((((high >> (j + 16)) & 1) as i32) << 4);
if matches!(kind, Kind::Q4One | Kind::Q5One) {
y[j] = a as f32 * d + min;
y[j + 16] = c as f32 * d + min;
} else {
let center = if kind == Kind::Q4Zero { 8 } else { 16 };
y[j] = (a - center) as f32 * d;
y[j + 16] = (c - center) as f32 * d;
}
}
}
fn mxfp4(x: &[u8], y: &mut [f32]) {
let d = e8_half(x[0]);
for j in 0..16 {
y[j] = FP4[(x[1 + j] & 15) as usize] as f32 * d;
y[j + 16] = FP4[(x[1 + j] >> 4) as usize] as f32 * d;
}
}
fn nvfp4(x: &[u8], y: &mut [f32]) {
for k in 0..4 {
let d = ue4(x[k]);
for j in 0..8 {
let v = x[4 + k / 2 * 16 + j + k % 2 * 8];
y[k * 16 + j] = FP4[(v & 15) as usize] as f32 * d;
y[k * 16 + j + 8] = FP4[(v >> 4) as usize] as f32 * d;
}
}
}