STRA-338 params p02: native-cpu-expert, cpu-sys, cpu-kernels, cpu-worker, obs down to 5 parameters
This commit is contained in:
@@ -28,10 +28,12 @@ fn record_of(ctx: &ReqCtx) -> Record {
|
||||
fn line(record: &Record) -> String {
|
||||
leleka_obs::format_line(
|
||||
&JSON,
|
||||
1_793_613_072_345,
|
||||
Level::Info,
|
||||
"api",
|
||||
"request",
|
||||
leleka_obs::EventHead {
|
||||
ts_ms: 1_793_613_072_345,
|
||||
level: Level::Info,
|
||||
comp: "api",
|
||||
ev: "request",
|
||||
},
|
||||
&record.fields(),
|
||||
0,
|
||||
)
|
||||
|
||||
@@ -10,14 +10,28 @@ pub(super) type IsumsMx = fn(&[u8], &[u8], &mut [i32]) -> Result<(), KernelError
|
||||
pub(super) type QuantQ8 = fn(&[f32], &mut [u8]) -> Result<(), KernelError>;
|
||||
pub(super) type DotMxR = fn(&[u8], &[f32], &[i8]) -> Result<f32, KernelError>;
|
||||
pub(super) type DotMulti = fn(&[u8], &[Q8rRef], &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type AttnScores = fn(&[f32], usize, &[u16], usize, usize, f32, &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type AttnSum = fn(&[f32], usize, usize, &[u16], usize, &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type AttnScores = fn(&[f32], &[u16], ScoreSpec, &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type AttnSum = fn(&[f32], &[u16], AttnShape, &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type ToHalf = fn(&[f32], &mut [u16]) -> Result<(), KernelError>;
|
||||
pub(super) type FromHalf = fn(&[u16], &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type RowsDot = fn(&[f32], &[f32], usize, usize, &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type Swiglu = fn(&[f32], &[f32], f32, f32, &mut [f32]) -> Result<(), KernelError>;
|
||||
pub(super) type ExpSum = fn(&mut [f32], f32) -> Result<f32, KernelError>;
|
||||
|
||||
/// The layout of a `rows_dot` call: `n` rows that lie `stride` floats apart.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct RowsShape {
|
||||
pub stride: usize,
|
||||
pub n: usize,
|
||||
}
|
||||
|
||||
/// The two constants of the gpt-oss expert activation.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SwigluOaiParams {
|
||||
pub alpha: f32,
|
||||
pub limit: f32,
|
||||
}
|
||||
|
||||
/// A resolved set of kernels for one level. Cheap to copy; resolve once at startup.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct Dispatch {
|
||||
@@ -86,7 +100,10 @@ impl Dispatch {
|
||||
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_scalar,
|
||||
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_scalar,
|
||||
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_scalar,
|
||||
rows_dot: |q, rows, stride, n, out| leleka_cpu_sys::attn_scores_scalar(q, 1, rows, stride, n, 1.0, out),
|
||||
rows_dot: |q, rows, stride, n, out| {
|
||||
let shape = AttnShape { heads: 1, n, stride };
|
||||
leleka_cpu_sys::attn_scores_scalar(q, rows, ScoreSpec { shape, scale: 1.0 }, out)
|
||||
},
|
||||
swiglu_oai: leleka_cpu_sys::swiglu_oai_scalar,
|
||||
exp_shift_sum: leleka_cpu_sys::exp_shift_sum_scalar,
|
||||
}
|
||||
@@ -110,7 +127,10 @@ impl Dispatch {
|
||||
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
|
||||
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2,
|
||||
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_avx2,
|
||||
rows_dot: |q, rows, stride, n, out| leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out),
|
||||
rows_dot: |q, rows, stride, n, out| {
|
||||
let shape = AttnShape { heads: 1, n, stride };
|
||||
leleka_cpu_sys::attn_scores_avx2(q, rows, ScoreSpec { shape, scale: 1.0 }, out)
|
||||
},
|
||||
swiglu_oai: leleka_cpu_sys::swiglu_oai_avx2,
|
||||
exp_shift_sum: leleka_cpu_sys::exp_shift_sum_avx2,
|
||||
}
|
||||
@@ -136,7 +156,10 @@ impl Dispatch {
|
||||
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
|
||||
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2,
|
||||
f16_to_f32: leleka_cpu_sys::f16_to_f32_slice_avx2,
|
||||
rows_dot: |q, rows, stride, n, out| leleka_cpu_sys::attn_scores_avx2(q, 1, rows, stride, n, 1.0, out),
|
||||
rows_dot: |q, rows, stride, n, out| {
|
||||
let shape = AttnShape { heads: 1, n, stride };
|
||||
leleka_cpu_sys::attn_scores_avx2(q, rows, ScoreSpec { shape, scale: 1.0 }, out)
|
||||
},
|
||||
swiglu_oai: leleka_cpu_sys::swiglu_oai_avx2,
|
||||
exp_shift_sum: leleka_cpu_sys::exp_shift_sum_avx2,
|
||||
}
|
||||
@@ -219,19 +242,8 @@ impl Dispatch {
|
||||
/// Attention scores for a group of `heads` query heads sharing the keys (stored as half floats):
|
||||
/// `out[g * n + i] = scale * dot(q[g * hd ..][..hd], keys[i * stride ..][..hd])`, `hd = q.len() / heads`.
|
||||
/// SIMD levels differ from the portable one only in float summation order.
|
||||
// The argument list mirrors the kernel's, which is what its callers and tests read against.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn attn_scores(
|
||||
&self,
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[u16],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
(self.attn_scores)(q, heads, keys, stride, n, scale, out)
|
||||
pub fn attn_scores(&self, q: &[f32], keys: &[u16], spec: ScoreSpec, out: &mut [f32]) -> Result<(), KernelError> {
|
||||
(self.attn_scores)(q, keys, spec, out)
|
||||
}
|
||||
|
||||
/// Weighted value sums for a group of heads:
|
||||
@@ -239,25 +251,16 @@ impl Dispatch {
|
||||
pub fn attn_weighted_sum(
|
||||
&self,
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[u16],
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
(self.attn_weighted_sum)(weights, heads, n, values, stride, out)
|
||||
(self.attn_weighted_sum)(weights, values, shape, out)
|
||||
}
|
||||
|
||||
/// `out[i] = dot(q, rows[i * stride ..][..q.len()])` for `i < n` in single precision (the router).
|
||||
pub fn rows_dot(
|
||||
&self,
|
||||
q: &[f32],
|
||||
rows: &[f32],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
(self.rows_dot)(q, rows, stride, n, out)
|
||||
pub fn rows_dot(&self, q: &[f32], rows: &[f32], shape: RowsShape, out: &mut [f32]) -> Result<(), KernelError> {
|
||||
(self.rows_dot)(q, rows, shape.stride, shape.n, out)
|
||||
}
|
||||
|
||||
/// The gpt-oss expert activation for `gate` and `up` (equal lengths) into `out`.
|
||||
@@ -265,11 +268,10 @@ impl Dispatch {
|
||||
&self,
|
||||
gate: &[f32],
|
||||
up: &[f32],
|
||||
alpha: f32,
|
||||
limit: f32,
|
||||
params: SwigluOaiParams,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
(self.swiglu_oai)(gate, up, alpha, limit, out)
|
||||
(self.swiglu_oai)(gate, up, params.alpha, params.limit, out)
|
||||
}
|
||||
|
||||
/// Floats to half-precision bit patterns (round to nearest even); the slices must be equally long.
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use leleka_cpu_sys::{KernelError, MAX_DOT_LEN, MULTI_MAX, Q8rRef};
|
||||
pub use leleka_cpu_sys::{AttnShape, KernelError, MAX_DOT_LEN, MULTI_MAX, Q8rRef, ScoreSpec};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -15,4 +15,4 @@ mod tests;
|
||||
mod isa;
|
||||
pub use isa::{DispatchError, ISA_ENV, Isa};
|
||||
mod dispatch;
|
||||
pub use dispatch::Dispatch;
|
||||
pub use dispatch::{Dispatch, RowsShape, SwigluOaiParams};
|
||||
|
||||
@@ -6,33 +6,17 @@ use super::*;
|
||||
/// Attention scores for a group of `heads` query heads that share the keys:
|
||||
/// `out[g * n + i] = scale * dot(q[g * hd ..][..hd], keys[i * stride ..][..hd])` with
|
||||
/// `hd = q.len() / heads` (portable). `keys` must hold every position read.
|
||||
pub fn attn_scores_scalar(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[f32],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_scores(q, heads, keys.len(), stride, n, out)?;
|
||||
simd::attn_scores_scalar(q, heads, keys, stride, n, scale, out);
|
||||
pub fn attn_scores_scalar(q: &[f32], keys: &[f32], spec: ScoreSpec, out: &mut [f32]) -> Result<(), KernelError> {
|
||||
check_scores(q, keys.len(), spec.shape, out)?;
|
||||
simd::attn_scores_scalar(q, keys, spec, out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// AVX2 + FMA level of [`attn_scores_scalar`]; equal within float summation order.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn attn_scores_avx2(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[f32],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_scores(q, heads, keys.len(), stride, n, out)?;
|
||||
with_avx2!(simd::x86::attn_scores_avx2(q, heads, keys, stride, n, scale, out))
|
||||
pub fn attn_scores_avx2(q: &[f32], keys: &[f32], spec: ScoreSpec, out: &mut [f32]) -> Result<(), KernelError> {
|
||||
check_scores(q, keys.len(), spec.shape, out)?;
|
||||
with_avx2!(simd::x86::attn_scores_avx2(q, keys, spec, out))
|
||||
}
|
||||
|
||||
/// Weighted sums of the values for a group of heads:
|
||||
@@ -40,14 +24,12 @@ pub fn attn_scores_avx2(
|
||||
/// `hd = out.len() / heads` (portable).
|
||||
pub fn attn_weighted_sum_scalar(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[f32],
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
|
||||
simd::attn_weighted_sum_scalar(weights, heads, n, values, stride, out);
|
||||
check_weighted_sum(weights, values.len(), shape, out)?;
|
||||
simd::attn_weighted_sum_scalar(weights, values, shape, out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -55,59 +37,37 @@ pub fn attn_weighted_sum_scalar(
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn attn_weighted_sum_avx2(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[f32],
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
|
||||
with_avx2!(simd::x86::attn_weighted_sum_avx2(
|
||||
weights, heads, n, values, stride, out
|
||||
))
|
||||
check_weighted_sum(weights, values.len(), shape, out)?;
|
||||
with_avx2!(simd::x86::attn_weighted_sum_avx2(weights, values, shape, out))
|
||||
}
|
||||
|
||||
/// As [`attn_scores_scalar`] with the keys stored as IEEE half floats (bit patterns).
|
||||
pub fn attn_scores_f16_scalar(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[u16],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_scores(q, heads, keys.len(), stride, n, out)?;
|
||||
simd::attn_scores_f16_scalar(q, heads, keys, stride, n, scale, out);
|
||||
pub fn attn_scores_f16_scalar(q: &[f32], keys: &[u16], spec: ScoreSpec, out: &mut [f32]) -> Result<(), KernelError> {
|
||||
check_scores(q, keys.len(), spec.shape, out)?;
|
||||
simd::attn_scores_f16_scalar(q, keys, spec, out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// AVX2 + FMA + F16C level of [`attn_scores_f16_scalar`]; equal within float summation order.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn attn_scores_f16_avx2(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[u16],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_scores(q, heads, keys.len(), stride, n, out)?;
|
||||
with_avx2!(simd::x86::attn_scores_f16_avx2(q, heads, keys, stride, n, scale, out))
|
||||
pub fn attn_scores_f16_avx2(q: &[f32], keys: &[u16], spec: ScoreSpec, out: &mut [f32]) -> Result<(), KernelError> {
|
||||
check_scores(q, keys.len(), spec.shape, out)?;
|
||||
with_avx2!(simd::x86::attn_scores_f16_avx2(q, keys, spec, out))
|
||||
}
|
||||
|
||||
/// As [`attn_weighted_sum_scalar`] with the values stored as IEEE half floats.
|
||||
pub fn attn_weighted_sum_f16_scalar(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[u16],
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
|
||||
simd::attn_weighted_sum_f16_scalar(weights, heads, n, values, stride, out);
|
||||
check_weighted_sum(weights, values.len(), shape, out)?;
|
||||
simd::attn_weighted_sum_f16_scalar(weights, values, shape, out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -115,16 +75,12 @@ pub fn attn_weighted_sum_f16_scalar(
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn attn_weighted_sum_f16_avx2(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[u16],
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_weighted_sum(weights, heads, n, values.len(), stride, out)?;
|
||||
with_avx2!(simd::x86::attn_weighted_sum_f16_avx2(
|
||||
weights, heads, n, values, stride, out
|
||||
))
|
||||
check_weighted_sum(weights, values.len(), shape, out)?;
|
||||
with_avx2!(simd::x86::attn_weighted_sum_f16_avx2(weights, values, shape, out))
|
||||
}
|
||||
|
||||
/// The gpt-oss expert activation, element by element (portable):
|
||||
|
||||
@@ -99,12 +99,11 @@ pub(super) fn check_strided(count: usize, stride: usize, width: usize, data_len:
|
||||
/// Checks the shapes of a group of `heads` query heads (`q.len() = heads * hd`) over `n` positions.
|
||||
pub(super) fn check_scores(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys_len: usize,
|
||||
stride: usize,
|
||||
n: usize,
|
||||
shape: AttnShape,
|
||||
out: &[f32],
|
||||
) -> Result<(), KernelError> {
|
||||
let AttnShape { heads, n, stride } = shape;
|
||||
if heads == 0 || q.is_empty() || !q.len().is_multiple_of(heads) {
|
||||
return Err(KernelError::LengthMismatch);
|
||||
}
|
||||
@@ -117,12 +116,11 @@ pub(super) fn check_scores(
|
||||
|
||||
pub(super) fn check_weighted_sum(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values_len: usize,
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &[f32],
|
||||
) -> Result<(), KernelError> {
|
||||
let AttnShape { heads, n, stride } = shape;
|
||||
if heads == 0 || out.is_empty() || !out.len().is_multiple_of(heads) {
|
||||
return Err(KernelError::LengthMismatch);
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ pub mod mapping;
|
||||
pub mod simd;
|
||||
pub mod topology;
|
||||
|
||||
pub use simd::{MULTI_MAX, Q8rRef};
|
||||
pub use simd::{AttnShape, MULTI_MAX, Q8rRef, ScoreSpec};
|
||||
|
||||
/// Longest vector the int32 accumulators can hold exactly (`131072 * 128 * 127 < 2^31`).
|
||||
pub const MAX_DOT_LEN: usize = 131_072;
|
||||
|
||||
@@ -27,6 +27,22 @@ pub const Q8_0_BYTES: usize = 34;
|
||||
// They work on a group of `heads` query heads that share the same keys and values (grouped-query
|
||||
// attention), so each key and value row is read once for the whole group.
|
||||
|
||||
/// The shape of an attention call: `heads` query heads that share the keys (or values), over `n` positions that
|
||||
/// lie `stride` elements apart.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct AttnShape {
|
||||
pub heads: usize,
|
||||
pub n: usize,
|
||||
pub stride: usize,
|
||||
}
|
||||
|
||||
/// An attention score call: the [`AttnShape`] and the factor applied to every dot product.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct ScoreSpec {
|
||||
pub shape: AttnShape,
|
||||
pub scale: f32,
|
||||
}
|
||||
|
||||
/// Positions handled per block: the rows of a block stay in the L1 cache while every head uses them.
|
||||
pub const ATTN_BLOCK: usize = 16;
|
||||
/// Bias that turns signed weights into unsigned ones for the VNNI tile kernels (`w + 128`).
|
||||
|
||||
@@ -135,7 +135,8 @@ pub fn dot_q8_q8r_scalar(x: &[u8], ys: &[f32], yq: &[i8]) -> f32 {
|
||||
|
||||
/// `out[g * n + i] = scale * dot(q[g * hd ..][..hd], keys[i * stride ..][..hd])` for each head `g` and
|
||||
/// position `i < n`, with `hd = q.len() / heads`.
|
||||
pub fn attn_scores_scalar(q: &[f32], heads: usize, keys: &[f32], stride: usize, n: usize, scale: f32, out: &mut [f32]) {
|
||||
pub fn attn_scores_scalar(q: &[f32], keys: &[f32], spec: ScoreSpec, out: &mut [f32]) {
|
||||
let ScoreSpec { shape: AttnShape { heads, n, stride }, scale } = spec;
|
||||
let hd = q.len() / heads;
|
||||
for g in 0..heads {
|
||||
let query = &q[g * hd..(g + 1) * hd];
|
||||
@@ -152,14 +153,8 @@ pub fn attn_scores_scalar(q: &[f32], heads: usize, keys: &[f32], stride: usize,
|
||||
|
||||
/// `out[g * hd ..][..hd] = sum_i weights[g * n + i] * values[i * stride ..][..hd]`, with
|
||||
/// `hd = out.len() / heads`.
|
||||
pub fn attn_weighted_sum_scalar(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[f32],
|
||||
stride: usize,
|
||||
out: &mut [f32],
|
||||
) {
|
||||
pub fn attn_weighted_sum_scalar(weights: &[f32], values: &[f32], shape: AttnShape, out: &mut [f32]) {
|
||||
let AttnShape { heads, n, stride } = shape;
|
||||
let hd = out.len() / heads;
|
||||
out.fill(0.0);
|
||||
for g in 0..heads {
|
||||
@@ -176,15 +171,8 @@ pub fn attn_weighted_sum_scalar(
|
||||
}
|
||||
|
||||
/// As [`attn_scores_scalar`] with the keys stored as IEEE half floats (bit patterns).
|
||||
pub fn attn_scores_f16_scalar(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[u16],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) {
|
||||
pub fn attn_scores_f16_scalar(q: &[f32], keys: &[u16], spec: ScoreSpec, out: &mut [f32]) {
|
||||
let ScoreSpec { shape: AttnShape { heads, n, stride }, scale } = spec;
|
||||
let hd = q.len() / heads;
|
||||
for g in 0..heads {
|
||||
let query = &q[g * hd..(g + 1) * hd];
|
||||
@@ -200,14 +188,8 @@ pub fn attn_scores_f16_scalar(
|
||||
}
|
||||
|
||||
/// As [`attn_weighted_sum_scalar`] with the values stored as IEEE half floats.
|
||||
pub fn attn_weighted_sum_f16_scalar(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[u16],
|
||||
stride: usize,
|
||||
out: &mut [f32],
|
||||
) {
|
||||
pub fn attn_weighted_sum_f16_scalar(weights: &[f32], values: &[u16], shape: AttnShape, out: &mut [f32]) {
|
||||
let AttnShape { heads, n, stride } = shape;
|
||||
let hd = out.len() / heads;
|
||||
out.fill(0.0);
|
||||
for g in 0..heads {
|
||||
|
||||
@@ -33,7 +33,7 @@ use std::arch::x86_64::*;
|
||||
// block's accumulation from `-128 * sum(x)` in lane 0 (the activation's `corr`), and reads the
|
||||
// activation scale as a ready-made vector. Both give exact integer block sums.
|
||||
|
||||
use super::ActRef;
|
||||
use super::{ActRef, AttnShape, ScoreSpec};
|
||||
|
||||
/// Expands to a `match` over the tile shapes `1..=4` rows by `1..=4` activations.
|
||||
macro_rules! tile_shapes {
|
||||
|
||||
@@ -35,15 +35,11 @@ pub(super) unsafe fn attn_dot(q: *const f32, k: *const f32, hd: usize) -> f32 {
|
||||
}
|
||||
|
||||
#[target_feature(enable = "avx2,fma")]
|
||||
pub unsafe fn attn_scores_avx2(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[f32],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) {
|
||||
pub unsafe fn attn_scores_avx2(q: &[f32], keys: &[f32], spec: ScoreSpec, out: &mut [f32]) {
|
||||
let ScoreSpec {
|
||||
shape: AttnShape { heads, n, stride },
|
||||
scale,
|
||||
} = spec;
|
||||
let hd = q.len() / heads;
|
||||
let mut first = 0;
|
||||
while first < n {
|
||||
@@ -131,12 +127,11 @@ unsafe fn weighted_sum_column_chunk(
|
||||
#[target_feature(enable = "avx2,fma")]
|
||||
pub unsafe fn attn_weighted_sum_avx2(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[f32],
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &mut [f32],
|
||||
) {
|
||||
let AttnShape { heads, n, stride } = shape;
|
||||
let hd = out.len() / heads;
|
||||
out.fill(0.0);
|
||||
let ws = WeightedSum {
|
||||
|
||||
@@ -4,15 +4,11 @@
|
||||
use super::*;
|
||||
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub unsafe fn attn_scores_f16_avx2(
|
||||
q: &[f32],
|
||||
heads: usize,
|
||||
keys: &[u16],
|
||||
stride: usize,
|
||||
n: usize,
|
||||
scale: f32,
|
||||
out: &mut [f32],
|
||||
) {
|
||||
pub unsafe fn attn_scores_f16_avx2(q: &[f32], keys: &[u16], spec: ScoreSpec, out: &mut [f32]) {
|
||||
let ScoreSpec {
|
||||
shape: AttnShape { heads, n, stride },
|
||||
scale,
|
||||
} = spec;
|
||||
let hd = q.len() / heads;
|
||||
let mut first = 0;
|
||||
while first < n {
|
||||
@@ -92,12 +88,11 @@ unsafe fn weighted_sum_f16_column_chunk(
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
pub unsafe fn attn_weighted_sum_f16_avx2(
|
||||
weights: &[f32],
|
||||
heads: usize,
|
||||
n: usize,
|
||||
values: &[u16],
|
||||
stride: usize,
|
||||
shape: AttnShape,
|
||||
out: &mut [f32],
|
||||
) {
|
||||
let AttnShape { heads, n, stride } = shape;
|
||||
let hd = out.len() / heads;
|
||||
out.fill(0.0);
|
||||
let ws = WeightedSum {
|
||||
|
||||
@@ -75,11 +75,13 @@ fn scores_match_an_f64_reference_for_groups_of_heads() {
|
||||
let q: Vec<f32> = (0..heads * hd).map(|_| rng.f32(2.0)).collect();
|
||||
let keys: Vec<f32> = (0..shape.extent()).map(|_| rng.f32(2.0)).collect();
|
||||
let mut out_s = vec![0f32; heads * n];
|
||||
sys::attn_scores_scalar(&q, heads, &keys, stride, n, 0.125, &mut out_s).unwrap();
|
||||
sys::attn_scores_scalar(&q, &keys, score_spec(heads, n, stride, 0.125), &mut out_s)
|
||||
.unwrap();
|
||||
let mut out_v = out_s.clone();
|
||||
if sys::avx2_available() {
|
||||
out_v.fill(f32::NAN);
|
||||
sys::attn_scores_avx2(&q, heads, &keys, stride, n, 0.125, &mut out_v).unwrap();
|
||||
sys::attn_scores_avx2(&q, &keys, score_spec(heads, n, stride, 0.125), &mut out_v)
|
||||
.unwrap();
|
||||
}
|
||||
check_scores(shape, &q, &keys, [&out_s, &out_v]);
|
||||
}
|
||||
@@ -116,11 +118,18 @@ fn weighted_sums_match_an_f64_reference_for_groups_of_heads() {
|
||||
let weights: Vec<f32> = (0..heads * n).map(|_| rng.f32(1.0).abs()).collect();
|
||||
let values: Vec<f32> = (0..shape.extent()).map(|_| rng.f32(3.0)).collect();
|
||||
let mut out_s = vec![7f32; heads * hd];
|
||||
sys::attn_weighted_sum_scalar(&weights, heads, n, &values, stride, &mut out_s).unwrap();
|
||||
sys::attn_weighted_sum_scalar(&weights, &values, attn_shape(heads, n, stride), &mut out_s)
|
||||
.unwrap();
|
||||
let mut out_v = out_s.clone();
|
||||
if sys::avx2_available() {
|
||||
out_v.fill(f32::NAN);
|
||||
sys::attn_weighted_sum_avx2(&weights, heads, n, &values, stride, &mut out_v).unwrap();
|
||||
sys::attn_weighted_sum_avx2(
|
||||
&weights,
|
||||
&values,
|
||||
attn_shape(heads, n, stride),
|
||||
&mut out_v,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
check_weighted_sums(shape, &weights, &values, [&out_s, &out_v]);
|
||||
}
|
||||
@@ -257,21 +266,21 @@ fn half_precision_kernels_refuse_short_buffers() {
|
||||
let keys = [0u16; 20];
|
||||
let mut out = [0.0f32; 6];
|
||||
assert_eq!(
|
||||
sys::attn_scores_f16_scalar(&q, 2, &keys, 8, 3, 1.0, &mut out),
|
||||
sys::attn_scores_f16_scalar(&q, &keys, score_spec(2, 3, 8, 1.0), &mut out),
|
||||
Err(sys::KernelError::LengthMismatch)
|
||||
);
|
||||
let mut o = [0.0f32; 16];
|
||||
assert_eq!(
|
||||
sys::attn_weighted_sum_f16_scalar(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
||||
sys::attn_weighted_sum_f16_scalar(&[1.0; 6], &keys[..10], attn_shape(2, 3, 8), &mut o),
|
||||
Err(sys::KernelError::LengthMismatch)
|
||||
);
|
||||
if sys::avx2_available() {
|
||||
assert_eq!(
|
||||
sys::attn_scores_f16_avx2(&q, 2, &keys, 8, 3, 1.0, &mut out),
|
||||
sys::attn_scores_f16_avx2(&q, &keys, score_spec(2, 3, 8, 1.0), &mut out),
|
||||
Err(sys::KernelError::LengthMismatch)
|
||||
);
|
||||
assert_eq!(
|
||||
sys::attn_weighted_sum_f16_avx2(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
||||
sys::attn_weighted_sum_f16_avx2(&[1.0; 6], &keys[..10], attn_shape(2, 3, 8), &mut o),
|
||||
Err(sys::KernelError::LengthMismatch)
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,17 @@
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn attn_shape(heads: usize, n: usize, stride: usize) -> sys::AttnShape {
|
||||
sys::AttnShape { heads, n, stride }
|
||||
}
|
||||
|
||||
pub(super) fn score_spec(heads: usize, n: usize, stride: usize, scale: f32) -> sys::ScoreSpec {
|
||||
sys::ScoreSpec {
|
||||
shape: attn_shape(heads, n, stride),
|
||||
scale,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn expect_mismatch(name: &str, result: Result<(), sys::KernelError>) {
|
||||
assert_eq!(result, Err(sys::KernelError::LengthMismatch), "{name}");
|
||||
}
|
||||
@@ -12,27 +23,27 @@ pub(super) fn refuse_score_shapes(q: &[f32; 16], keys: &[f32; 20]) {
|
||||
// three positions at stride 8 need 8 * 2 + 8 = 24 floats
|
||||
check(
|
||||
"keys too short",
|
||||
sys::attn_scores_scalar(q, 2, keys, 8, 3, 1.0, &mut out),
|
||||
sys::attn_scores_scalar(q, keys, score_spec(2, 3, 8, 1.0), &mut out),
|
||||
);
|
||||
check(
|
||||
"output too short",
|
||||
sys::attn_scores_scalar(q, 2, keys, 8, 2, 1.0, &mut out[..3]),
|
||||
sys::attn_scores_scalar(q, keys, score_spec(2, 2, 8, 1.0), &mut out[..3]),
|
||||
);
|
||||
check(
|
||||
"no heads",
|
||||
sys::attn_scores_scalar(q, 0, keys, 8, 2, 1.0, &mut out),
|
||||
sys::attn_scores_scalar(q, keys, score_spec(0, 2, 8, 1.0), &mut out),
|
||||
);
|
||||
check(
|
||||
"heads do not divide q",
|
||||
sys::attn_scores_scalar(q, 3, keys, 8, 2, 1.0, &mut out),
|
||||
sys::attn_scores_scalar(q, keys, score_spec(3, 2, 8, 1.0), &mut out),
|
||||
);
|
||||
check(
|
||||
"empty q",
|
||||
sys::attn_scores_scalar(&[], 1, keys, 8, 2, 1.0, &mut out),
|
||||
sys::attn_scores_scalar(&[], keys, score_spec(1, 2, 8, 1.0), &mut out),
|
||||
);
|
||||
check(
|
||||
"stride overflow",
|
||||
sys::attn_scores_scalar(q, 2, keys, usize::MAX, 3, 1.0, &mut out),
|
||||
sys::attn_scores_scalar(q, keys, score_spec(2, 3, usize::MAX, 1.0), &mut out),
|
||||
);
|
||||
refuse_avx2_score_shape(q, keys);
|
||||
}
|
||||
@@ -43,7 +54,7 @@ pub(super) fn refuse_avx2_score_shape(q: &[f32; 16], keys: &[f32; 20]) {
|
||||
if sys::avx2_available() {
|
||||
check(
|
||||
"avx2 keys too short",
|
||||
sys::attn_scores_avx2(q, 2, keys, 8, 3, 1.0, &mut out),
|
||||
sys::attn_scores_avx2(q, keys, score_spec(2, 3, 8, 1.0), &mut out),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -53,20 +64,20 @@ pub(super) fn refuse_weighted_sum_shapes(keys: &[f32; 20]) {
|
||||
let check = expect_mismatch;
|
||||
check(
|
||||
"weights too short",
|
||||
sys::attn_weighted_sum_scalar(&[1.0; 5], 2, 3, keys, 4, &mut o),
|
||||
sys::attn_weighted_sum_scalar(&[1.0; 5], keys, attn_shape(2, 3, 4), &mut o),
|
||||
);
|
||||
check(
|
||||
"values too short",
|
||||
sys::attn_weighted_sum_scalar(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
||||
sys::attn_weighted_sum_scalar(&[1.0; 6], &keys[..10], attn_shape(2, 3, 8), &mut o),
|
||||
);
|
||||
check(
|
||||
"no heads",
|
||||
sys::attn_weighted_sum_scalar(&[1.0; 6], 0, 3, keys, 4, &mut o),
|
||||
sys::attn_weighted_sum_scalar(&[1.0; 6], keys, attn_shape(0, 3, 4), &mut o),
|
||||
);
|
||||
if sys::avx2_available() {
|
||||
check(
|
||||
"avx2 values too short",
|
||||
sys::attn_weighted_sum_avx2(&[1.0; 6], 2, 3, &keys[..10], 8, &mut o),
|
||||
sys::attn_weighted_sum_avx2(&[1.0; 6], &keys[..10], attn_shape(2, 3, 8), &mut o),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -83,11 +94,23 @@ pub(super) fn to_half(values: &[f32]) -> (Vec<u16>, Vec<f32>) {
|
||||
pub(super) fn half_scores(shape: Shape, q: &[f32], keys16: &[u16]) -> [Vec<f32>; 2] {
|
||||
let (heads, _hd, stride, n) = shape.parts();
|
||||
let mut scores_s = vec![0f32; heads * n];
|
||||
sys::attn_scores_f16_scalar(q, heads, keys16, stride, n, 0.125, &mut scores_s).unwrap();
|
||||
sys::attn_scores_f16_scalar(
|
||||
q,
|
||||
keys16,
|
||||
score_spec(heads, n, stride, 0.125),
|
||||
&mut scores_s,
|
||||
)
|
||||
.unwrap();
|
||||
let mut scores_v = scores_s.clone();
|
||||
if sys::avx2_available() {
|
||||
scores_v.fill(f32::NAN);
|
||||
sys::attn_scores_f16_avx2(q, heads, keys16, stride, n, 0.125, &mut scores_v).unwrap();
|
||||
sys::attn_scores_f16_avx2(
|
||||
q,
|
||||
keys16,
|
||||
score_spec(heads, n, stride, 0.125),
|
||||
&mut scores_v,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
[scores_s, scores_v]
|
||||
}
|
||||
@@ -96,11 +119,18 @@ pub(super) fn half_scores(shape: Shape, q: &[f32], keys16: &[u16]) -> [Vec<f32>;
|
||||
pub(super) fn half_sums(shape: Shape, weights: &[f32], values16: &[u16]) -> [Vec<f32>; 2] {
|
||||
let (heads, hd, stride, n) = shape.parts();
|
||||
let mut sums_s = vec![0f32; heads * hd];
|
||||
sys::attn_weighted_sum_f16_scalar(weights, heads, n, values16, stride, &mut sums_s).unwrap();
|
||||
sys::attn_weighted_sum_f16_scalar(weights, values16, attn_shape(heads, n, stride), &mut sums_s)
|
||||
.unwrap();
|
||||
let mut sums_v = sums_s.clone();
|
||||
if sys::avx2_available() {
|
||||
sums_v.fill(f32::NAN);
|
||||
sys::attn_weighted_sum_f16_avx2(weights, heads, n, values16, stride, &mut sums_v).unwrap();
|
||||
sys::attn_weighted_sum_f16_avx2(
|
||||
weights,
|
||||
values16,
|
||||
attn_shape(heads, n, stride),
|
||||
&mut sums_v,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
[sums_s, sums_v]
|
||||
}
|
||||
|
||||
@@ -111,6 +111,13 @@ fn abs_prepared_acts(acts: &[sys::PreparedAct]) -> Vec<sys::PreparedAct> {
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The level under test, the portable reference it is compared with, and the name used in failure messages.
|
||||
struct TileKernels<'a> {
|
||||
kernel: TileFn,
|
||||
reference: TileFn,
|
||||
label: &'a str,
|
||||
}
|
||||
|
||||
/// What `check_level` compares for every tile shape.
|
||||
struct Level<'a> {
|
||||
blocks: usize,
|
||||
@@ -124,14 +131,12 @@ struct Level<'a> {
|
||||
}
|
||||
|
||||
/// Run `kernel` for every shape and compare with the 1x1 tile and the portable reference.
|
||||
fn check_level(
|
||||
d: &Data,
|
||||
rows: &[Vec<u8>],
|
||||
abs_row: fn(&[u8]) -> Vec<u8>,
|
||||
kernel: TileFn,
|
||||
reference: TileFn,
|
||||
label: &str,
|
||||
) {
|
||||
fn check_level(d: &Data, rows: &[Vec<u8>], abs_row: fn(&[u8]) -> Vec<u8>, kernels: TileKernels) {
|
||||
let TileKernels {
|
||||
kernel,
|
||||
reference,
|
||||
label,
|
||||
} = kernels;
|
||||
let abs_rows: Vec<Vec<u8>> = rows.iter().map(|r| abs_row(r)).collect();
|
||||
let abs_prepared = abs_prepared_acts(&d.acts);
|
||||
let abs_acts: Vec<sys::ActRef> = abs_prepared.iter().map(|a| a.view()).collect();
|
||||
@@ -285,17 +290,21 @@ fn check_avx2_levels(d: &Data) {
|
||||
d,
|
||||
&d.mx_rows,
|
||||
abs_mx,
|
||||
sys::mxfp4_q8r_tile_avx2,
|
||||
sys::mxfp4_q8r_tile_scalar,
|
||||
"mxfp4 avx2",
|
||||
TileKernels {
|
||||
kernel: sys::mxfp4_q8r_tile_avx2,
|
||||
reference: sys::mxfp4_q8r_tile_scalar,
|
||||
label: "mxfp4 avx2",
|
||||
},
|
||||
);
|
||||
check_level(
|
||||
d,
|
||||
&d.q8_rows,
|
||||
abs_q8,
|
||||
sys::q8_q8r_tile_avx2,
|
||||
sys::q8_q8r_tile_scalar,
|
||||
"q8 avx2",
|
||||
TileKernels {
|
||||
kernel: sys::q8_q8r_tile_avx2,
|
||||
reference: sys::q8_q8r_tile_scalar,
|
||||
label: "q8 avx2",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -305,16 +314,20 @@ fn check_avxvnni_levels(d: &Data) {
|
||||
d,
|
||||
&d.mx_rows,
|
||||
abs_mx,
|
||||
sys::mxfp4_q8r_tile_avxvnni,
|
||||
sys::mxfp4_q8r_tile_scalar,
|
||||
"mxfp4 vnni",
|
||||
TileKernels {
|
||||
kernel: sys::mxfp4_q8r_tile_avxvnni,
|
||||
reference: sys::mxfp4_q8r_tile_scalar,
|
||||
label: "mxfp4 vnni",
|
||||
},
|
||||
);
|
||||
check_level(
|
||||
d,
|
||||
&d.q8_rows,
|
||||
abs_q8,
|
||||
sys::q8_q8r_tile_avxvnni,
|
||||
sys::q8_q8r_tile_scalar,
|
||||
"q8 vnni",
|
||||
TileKernels {
|
||||
kernel: sys::q8_q8r_tile_avxvnni,
|
||||
reference: sys::q8_q8r_tile_scalar,
|
||||
label: "q8 vnni",
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
@@ -185,7 +185,7 @@ fn run_request<D: Decoder, W: Write>(
|
||||
) -> io::Result<()> {
|
||||
control.stop.store(false, Ordering::SeqCst);
|
||||
control.active.store(true, Ordering::SeqCst);
|
||||
let outcome = generate(decoder, request, stop_tokens, seed, control, output);
|
||||
let outcome = generate(decoder, request, (stop_tokens, seed), control, output);
|
||||
control.active.store(false, Ordering::SeqCst);
|
||||
match outcome {
|
||||
Ok(()) => Ok(()),
|
||||
@@ -216,8 +216,7 @@ fn write_line<W: Write>(output: &Mutex<W>, line: &str) -> io::Result<()> {
|
||||
fn generate<D: Decoder, W: Write>(
|
||||
decoder: &mut D,
|
||||
request: &Generate,
|
||||
stop_tokens: &[u32],
|
||||
seed: u64,
|
||||
(stop_tokens, seed): (&[u32], u64),
|
||||
control: &Control,
|
||||
output: &Mutex<W>,
|
||||
) -> Result<(), GenerationError> {
|
||||
|
||||
@@ -94,19 +94,10 @@ impl Log {
|
||||
fields: &[leleka_obs::Field<'_>],
|
||||
) {
|
||||
let now = leleka_obs::now_ms();
|
||||
let file_line =
|
||||
leleka_obs::format_line(&file_settings(), now, level, "supervisor", ev, fields, 0)
|
||||
+ "\n";
|
||||
let head = leleka_obs::EventHead { ts_ms: now, level, comp: "supervisor", ev };
|
||||
let file_line = leleka_obs::format_line(&file_settings(), head, fields, 0) + "\n";
|
||||
if level >= leleka_obs::settings().min_level {
|
||||
let shown = leleka_obs::format_line(
|
||||
leleka_obs::settings(),
|
||||
now,
|
||||
level,
|
||||
"supervisor",
|
||||
ev,
|
||||
fields,
|
||||
0,
|
||||
) + "\n";
|
||||
let shown = leleka_obs::format_line(leleka_obs::settings(), head, fields, 0) + "\n";
|
||||
let _ = std::io::stderr().write_all(shown.as_bytes());
|
||||
}
|
||||
if let Ok(mut file) = self.file.lock() {
|
||||
|
||||
@@ -3,7 +3,9 @@
|
||||
use crate::model_binding::qwen4exp_input::{
|
||||
BindingIdentity, InputBindingError, ModelBinding, MoeMatrixRole, MoeRoutedSourceScope, MoeWeightDescriptor,
|
||||
};
|
||||
use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PendingBatch, PreparedJob};
|
||||
use leleka_native_cpu_expert::{
|
||||
CpuPool, DownFormat, ExpertBytes, ExpertFormats, GateUpFormat, PendingBatch, PreparedJob,
|
||||
};
|
||||
const H: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
@@ -82,8 +84,9 @@ impl CpuMissWorkspace {
|
||||
let (gu, dt) = validate_triplet([gate, up, down])?;
|
||||
let [gate_bytes, up_bytes, down_bytes] = read_triplet_bytes(source, member, [gate, up, down])?;
|
||||
let input = flatten_activations(activations)?;
|
||||
let job = PreparedJob::new(gu, dt, gate_bytes, up_bytes, down_bytes, input, activations.len())
|
||||
.map_err(native_error)?;
|
||||
let formats = ExpertFormats { gu, down: dt };
|
||||
let bytes = ExpertBytes { gate: gate_bytes, up: up_bytes, down: down_bytes };
|
||||
let job = PreparedJob::new(formats, bytes, input, activations.len()).map_err(native_error)?;
|
||||
source.validate_binding(binding).map_err(CpuMissError::Source)?;
|
||||
Ok(PreparedCpuMiss { binding: binding.identity(), descriptors: [gate, up, down], job })
|
||||
}
|
||||
|
||||
@@ -157,8 +157,14 @@ impl Scratch {
|
||||
) {
|
||||
let (Some(router), Some(layout)) = (routers.get(layer), layouts.get(layer)) else { return };
|
||||
let out = &mut self.logits[..rows * EXPERTS];
|
||||
if leleka_native_cpu_expert::bf16_rows_multi(router, EXPERTS, HIDDEN, &self.x[..rows * HIDDEN], rows, out)
|
||||
.is_ok()
|
||||
if leleka_native_cpu_expert::bf16_rows_multi(
|
||||
router,
|
||||
leleka_native_cpu_expert::MatrixDims { rows: EXPERTS, cols: HIDDEN },
|
||||
&self.x[..rows * HIDDEN],
|
||||
rows,
|
||||
out,
|
||||
)
|
||||
.is_ok()
|
||||
{
|
||||
collect_wanted(out, rows, &self.resident, (&mut self.order[..], &mut self.want));
|
||||
for &e in &self.want {
|
||||
|
||||
@@ -18,7 +18,7 @@ use leleka_cuda_driver::{
|
||||
Driver, OriginalExpertCache, OriginalExpertTierProbe, OriginalVerifyCpuRows, OriginalVerifyCpuSink,
|
||||
OriginalVerifyExpertFormats, OriginalVerifyGpuPlan,
|
||||
};
|
||||
use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PreparedJob};
|
||||
use leleka_native_cpu_expert::{CpuPool, DownFormat, ExpertBytes, ExpertFormats, GateUpFormat, PreparedJob};
|
||||
|
||||
const H: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
@@ -104,11 +104,12 @@ fn chunk_jobs(
|
||||
let blob = blobs(e);
|
||||
jobs.push(
|
||||
PreparedJob::new(
|
||||
GateUpFormat::Iq4Xs,
|
||||
DownFormat::Iq4Nl,
|
||||
blob[..GATE].into(),
|
||||
blob[GATE..2 * GATE].into(),
|
||||
blob[2 * GATE..].into(),
|
||||
ExpertFormats { gu: GateUpFormat::Iq4Xs, down: DownFormat::Iq4Nl },
|
||||
ExpertBytes {
|
||||
gate: blob[..GATE].into(),
|
||||
up: blob[GATE..2 * GATE].into(),
|
||||
down: blob[2 * GATE..].into(),
|
||||
},
|
||||
input.into_boxed_slice(),
|
||||
entries.len(),
|
||||
)
|
||||
|
||||
@@ -188,8 +188,10 @@ fn swiglu_rows(dispatch: &Dispatch, gate: &[f32], up: &[f32], ff: usize) -> Vec<
|
||||
.swiglu_oai(
|
||||
&gate[first * ff..(first + count) * ff],
|
||||
&up[first * ff..(first + count) * ff],
|
||||
SWIGLU_ALPHA,
|
||||
SWIGLU_LIMIT,
|
||||
leleka_cpu_kernels::SwigluOaiParams {
|
||||
alpha: SWIGLU_ALPHA,
|
||||
limit: SWIGLU_LIMIT,
|
||||
},
|
||||
out,
|
||||
)
|
||||
.expect("activation kernel");
|
||||
|
||||
@@ -193,7 +193,15 @@ fn route_row(ctx: &LayerCtx, h: &[f32]) -> Vec<(usize, f32)> {
|
||||
let c = ctx.c;
|
||||
let mut logits = vec![0.0f32; c.n_expert];
|
||||
ctx.dispatch
|
||||
.rows_dot(h, ctx.view.router_w, c.n_embd, c.n_expert, &mut logits)
|
||||
.rows_dot(
|
||||
h,
|
||||
ctx.view.router_w,
|
||||
leleka_cpu_kernels::RowsShape {
|
||||
stride: c.n_embd,
|
||||
n: c.n_expert,
|
||||
},
|
||||
&mut logits,
|
||||
)
|
||||
.expect("router kernel");
|
||||
for (l, b) in logits.iter_mut().zip(ctx.view.router_b) {
|
||||
*l += b;
|
||||
|
||||
@@ -75,11 +75,12 @@ impl Model {
|
||||
let c = &self.config;
|
||||
let mut hqs = Vec::with_capacity(pass.n);
|
||||
let mut chosen: Vec<Vec<(usize, f32)>> = Vec::with_capacity(pass.n);
|
||||
let router_rows = leleka_cpu_kernels::RowsShape { stride: c.n_embd, n: c.n_expert };
|
||||
for x in xs {
|
||||
ops::rms_norm(x, &layer.post_norm, c.rms_eps, &mut pass.h);
|
||||
let mut logits = vec![0.0f32; c.n_expert];
|
||||
self.dispatch
|
||||
.rows_dot(&pass.h, &layer.router_w, c.n_embd, c.n_expert, &mut logits)
|
||||
.rows_dot(&pass.h, &layer.router_w, router_rows, &mut logits)
|
||||
.map_err(|err| ModelError::Invalid(format!("router kernel: {err}")))?;
|
||||
for (slot, bias) in logits.iter_mut().zip(&layer.router_b) {
|
||||
*slot += bias;
|
||||
@@ -142,7 +143,15 @@ impl Model {
|
||||
// the products come out as [row][token]: with one token the columns are contiguous
|
||||
let kernel = |g: &[f32], u: &[f32], out: &mut [f32]| {
|
||||
self.dispatch
|
||||
.swiglu_oai(g, u, SWIGLU_ALPHA, SWIGLU_LIMIT, out)
|
||||
.swiglu_oai(
|
||||
g,
|
||||
u,
|
||||
leleka_cpu_kernels::SwigluOaiParams {
|
||||
alpha: SWIGLU_ALPHA,
|
||||
limit: SWIGLU_LIMIT,
|
||||
},
|
||||
out,
|
||||
)
|
||||
.map_err(|err| ModelError::Invalid(format!("activation kernel: {err}")))
|
||||
};
|
||||
if na == 1 {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
//! RoPE with the iterative angle recurrence, softmax with a learned sink, router top-k with softmax over
|
||||
//! the selected logits, and the clamped gated activation of the experts. Written for Leleka.
|
||||
|
||||
use leleka_cpu_kernels::{Dispatch, KernelError};
|
||||
use leleka_cpu_kernels::{AttnShape, Dispatch, KernelError, ScoreSpec};
|
||||
|
||||
/// `y = x / sqrt(mean(x^2) + eps) * weight`; the sum of squares is accumulated in f64 like ggml.
|
||||
pub fn rms_norm(x: &[f32], weight: &[f32], eps: f32, out: &mut [f32]) {
|
||||
@@ -156,13 +156,14 @@ pub fn attend_group_with_sink(
|
||||
let scores = scores
|
||||
.get_mut(..heads * n)
|
||||
.ok_or(KernelError::LengthMismatch)?;
|
||||
dispatch.attn_scores(group.queries, heads, kv.keys, kv.stride, n, group.scale, scores)?;
|
||||
let shape = AttnShape { heads, n, stride: kv.stride };
|
||||
dispatch.attn_scores(group.queries, kv.keys, ScoreSpec { shape, scale: group.scale }, scores)?;
|
||||
let mut inverse = [0.0f32; 32];
|
||||
let inverse = inverse
|
||||
.get_mut(..heads)
|
||||
.ok_or(KernelError::LengthMismatch)?;
|
||||
softmax_scores_in_place(dispatch, group.sinks, scores, n, inverse)?;
|
||||
dispatch.attn_weighted_sum(scores, heads, n, kv.values, kv.stride, out)?;
|
||||
dispatch.attn_weighted_sum(scores, kv.values, shape, out)?;
|
||||
scale_heads_by_inverse(out, inverse);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -89,7 +89,8 @@ fn swiglu_quant_matches_the_cpu_activation() {
|
||||
let up: Vec<f32> = (0..rows * n).map(|_| rng.unit() * 12.0).collect();
|
||||
let (alpha, limit) = (1.702f32, 7.0f32);
|
||||
let mut act = vec![0.0f32; rows * n];
|
||||
d.swiglu_oai(&gate, &up, alpha, limit, &mut act).unwrap();
|
||||
d.swiglu_oai(&gate, &up, leleka_cpu_kernels::SwigluOaiParams { alpha, limit }, &mut act)
|
||||
.unwrap();
|
||||
// the CPU kernel against the scalar definition, so a GPU/CPU gap can be attributed
|
||||
for i in (0..act.len()).step_by(997) {
|
||||
let want = ops::swiglu_oai(gate[i], up[i], alpha, limit);
|
||||
@@ -123,8 +124,13 @@ fn router_picks_the_cpu_experts_and_weights() {
|
||||
let (got_ids, got_w) = (gpu.read_u32(&ids).unwrap(), gpu.read_f32(&weights).unwrap());
|
||||
for t in 0..m {
|
||||
let mut logits = vec![0.0f32; 32];
|
||||
d.rows_dot(&h[t * e..(t + 1) * e], &w, e, 32, &mut logits)
|
||||
.unwrap();
|
||||
d.rows_dot(
|
||||
&h[t * e..(t + 1) * e],
|
||||
&w,
|
||||
leleka_cpu_kernels::RowsShape { stride: e, n: 32 },
|
||||
&mut logits,
|
||||
)
|
||||
.unwrap();
|
||||
for (l, b) in logits.iter_mut().zip(&bias) {
|
||||
*l += b;
|
||||
}
|
||||
|
||||
@@ -72,7 +72,12 @@ fn the_nan_guard_reports_each_healed_and_unhealed_window() {
|
||||
fn engine_line(r: &RequestLine<'_>) -> String {
|
||||
use leleka_obs::{Format, Level, Settings};
|
||||
let json = Settings { min_level: Level::Info, format: Format::Json, debug: false, legacy: false };
|
||||
leleka_obs::format_line(&json, 1_793_613_072_345, Level::Info, "engine", "request", &request_line_fields(r), 0)
|
||||
leleka_obs::format_line(
|
||||
&json,
|
||||
leleka_obs::EventHead { ts_ms: 1_793_613_072_345, level: Level::Info, comp: "engine", ev: "request" },
|
||||
&request_line_fields(r),
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
fn assert_the_full_engine_line_carries_the_figures() {
|
||||
|
||||
@@ -90,7 +90,8 @@ fn alt_paths(a: &AltArgs) -> Result<AltPaths, String> {
|
||||
fn write_schedule(a: &AltArgs, out: &Path, procs: &[Proc]) -> Result<Planned, String> {
|
||||
let first_round = (a.batch - 1) * a.rounds + 1;
|
||||
let planned = make_schedule(a.seed, a.batch, a.rounds, procs);
|
||||
let text = schedule_text(a.seed, a.batch, a.rounds, &a.case, a.pin, first_round, &planned);
|
||||
let header = ScheduleHeader { seed: a.seed, batch: a.batch, rounds: a.rounds, case: &a.case, pin: a.pin };
|
||||
let text = schedule_text(header, first_round, &planned);
|
||||
fs::create_dir_all(out).map_err(|e| format!("{}: {e}", out.display()))?;
|
||||
if let Some(parent) = a.schedule.parent().filter(|p| !p.as_os_str().is_empty()) {
|
||||
fs::create_dir_all(parent).map_err(|e| format!("{}: {e}", parent.display()))?;
|
||||
|
||||
@@ -146,15 +146,17 @@ pub(super) fn make_schedule(seed: u64, batch: u32, rounds: u32, procs: &[Proc])
|
||||
out
|
||||
}
|
||||
|
||||
pub(super) fn schedule_text(
|
||||
seed: u64,
|
||||
batch: u32,
|
||||
rounds: u32,
|
||||
case: &str,
|
||||
pin: usize,
|
||||
first_round: u32,
|
||||
order: &[Vec<Proc>],
|
||||
) -> String {
|
||||
/// What the header line of a schedule file records about the batch.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct ScheduleHeader<'a> {
|
||||
pub(super) seed: u64,
|
||||
pub(super) batch: u32,
|
||||
pub(super) rounds: u32,
|
||||
pub(super) case: &'a str,
|
||||
pub(super) pin: usize,
|
||||
}
|
||||
pub(super) fn schedule_text(header: ScheduleHeader, first_round: u32, order: &[Vec<Proc>]) -> String {
|
||||
let ScheduleHeader { seed, batch, rounds, case, pin } = header;
|
||||
let mut t = format!(
|
||||
"{SCHEDULE_MAGIC} (written before the first run; the runner reads this file back)\n# seed={seed} batch={batch} \
|
||||
rounds={rounds} case={case} pin={pin}\n"
|
||||
|
||||
@@ -44,8 +44,8 @@
|
||||
//! cargo test -p leleka-native-cpu-expert --example kernel_ab
|
||||
|
||||
use leleka_native_cpu_expert::{
|
||||
BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob, cpu_kernel_report,
|
||||
rust_topology,
|
||||
BorrowedExpert, BorrowedGroup, DirectCpuPool, DownFormat, ExpertBytes, ExpertFormats, GateUpFormat, PreparedJob,
|
||||
cpu_kernel_report, rust_topology,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::cell::Cell;
|
||||
@@ -158,8 +158,8 @@ use cmd_time_fn::cmd_time;
|
||||
mod impl_impl;
|
||||
#[allow(unused_imports)]
|
||||
use impl_impl::{
|
||||
cell_env, inside_git_checkout, make_schedule, parse_regime, parse_schedule, procs_for, run_cell, schedule_text,
|
||||
scrubbed_command, splitmix,
|
||||
ScheduleHeader, cell_env, inside_git_checkout, make_schedule, parse_regime, parse_schedule, procs_for, run_cell,
|
||||
schedule_text, scrubbed_command, splitmix,
|
||||
};
|
||||
mod describe_cpp_tree_fn;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -15,7 +15,8 @@ fn the_schedule_is_reproducible_from_the_seed() {
|
||||
assert_ne!(a, make_schedule(7, 2, 30, &procs), "another batch gives another schedule");
|
||||
assert_eq!(a.len(), 30);
|
||||
// the text round-trips through the file format and names the seed
|
||||
let text = schedule_text(7, 1, 30, "18-20-r1", 9, 1, &a);
|
||||
let header = ScheduleHeader { seed: 7, batch: 1, rounds: 30, case: "18-20-r1", pin: 9 };
|
||||
let text = schedule_text(header, 1, &a);
|
||||
assert!(text.contains("seed=7 batch=1 rounds=30 case=18-20-r1 pin=9"));
|
||||
let back = parse_schedule(&text).unwrap();
|
||||
assert_eq!(back.iter().map(|r| r.1.clone()).collect::<Vec<_>>(), a);
|
||||
@@ -53,7 +54,8 @@ fn a_schedule_file_is_written_once_and_a_bad_one_is_refused() {
|
||||
assert!(create_new_file(&f, b"y").unwrap_err().contains("nothing is overwritten"));
|
||||
assert_eq!(fs::read(&f).unwrap(), b"x");
|
||||
let procs = procs_for(&TREES);
|
||||
let good = schedule_text(1, 1, 3, "c", 0, 1, &make_schedule(1, 1, 3, &procs));
|
||||
let header = ScheduleHeader { seed: 1, batch: 1, rounds: 3, case: "c", pin: 0 };
|
||||
let good = schedule_text(header, 1, &make_schedule(1, 1, 3, &procs));
|
||||
assert!(parse_schedule(&good).is_ok());
|
||||
assert!(parse_schedule("nope").is_err());
|
||||
assert!(parse_schedule(&good.replace("cpp-avx2-a", "cpp-avx2-z")).unwrap_err().contains("unknown process"));
|
||||
|
||||
@@ -25,11 +25,8 @@ pub(super) fn compute_case(pool: &mut DirectCpuPool, case: &CaseIn) -> Result<Ve
|
||||
(gate_up_row(case.header.gu).ok_or("gate/up type")?.1, down_row(case.header.down).ok_or("down type")?.1);
|
||||
let input = case.input();
|
||||
PreparedJob::new(
|
||||
gu,
|
||||
down,
|
||||
case.gate().into(),
|
||||
case.up().into(),
|
||||
case.down().into(),
|
||||
ExpertFormats { gu, down },
|
||||
ExpertBytes { gate: case.gate().into(), up: case.up().into(), down: case.down().into() },
|
||||
input.clone().into(),
|
||||
case.header.rows,
|
||||
)
|
||||
|
||||
@@ -98,15 +98,9 @@ fn zeroed_output(len: usize) -> Result<Box<[f32]>> {
|
||||
Ok(output.into_boxed_slice())
|
||||
}
|
||||
impl PreparedJob {
|
||||
pub fn new(
|
||||
gu: GateUpFormat,
|
||||
down: DownFormat,
|
||||
gate: Box<[u8]>,
|
||||
up: Box<[u8]>,
|
||||
down_bytes: Box<[u8]>,
|
||||
input: Box<[f32]>,
|
||||
rows: usize,
|
||||
) -> Result<Self> {
|
||||
pub fn new(formats: ExpertFormats, bytes: ExpertBytes, input: Box<[f32]>, rows: usize) -> Result<Self> {
|
||||
let ExpertFormats { gu, down } = formats;
|
||||
let ExpertBytes { gate, up, down: down_bytes } = bytes;
|
||||
check_job_input(rows, &input)?;
|
||||
let (gsize, gb) = gu.matrix_bytes();
|
||||
let (dsize, db) = down.matrix_bytes();
|
||||
|
||||
@@ -51,7 +51,7 @@ pub mod rust_topology;
|
||||
#[allow(unsafe_code)]
|
||||
mod rust_weight_iq;
|
||||
mod rust_weight_quant;
|
||||
pub use rust_kq::{bf16_rows, bf16_rows_multi};
|
||||
pub use rust_kq::{MatrixDims, bf16_rows, bf16_rows_multi};
|
||||
pub use rust_platform::advise_will_need;
|
||||
|
||||
const H: usize = 2560;
|
||||
@@ -87,6 +87,19 @@ pub enum DownFormat {
|
||||
Q2_0,
|
||||
}
|
||||
|
||||
/// The block formats of one expert: its fused gate/up pair and its down matrix.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct ExpertFormats {
|
||||
pub gu: GateUpFormat,
|
||||
pub down: DownFormat,
|
||||
}
|
||||
/// One expert's three encoded matrices as owned bytes.
|
||||
pub struct ExpertBytes {
|
||||
pub gate: Box<[u8]>,
|
||||
pub up: Box<[u8]>,
|
||||
pub down: Box<[u8]>,
|
||||
}
|
||||
|
||||
/// Owned detached bytes only. Runtime authenticates actual descriptors/source.
|
||||
pub struct PreparedJob {
|
||||
gu: GateUpFormat,
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
//! GPU comparisons, CLI/model loaders and measurements are supplied by the
|
||||
//! caller. These arrays are numerical values, never authenticated model owners.
|
||||
use super::rust_ggml::{Kind, NativeFormat};
|
||||
use super::rust_model_quant::ChunkSpan;
|
||||
use super::{Error, Result};
|
||||
|
||||
fn zeros<T: Default>(n: usize) -> Result<Vec<T>> {
|
||||
@@ -215,7 +216,8 @@ fn quantize_part(kind: Kind, w: &[f32], dest: &mut [u8], dims: (usize, usize)) -
|
||||
None
|
||||
};
|
||||
let bytes = kind.row_bytes(cols)?.checked_mul(rows).ok_or(Error::Shape)?;
|
||||
super::rust_model_quant::quantize_chunk(kind, w, &mut dest[..bytes], 0, rows, cols, imatrix.as_deref())?;
|
||||
let span = ChunkSpan { start: 0, nrows: rows, n_per_row: cols };
|
||||
super::rust_model_quant::quantize_chunk(kind, w, &mut dest[..bytes], span, imatrix.as_deref())?;
|
||||
Ok(())
|
||||
}
|
||||
pub fn check_inputs(seed: u32, rows: usize, width: usize) -> Result<Vec<f32>> {
|
||||
@@ -246,6 +248,7 @@ pub fn q5_one_min_case() -> Result<Q5OneMinCase> {
|
||||
*x = 0.01 * (rng.signed_100() as f32 + 0.45);
|
||||
}
|
||||
let mut weights = zeros(rows * Kind::Q5One.row_bytes(width)?)?;
|
||||
super::rust_model_quant::quantize_chunk(Kind::Q5One, &w, &mut weights, 0, rows, width, None)?;
|
||||
let span = ChunkSpan { start: 0, nrows: rows, n_per_row: width };
|
||||
super::rust_model_quant::quantize_chunk(Kind::Q5One, &w, &mut weights, span, None)?;
|
||||
Ok(Q5OneMinCase { weights, input: x, width, rows })
|
||||
}
|
||||
|
||||
@@ -26,7 +26,7 @@ impl<'a> Case<'a> {
|
||||
Ok(case)
|
||||
}
|
||||
fn gate_up(&mut self) -> Fail<()> {
|
||||
numerical(cpu::native_gu_rows(self.f, self.blob, &refs(&self.act), &mut outputs(&mut self.ff, FF), 0, FF))
|
||||
numerical(cpu::native_gu_rows(self.f, self.blob, &refs(&self.act), &mut outputs(&mut self.ff, FF), 0..FF))
|
||||
}
|
||||
/// Quantizes `ff` (as left by the throughput loops) into `hq`, runs down, then re-runs GU for width invariance.
|
||||
fn down(&mut self) -> Fail<Vec<f32>> {
|
||||
@@ -34,7 +34,7 @@ impl<'a> Case<'a> {
|
||||
// re-running GU for width invariance. Do not quantize hq again afterwards.
|
||||
quantize_acts(&mut self.hq, self.f.down, &self.ff, FF)?;
|
||||
let mut got = numerical(zeros::<f32>(NT * H))?;
|
||||
numerical(cpu::native_down_rows(self.f, self.blob, &refs(&self.hq), &mut outputs(&mut got, H), 0, H))?;
|
||||
numerical(cpu::native_down_rows(self.f, self.blob, &refs(&self.hq), &mut outputs(&mut got, H), 0..H))?;
|
||||
self.gate_up()?;
|
||||
Ok(got)
|
||||
}
|
||||
@@ -122,7 +122,8 @@ fn iq_gate_check(c: &Case, gref: &[f32], tag: &CStr, is512: bool) -> Fail<usize>
|
||||
let (f, gn) = (c.f, name(c.f.gu));
|
||||
let mut g = numerical(zeros::<f32>(NT * FF))?;
|
||||
let weights = &c.blob[..f.up_offset];
|
||||
numerical(cpu::iq_rows(f.gu, weights, H, &refs(&c.act), &mut outputs(&mut g, FF), 0, FF, is512))?;
|
||||
let matrix = cpu::EncodedRows { kind: f.gu, weights, width: H };
|
||||
numerical(cpu::iq_rows(matrix, &refs(&c.act), &mut outputs(&mut g, FF), 0..FF, is512))?;
|
||||
let rg = rel(&g, gref)?;
|
||||
report!(" %s %s gate rows vs ggml vec_dot: rel %.2e\n", gn.as_ptr(), tag.as_ptr(), rg);
|
||||
if rg <= 1e-5 {
|
||||
@@ -139,14 +140,14 @@ fn time_iq_gu(c: &mut Case, is512: bool) -> Fail<(f64, f64)> {
|
||||
let mut f1 = [&mut c.ff[..FF]];
|
||||
let start = Instant::now();
|
||||
for _ in 0..50 {
|
||||
numerical(cpu::iq_gu_rows(f, blob, &a1, &mut f1, 0, FF, is512))?;
|
||||
numerical(cpu::iq_gu_rows(cpu::GateUpBlob { format: f, bytes: blob }, &a1, &mut f1, 0..FF, is512))?;
|
||||
}
|
||||
let us1 = elapsed(start, 50);
|
||||
let aa = [&c.act[0], &c.act[1], &c.act[2]];
|
||||
let mut views = outputs(&mut c.ff, FF);
|
||||
let start = Instant::now();
|
||||
for _ in 0..50 {
|
||||
numerical(cpu::iq_gu_rows(f, blob, &aa, &mut views, 0, FF, is512))?;
|
||||
numerical(cpu::iq_gu_rows(cpu::GateUpBlob { format: f, bytes: blob }, &aa, &mut views, 0..FF, is512))?;
|
||||
}
|
||||
Ok((us1, elapsed(start, 50)))
|
||||
}
|
||||
@@ -170,9 +171,9 @@ fn width_diffs(c: &Case, got: &[f32]) -> Fail<(usize, usize)> {
|
||||
let mut one_ff = numerical(zeros::<f32>(FF))?;
|
||||
let mut one_out = numerical(zeros::<f32>(H))?;
|
||||
for k in 0..NT {
|
||||
numerical(cpu::native_gu_rows(f, blob, &[&c.act[k]], &mut [&mut one_ff], 0, FF))?;
|
||||
numerical(cpu::native_gu_rows(f, blob, &[&c.act[k]], &mut [&mut one_ff], 0..FF))?;
|
||||
gu_diff += bits(&one_ff, &c.ff[k * FF..(k + 1) * FF])?;
|
||||
numerical(cpu::native_down_rows(f, blob, &[&c.hq[k]], &mut [&mut one_out], 0, H))?;
|
||||
numerical(cpu::native_down_rows(f, blob, &[&c.hq[k]], &mut [&mut one_out], 0..H))?;
|
||||
dn_diff += bits(&one_out, &got[k * H..(k + 1) * H])?;
|
||||
}
|
||||
Ok((gu_diff, dn_diff))
|
||||
@@ -252,7 +253,8 @@ fn kq_differ(k: &KqCase, acts: &[NativeActivation; 8], reference: &[f32], values
|
||||
let mut differ = 0usize;
|
||||
for nt in 1..=8 {
|
||||
let mut views = outputs(&mut values[..nt * rows], rows);
|
||||
numerical(cpu::kq_rows(k.kind, k.w, k.width, &refs(&acts[..nt]), &mut views, 0, rows))?;
|
||||
let matrix = cpu::EncodedRows { kind: k.kind, weights: k.w, width: k.width };
|
||||
numerical(cpu::kq_rows(matrix, &refs(&acts[..nt]), &mut views, 0..rows))?;
|
||||
for t in 0..nt {
|
||||
let (got, want) = (&values[t * rows..(t + 1) * rows], &reference[t * rows..(t + 1) * rows]);
|
||||
differ += usize::from(bits(got, want)? != 0);
|
||||
@@ -268,7 +270,8 @@ fn kq_times(k: &KqCase, acts: &[NativeActivation; 8], values: &mut [f32]) -> Fai
|
||||
let mut views = outputs(&mut values[..4 * rows], rows);
|
||||
let start = Instant::now();
|
||||
for _ in 0..30 {
|
||||
numerical(cpu::kq_rows(k.kind, k.w, k.width, &aa, &mut views, 0, rows))?;
|
||||
let matrix = cpu::EncodedRows { kind: k.kind, weights: k.w, width: k.width };
|
||||
numerical(cpu::kq_rows(matrix, &aa, &mut views, 0..rows))?;
|
||||
}
|
||||
let usk = elapsed(start, 30);
|
||||
drop(views);
|
||||
@@ -305,7 +308,7 @@ fn q2_report(c: &Case, got: &[f32]) -> Fail<()> {
|
||||
}
|
||||
let mut alt = numerical(zeros::<f32>(NT * H))?;
|
||||
let aa: Vec<_> = a.iter().collect();
|
||||
numerical(cpu::q2_rows(&c.blob[c.f.down_offset..], FF, &aa, &mut outputs(&mut alt, H), 0, H))?;
|
||||
numerical(cpu::q2_rows(&c.blob[c.f.down_offset..], FF, &aa, &mut outputs(&mut alt, H), 0..H))?;
|
||||
let tag = if cpu::cpu_avx512_ok() { c"AVX-512" } else { c"AVX-2" };
|
||||
report!(" q2_0 %s down vs ggml down: rel %.2e\n", tag.as_ptr(), rel(&alt, got)?);
|
||||
Ok(())
|
||||
|
||||
@@ -151,7 +151,7 @@ unsafe fn native_row(sp: &Span, f: &NativeFormat, r: usize) {
|
||||
if kind.original_id() == 42 {
|
||||
q2_row(sp, row, &up, &mut g, &mut u);
|
||||
} else if gate {
|
||||
gate_up_row(sp, kind, row, &sp.blob[up], &mut g, &mut u);
|
||||
gate_up_row(sp, kind, GateUpRows { gate: row, up: &sp.blob[up] }, &mut g, &mut u);
|
||||
} else {
|
||||
down_row(sp, kind, row, &mut g);
|
||||
}
|
||||
@@ -186,19 +186,27 @@ unsafe fn q2_row(sp: &Span, row: &[u8], up: &std::ops::Range<usize>, g: &mut [f3
|
||||
}
|
||||
}
|
||||
|
||||
/// The encoded gate row and up row of one hidden unit.
|
||||
#[derive(Clone, Copy)]
|
||||
struct GateUpRows<'a> {
|
||||
gate: &'a [u8],
|
||||
up: &'a [u8],
|
||||
}
|
||||
|
||||
/// Non-Q2 gate/up row pair against the per-token native activations.
|
||||
///
|
||||
/// # Safety
|
||||
/// As `native_row`.
|
||||
unsafe fn gate_up_row(sp: &Span, kind: Kind, row: &[u8], up: &[u8], g: &mut [f32; 8], u: &mut [f32; 8]) {
|
||||
unsafe fn gate_up_row(sp: &Span, kind: Kind, rows: GateUpRows, g: &mut [f32; 8], u: &mut [f32; 8]) {
|
||||
unsafe {
|
||||
let n = sp.n;
|
||||
let mut a = [&*sp.j.na[0]; 8];
|
||||
for t in 0..n {
|
||||
a[t] = &*sp.j.na[t];
|
||||
}
|
||||
rust_native_general::group_dot(kind, row, &a[..n], &mut g[..n], rust_simd::dispatch(), true);
|
||||
rust_native_general::group_dot(kind, up, &a[..n], &mut u[..n], rust_simd::dispatch(), true);
|
||||
let route = || rust_native_general::DotRoute { d: rust_simd::dispatch(), gu: true };
|
||||
rust_native_general::group_dot(kind, rows.gate, &a[..n], &mut g[..n], route());
|
||||
rust_native_general::group_dot(kind, rows.up, &a[..n], &mut u[..n], route());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -214,6 +222,8 @@ unsafe fn down_row(sp: &Span, kind: Kind, row: &[u8], g: &mut [f32; 8]) {
|
||||
for t in 0..n {
|
||||
a[t] = &*base.add(t);
|
||||
}
|
||||
rust_native_general::group_dot_bytes(kind, row, FF, &a[..n], &mut g[..n], rust_simd::dispatch(), false);
|
||||
let route = rust_native_general::DotRoute { d: rust_simd::dispatch(), gu: false };
|
||||
let encoded = rust_native_general::EncodedRow { kind, bytes: row, n: FF };
|
||||
rust_native_general::group_dot_bytes(encoded, &a[..n], &mut g[..n], route);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -119,9 +119,16 @@ unsafe fn decode_q6(x: &[u8], y: &Q8K, q: &mut [u8; 256]) -> ([i16; 16], f32) {
|
||||
}
|
||||
(std::array::from_fn(|j| x[192 + j] as i8 as i16), y.d * h(x, 208))
|
||||
}
|
||||
/// The unpacked quants of one block and, for Q3_K, the high bits that go with them.
|
||||
#[derive(Clone, Copy)]
|
||||
struct BlockQuants<'a> {
|
||||
q: &'a [u8; 256],
|
||||
hi: &'a [u8; 256],
|
||||
}
|
||||
/// The four 32-lane products of one 128-quant group starting at `at`.
|
||||
#[target_feature(enable = "avx2,fma,f16c")]
|
||||
unsafe fn group_products(kind: i32, q: &[u8; 256], hi: &[u8; 256], y: &Q8K, sc: &[i16; 16], at: usize) -> [__m256i; 4] {
|
||||
unsafe fn group_products(kind: i32, quants: BlockQuants, y: &Q8K, sc: &[i16; 16], at: usize) -> [__m256i; 4] {
|
||||
let BlockQuants { q, hi } = quants;
|
||||
unsafe {
|
||||
let mut p = [_mm256_setzero_si256(); 4];
|
||||
for j in 0..4 {
|
||||
@@ -142,7 +149,7 @@ unsafe fn block_sum(kind: i32, q: &[u8; 256], hi: &[u8; 256], y: &Q8K, sc: &[i16
|
||||
unsafe {
|
||||
let mut sum = _mm256_setzero_si256();
|
||||
for group in 0..2 {
|
||||
let p = group_products(kind, q, hi, y, sc, group * 128);
|
||||
let p = group_products(kind, BlockQuants { q, hi }, y, sc, group * 128);
|
||||
if kind == 14 {
|
||||
sum = _mm256_add_epi32(sum, _mm256_add_epi32(p[0], p[1]));
|
||||
sum = _mm256_add_epi32(sum, _mm256_add_epi32(p[2], p[3]));
|
||||
|
||||
@@ -317,14 +317,14 @@ unsafe fn bf16_single(w: &[u16], rows: usize, cols: usize, x: &[f32], out: &mut
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn bf16_rows_multi(
|
||||
weights: &[u16],
|
||||
rows: usize,
|
||||
cols: usize,
|
||||
input: &[f32],
|
||||
nt: usize,
|
||||
out: &mut [f32],
|
||||
) -> Result<()> {
|
||||
/// The rows and columns of a bf16 weight matrix.
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub struct MatrixDims {
|
||||
pub rows: usize,
|
||||
pub cols: usize,
|
||||
}
|
||||
pub fn bf16_rows_multi(weights: &[u16], dims: MatrixDims, input: &[f32], nt: usize, out: &mut [f32]) -> Result<()> {
|
||||
let MatrixDims { rows, cols } = dims;
|
||||
if nt == 0
|
||||
|| nt > 8
|
||||
|| cols % 8 != 0
|
||||
@@ -340,12 +340,13 @@ pub fn bf16_rows_multi(
|
||||
// SAFETY: avx2_ok() proved AVX2+FMA; cols%8==0, nt<=8 and the checked products pin w=rows*cols, x=nt*cols,
|
||||
// out=nt*rows.
|
||||
unsafe {
|
||||
bf16_multi(weights, rows, cols, input, nt, out);
|
||||
bf16_multi(weights, dims, input, nt, out);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
#[target_feature(enable = "avx2,fma")]
|
||||
unsafe fn bf16_multi(w: &[u16], rows: usize, cols: usize, x: &[f32], nt: usize, out: &mut [f32]) {
|
||||
unsafe fn bf16_multi(w: &[u16], dims: MatrixDims, x: &[f32], nt: usize, out: &mut [f32]) {
|
||||
let MatrixDims { rows, cols } = dims;
|
||||
unsafe {
|
||||
for r in 0..rows {
|
||||
let mut acc = [_mm256_setzero_ps(); 8];
|
||||
|
||||
@@ -56,7 +56,7 @@ pub use set_oracle_q8_zero_fn::set_oracle_q8_zero;
|
||||
use set_oracle_q8_zero_fn::unpack32;
|
||||
mod pair_rows_fn;
|
||||
#[allow(unused_imports)]
|
||||
use pair_rows_fn::{act_refs, down_row, gate_up_pair};
|
||||
use pair_rows_fn::{GateUpOut, act_refs, down_row, gate_up_pair};
|
||||
mod admit_fn;
|
||||
#[allow(unused_imports)]
|
||||
use admit_fn::admit;
|
||||
|
||||
@@ -4,15 +4,21 @@
|
||||
#[allow(unused_imports)]
|
||||
use super::*;
|
||||
|
||||
/// The output width of a legacy row-range entry point and the chunk count its activations must have.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct RowSpace {
|
||||
pub(super) width: usize,
|
||||
pub(super) chunks: i32,
|
||||
}
|
||||
pub(super) fn admit(
|
||||
blob: &[u8],
|
||||
a: &[&PlanarActivation],
|
||||
out: &[&mut [f32]],
|
||||
width: usize,
|
||||
chunks: i32,
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
space: RowSpace,
|
||||
rows: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
let RowSpace { width, chunks } = space;
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
if blob.len() != BLOB
|
||||
|| a.is_empty()
|
||||
|| a.len() > MAX_ROWS
|
||||
@@ -30,7 +36,7 @@ pub(super) fn admit(
|
||||
Ok(())
|
||||
}
|
||||
pub fn gate_up_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]], r0: usize, r1: usize) -> Result<()> {
|
||||
admit(blob, a, out, FF, 80, r0, r1)?;
|
||||
admit(blob, a, out, RowSpace { width: FF, chunks: 80 }, r0..r1)?;
|
||||
let empty = ActQ::default();
|
||||
let aa = act_refs(a, &empty);
|
||||
let n = a.len();
|
||||
@@ -38,7 +44,7 @@ pub fn gate_up_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]]
|
||||
let mut u = [0.0; MAX_ROWS];
|
||||
// Original row-range APIs always use row_dot, even in oracle activation mode.
|
||||
for r in r0..r1 {
|
||||
gate_up_pair(blob, r, &aa[..n], &mut g[..n], &mut u[..n], false);
|
||||
gate_up_pair(blob, r, &aa[..n], GateUpOut { g: &mut g[..n], u: &mut u[..n] }, false);
|
||||
for t in 0..n {
|
||||
out[t][r] = silu(g[t], u[t]);
|
||||
}
|
||||
@@ -46,7 +52,7 @@ pub fn gate_up_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]]
|
||||
Ok(())
|
||||
}
|
||||
pub fn down_rows(blob: &[u8], a: &[&PlanarActivation], out: &mut [&mut [f32]], r0: usize, r1: usize) -> Result<()> {
|
||||
admit(blob, a, out, H, 20, r0, r1)?;
|
||||
admit(blob, a, out, RowSpace { width: H, chunks: 20 }, r0..r1)?;
|
||||
let empty = ActQ::default();
|
||||
let aa = act_refs(a, &empty);
|
||||
let n = a.len();
|
||||
@@ -81,7 +87,7 @@ fn hidden_rows(blob: &[u8], aa: &[&ActQ], scratch: &mut PlanarScratch, oracle: b
|
||||
let mut g = [0.0; MAX_ROWS];
|
||||
let mut u = [0.0; MAX_ROWS];
|
||||
for r in 0..FF {
|
||||
gate_up_pair(blob, r, aa, &mut g[..n], &mut u[..n], oracle);
|
||||
gate_up_pair(blob, r, aa, GateUpOut { g: &mut g[..n], u: &mut u[..n] }, oracle);
|
||||
for t in 0..n {
|
||||
scratch.ff[t][r] = silu(g[t], u[t]);
|
||||
}
|
||||
|
||||
@@ -19,7 +19,7 @@ pub(in super::super) fn gate_each(
|
||||
let mut g = [0.0; MAX_ROWS];
|
||||
let mut u = g;
|
||||
for r in r0..r1 {
|
||||
gate_up_pair(blob, r, &aa[..n], &mut g[..n], &mut u[..n], false);
|
||||
gate_up_pair(blob, r, &aa[..n], GateUpOut { g: &mut g[..n], u: &mut u[..n] }, false);
|
||||
for t in 0..n {
|
||||
write(t, r, silu(g[t], u[t]));
|
||||
}
|
||||
@@ -53,7 +53,7 @@ pub(in super::super) fn whole_single(blob: &[u8], a: &PlanarActivation, out: &mu
|
||||
let mut g = [0.0];
|
||||
let mut u = [0.0];
|
||||
for r in 0..FF {
|
||||
gate_up_pair(blob, r, &[&a.0], &mut g, &mut u, oracle);
|
||||
gate_up_pair(blob, r, &[&a.0], GateUpOut { g: &mut g, u: &mut u }, oracle);
|
||||
s.ff[r] = silu(g[0], u[0]);
|
||||
}
|
||||
s.a2.quantize(&s.ff).expect("admitted legacy whole geometry");
|
||||
|
||||
@@ -12,8 +12,14 @@ pub(super) fn act_refs<'a>(a: &'a [&PlanarActivation], empty: &'a ActQ) -> [&'a
|
||||
}
|
||||
aa
|
||||
}
|
||||
/// Gate (`g`) and up (`u`) dot products of row pair `r` against the activations `aa`.
|
||||
pub(super) fn gate_up_pair(blob: &[u8], r: usize, aa: &[&ActQ], g: &mut [f32], u: &mut [f32], oracle: bool) {
|
||||
/// The gate and up output slices of a row pair, one value per token.
|
||||
pub(super) struct GateUpOut<'a> {
|
||||
pub(super) g: &'a mut [f32],
|
||||
pub(super) u: &'a mut [f32],
|
||||
}
|
||||
/// Gate (`out.g`) and up (`out.u`) dot products of row pair `r` against the activations `aa`.
|
||||
pub(super) fn gate_up_pair(blob: &[u8], r: usize, aa: &[&ActQ], out: GateUpOut<'_>, oracle: bool) {
|
||||
let GateUpOut { g, u } = out;
|
||||
row(
|
||||
&blob[(2 * r) * 640..(2 * r + 1) * 640],
|
||||
&blob[GU_SCALES + 2 * r * 80..GU_SCALES + (2 * r + 1) * 80],
|
||||
|
||||
@@ -169,12 +169,12 @@ pub(super) unsafe fn row256(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut
|
||||
unsafe fn row512_blocks(
|
||||
codes: &[u8],
|
||||
a: &[&ActQ],
|
||||
b0: usize,
|
||||
n: usize,
|
||||
blocks: std::ops::Range<usize>,
|
||||
p: &[__m512; MAX_ROWS],
|
||||
acc: &mut [__m512; MAX_ROWS],
|
||||
) {
|
||||
unsafe {
|
||||
let (b0, n) = (blocks.start, blocks.len());
|
||||
let base = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
|
||||
for i in 0..n {
|
||||
let b = b0 + i;
|
||||
@@ -215,7 +215,7 @@ pub(super) unsafe fn row512(codes: &[u8], scales: &[u8], a: &[&ActQ], out: &mut
|
||||
p[t] = _mm512_mul_ps(dd, _mm512_maskz_loadu_ps(m16, a[t].scale.as_ptr().add(b0 * 2)));
|
||||
corr[t] = _mm512_fmadd_ps(dd, _mm512_maskz_loadu_ps(m16, a[t].hx.as_ptr().add(b0 * 2)), corr[t]);
|
||||
}
|
||||
row512_blocks(codes, a, b0, n, &p, &mut acc);
|
||||
row512_blocks(codes, a, b0..b0 + n, &p, &mut acc);
|
||||
}
|
||||
for t in 0..a.len() {
|
||||
out[t] = _mm512_reduce_add_ps(acc[t]) - _mm512_reduce_add_ps(corr[t]);
|
||||
|
||||
@@ -50,11 +50,16 @@ fn check_chunk_args(kind: Kind, start: usize, n_per_row: usize, imatrix: Option<
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Source end, destination start and end, and the byte count of `nrows` rows of `n_per_row` weights from `start`.
|
||||
fn chunk_extents(
|
||||
(start, nrows, n_per_row): (usize, usize, usize),
|
||||
rowbytes: usize,
|
||||
) -> Result<(usize, usize, usize, usize)> {
|
||||
/// Which part of a weight matrix a chunk quantization covers: `nrows` rows of `n_per_row` weights from `start`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct ChunkSpan {
|
||||
pub start: usize,
|
||||
pub nrows: usize,
|
||||
pub n_per_row: usize,
|
||||
}
|
||||
/// Source end, destination start and end, and the byte count of the rows `span` covers.
|
||||
fn chunk_extents(span: ChunkSpan, rowbytes: usize) -> Result<(usize, usize, usize, usize)> {
|
||||
let ChunkSpan { start, nrows, n_per_row } = span;
|
||||
let n = nrows.checked_mul(n_per_row).ok_or(Error::Shape)?;
|
||||
let end = start.checked_add(n).ok_or(Error::Shape)?;
|
||||
let at = (start / n_per_row).checked_mul(rowbytes).ok_or(Error::Shape)?;
|
||||
@@ -66,14 +71,13 @@ pub fn quantize_chunk(
|
||||
kind: Kind,
|
||||
src: &[f32],
|
||||
dst: &mut [u8],
|
||||
start: usize,
|
||||
nrows: usize,
|
||||
n_per_row: usize,
|
||||
span: ChunkSpan,
|
||||
imatrix: Option<&[f32]>,
|
||||
) -> Result<usize> {
|
||||
let ChunkSpan { start, n_per_row, .. } = span;
|
||||
check_chunk_args(kind, start, n_per_row, imatrix)?;
|
||||
let rowbytes = kind.row_bytes(n_per_row)?;
|
||||
let (end, at, outend, bytes) = chunk_extents((start, nrows, n_per_row), rowbytes)?;
|
||||
let (end, at, outend, bytes) = chunk_extents(span, rowbytes)?;
|
||||
if end > src.len() || outend > dst.len() {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
|
||||
@@ -42,6 +42,10 @@ pub use group_dot_bytes_policy_fn::iq_rows;
|
||||
#[allow(unused_imports)]
|
||||
pub use group_dot_bytes_policy_fn::kq_rows;
|
||||
#[allow(unused_imports)]
|
||||
pub(super) use group_dot_bytes_policy_fn::{DotPolicy, DotRoute, EncodedRow};
|
||||
#[allow(unused_imports)]
|
||||
pub use group_dot_bytes_policy_fn::{EncodedRows, GateUpBlob};
|
||||
#[allow(unused_imports)]
|
||||
use group_dot_bytes_policy_fn::{check_gu, check_rows, check_weights, kq_dot, store, typed};
|
||||
mod iq4nl_rows_fn;
|
||||
#[allow(unused_imports)]
|
||||
|
||||
@@ -66,16 +66,28 @@ unsafe fn kq_bytes_dot(k: i32, row: &[u8], n: usize, act: &[&[u8]], out: &mut [f
|
||||
}
|
||||
}
|
||||
}
|
||||
pub(super) unsafe fn group_dot_bytes_policy(
|
||||
kind: Kind,
|
||||
row: &[u8],
|
||||
n: usize,
|
||||
act: &[&[u8]],
|
||||
out: &mut [f32],
|
||||
d: &super::super::rust_simd::Dispatch,
|
||||
gu: bool,
|
||||
policy_nt: usize,
|
||||
) {
|
||||
/// One encoded weight row of `n` weights.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in super::super) struct EncodedRow<'a> {
|
||||
pub(in super::super) kind: Kind,
|
||||
pub(in super::super) bytes: &'a [u8],
|
||||
pub(in super::super) n: usize,
|
||||
}
|
||||
/// The CPU dispatch table and the role (gate/up or down) that pick the kernel of a dot.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in super::super) struct DotRoute<'a> {
|
||||
pub(in super::super) d: &'a super::super::rust_simd::Dispatch,
|
||||
pub(in super::super) gu: bool,
|
||||
}
|
||||
/// A route and the token count its multi-token policy is decided on (it can exceed the chunk handled).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(in super::super) struct DotPolicy<'a> {
|
||||
pub(in super::super) route: DotRoute<'a>,
|
||||
pub(in super::super) nt: usize,
|
||||
}
|
||||
pub(super) unsafe fn group_dot_bytes_policy(row: EncodedRow, act: &[&[u8]], out: &mut [f32], policy: DotPolicy) {
|
||||
let EncodedRow { kind, bytes: row, n } = row;
|
||||
let DotPolicy { route: DotRoute { d, gu }, nt: policy_nt } = policy;
|
||||
unsafe {
|
||||
let nt = act.len();
|
||||
let k = kind.original_id();
|
||||
@@ -123,13 +135,12 @@ pub(super) fn store(out: &mut [&mut [f32]], base: usize, r: usize, v: &[f32]) {
|
||||
}
|
||||
/// Admission of the explicit kq256 row API (shapes, activations, CPU); returns the row stride.
|
||||
fn admit_kq(
|
||||
kind: Kind,
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
matrix: EncodedRows,
|
||||
act: &[&NativeActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1): (usize, usize),
|
||||
) -> Result<usize> {
|
||||
let EncodedRows { kind, weights, width } = matrix;
|
||||
if !matches!(kind, Kind::Q4K | Kind::Q5One | Kind::Q8Zero) {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
@@ -143,17 +154,23 @@ fn admit_kq(
|
||||
}
|
||||
Ok(stride)
|
||||
}
|
||||
/// A matrix of whole encoded rows of `width` weights each, all of one kind.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct EncodedRows<'a> {
|
||||
pub kind: Kind,
|
||||
pub weights: &'a [u8],
|
||||
pub width: usize,
|
||||
}
|
||||
/// The explicit Original kq256 benchmark API is independent of its env policy.
|
||||
pub fn kq_rows(
|
||||
kind: Kind,
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
matrix: EncodedRows,
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
let stride = admit_kq(kind, weights, width, act, out, (r0, r1))?;
|
||||
let EncodedRows { kind, weights, width } = matrix;
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
let stride = admit_kq(matrix, act, out, (r0, r1))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
for r in r0..r1 {
|
||||
@@ -191,13 +208,12 @@ pub(super) unsafe fn iq_multi(avx512: bool, id: i32, row: &[u8], a: &[&[Q8K]], o
|
||||
}
|
||||
/// Admission of the explicit IQ256/IQ512 row API (shapes, activations, CPU); returns the row stride.
|
||||
fn admit_iq(
|
||||
kind: Kind,
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
matrix: EncodedRows,
|
||||
act: &[&NativeActivation],
|
||||
out: &[&mut [f32]],
|
||||
(r0, r1, avx512): (usize, usize, bool),
|
||||
) -> Result<usize> {
|
||||
let EncodedRows { kind, weights, width } = matrix;
|
||||
if !matches!(kind.original_id(), 16 | 17 | 18 | 21 | 22) || width == 0 {
|
||||
return Err(Error::Shape);
|
||||
}
|
||||
@@ -211,16 +227,15 @@ fn admit_iq(
|
||||
}
|
||||
/// Explicit Original IQ256/IQ512 benchmark entry, independent of MT/env policy.
|
||||
pub fn iq_rows(
|
||||
kind: Kind,
|
||||
weights: &[u8],
|
||||
width: usize,
|
||||
matrix: EncodedRows,
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
avx512: bool,
|
||||
) -> Result<()> {
|
||||
let stride = admit_iq(kind, weights, width, act, out, (r0, r1, avx512))?;
|
||||
let EncodedRows { kind, weights, width } = matrix;
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
let stride = admit_iq(matrix, act, out, (r0, r1, avx512))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
// SAFETY: module header; avx2_ok() (and avx512_ok()+dq_ok() when `avx512`) checked in admit_iq; width % 256
|
||||
@@ -291,15 +306,21 @@ unsafe fn iq_gu_row(
|
||||
}
|
||||
}
|
||||
}
|
||||
/// The gate/up blob of one expert and the format that describes it.
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct GateUpBlob<'a> {
|
||||
pub format: &'a NativeFormat,
|
||||
pub bytes: &'a [u8],
|
||||
}
|
||||
pub fn iq_gu_rows(
|
||||
f: &NativeFormat,
|
||||
blob: &[u8],
|
||||
blob: GateUpBlob,
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
avx512: bool,
|
||||
) -> Result<()> {
|
||||
let GateUpBlob { format: f, bytes: blob } = blob;
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
admit_iq_gu(f, blob, act, out, (r0, r1, avx512))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
|
||||
+15
-24
@@ -64,13 +64,14 @@ unsafe fn gate_up_row(
|
||||
) {
|
||||
unsafe {
|
||||
let d = super::super::rust_simd::dispatch();
|
||||
let policy = DotPolicy { route: DotRoute { d, gu: true }, nt: act.len() };
|
||||
for at in (0..act.len()).step_by(8) {
|
||||
let end = (at + 8).min(act.len());
|
||||
let chunk = &act[at..end];
|
||||
let mut g = [0.0; 8];
|
||||
let mut u = [0.0; 8];
|
||||
group_dot_policy(f.gu, gr, chunk, &mut g[..chunk.len()], d, true, act.len());
|
||||
group_dot_policy(f.gu, ur, chunk, &mut u[..chunk.len()], d, true, act.len());
|
||||
group_dot_policy(f.gu, gr, chunk, &mut g[..chunk.len()], policy);
|
||||
group_dot_policy(f.gu, ur, chunk, &mut u[..chunk.len()], policy);
|
||||
for t in 0..chunk.len() {
|
||||
ff[at + t][r] = super::super::rust_simd::silu(g[t], u[t]);
|
||||
}
|
||||
@@ -82,9 +83,9 @@ pub fn native_gu_rows(
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
ff: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
f.validate()?;
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
@@ -118,11 +119,12 @@ unsafe fn down_row<const BYTES: usize>(
|
||||
) {
|
||||
unsafe {
|
||||
let d = super::super::rust_simd::dispatch();
|
||||
let policy = DotPolicy { route: DotRoute { d, gu: false }, nt: hq.len() };
|
||||
for at in (0..hq.len()).step_by(8) {
|
||||
let end = (at + 8).min(hq.len());
|
||||
let chunk = &hq[at..end];
|
||||
let mut v = [0.0; 8];
|
||||
group_dot_policy(f.down, row, chunk, &mut v[..chunk.len()], d, false, hq.len());
|
||||
group_dot_policy(f.down, row, chunk, &mut v[..chunk.len()], policy);
|
||||
for t in 0..chunk.len() {
|
||||
out[at + t][r] = v[t];
|
||||
}
|
||||
@@ -134,9 +136,9 @@ pub fn native_down_rows<const BYTES: usize>(
|
||||
blob: &[u8],
|
||||
hq: &[&NativeActivation<BYTES>],
|
||||
out: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
f.validate()?;
|
||||
if !super::super::rust_simd::avx2_ok() {
|
||||
return Err(Error::Unsupported);
|
||||
@@ -180,28 +182,19 @@ pub(in super::super) unsafe fn group_dot<const BYTES: usize>(
|
||||
row: &[u8],
|
||||
act: &[&NativeActivation<BYTES>],
|
||||
out: &mut [f32],
|
||||
d: &super::super::rust_simd::Dispatch,
|
||||
gu: bool,
|
||||
route: DotRoute,
|
||||
) {
|
||||
unsafe {
|
||||
let mut raw: [&[u8]; 8] = [&[]; 8];
|
||||
for t in 0..act.len() {
|
||||
raw[t] = act[t].raw();
|
||||
}
|
||||
group_dot_bytes(kind, row, act[0].n, &raw[..act.len()], out, d, gu)
|
||||
group_dot_bytes(EncodedRow { kind, bytes: row, n: act[0].n }, &raw[..act.len()], out, route)
|
||||
}
|
||||
}
|
||||
pub(in super::super) unsafe fn group_dot_bytes(
|
||||
kind: Kind,
|
||||
row: &[u8],
|
||||
n: usize,
|
||||
act: &[&[u8]],
|
||||
out: &mut [f32],
|
||||
d: &super::super::rust_simd::Dispatch,
|
||||
gu: bool,
|
||||
) {
|
||||
pub(in super::super) unsafe fn group_dot_bytes(row: EncodedRow, act: &[&[u8]], out: &mut [f32], route: DotRoute) {
|
||||
unsafe {
|
||||
group_dot_bytes_policy(kind, row, n, act, out, d, gu, act.len());
|
||||
group_dot_bytes_policy(row, act, out, DotPolicy { route, nt: act.len() });
|
||||
}
|
||||
}
|
||||
pub(super) unsafe fn group_dot_policy<const BYTES: usize>(
|
||||
@@ -209,15 +202,13 @@ pub(super) unsafe fn group_dot_policy<const BYTES: usize>(
|
||||
row: &[u8],
|
||||
act: &[&NativeActivation<BYTES>],
|
||||
out: &mut [f32],
|
||||
d: &super::super::rust_simd::Dispatch,
|
||||
gu: bool,
|
||||
policy_nt: usize,
|
||||
policy: DotPolicy,
|
||||
) {
|
||||
unsafe {
|
||||
let mut raw: [&[u8]; 8] = [&[]; 8];
|
||||
for t in 0..act.len() {
|
||||
raw[t] = act[t].raw();
|
||||
}
|
||||
group_dot_bytes_policy(kind, row, act[0].n, &raw[..act.len()], out, d, gu, policy_nt)
|
||||
group_dot_bytes_policy(EncodedRow { kind, bytes: row, n: act[0].n }, &raw[..act.len()], out, policy)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,9 +30,9 @@ pub fn iq4nl_rows(
|
||||
width: usize,
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
let stride = admit_iq4nl(weights, width, act, out, (r0, r1))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
@@ -117,9 +117,9 @@ pub fn kq_gu_rows(
|
||||
blob: &[u8],
|
||||
act: &[&NativeActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
admit_kq_gu(f, blob, act, out, (r0, r1))?;
|
||||
for base in (0..act.len()).step_by(8) {
|
||||
let act = &act[base..(base + 8).min(act.len())];
|
||||
@@ -168,9 +168,9 @@ pub fn q2_rows(
|
||||
width: usize,
|
||||
act: &[&super::super::rust_legacy::PlanarActivation],
|
||||
out: &mut [&mut [f32]],
|
||||
r0: usize,
|
||||
r1: usize,
|
||||
rows: std::ops::Range<usize>,
|
||||
) -> Result<()> {
|
||||
let (r0, r1) = (rows.start, rows.end);
|
||||
let stride = check_q2_rows(weights, width, act, out, (r0, r1))?;
|
||||
let empty = super::super::rust_types::ActQ::default();
|
||||
let mut a = [∅ 8];
|
||||
|
||||
@@ -81,7 +81,7 @@ fn gate_up_output(f: &NativeFormat, blob: &[u8], acts: &[NativeActivation], n_ff
|
||||
let refs: Vec<&NativeActivation> = acts.iter().collect();
|
||||
let mut ff = vec![vec![0.0f32; n_ff]; acts.len()];
|
||||
let mut outs: Vec<&mut [f32]> = ff.iter_mut().map(|v| v.as_mut_slice()).collect();
|
||||
native_gu_rows(f, blob, &refs, &mut outs, 0, n_ff).unwrap();
|
||||
native_gu_rows(f, blob, &refs, &mut outs, 0..n_ff).unwrap();
|
||||
ff
|
||||
}
|
||||
|
||||
|
||||
@@ -44,11 +44,11 @@ pub(super) use alloc_fn::init;
|
||||
#[allow(unused_imports)]
|
||||
use alloc_fn::put_h;
|
||||
#[allow(unused_imports)]
|
||||
use alloc_fn::quant_candidates;
|
||||
#[allow(unused_imports)]
|
||||
use alloc_fn::signs;
|
||||
#[allow(unused_imports)]
|
||||
use alloc_fn::totals;
|
||||
#[allow(unused_imports)]
|
||||
use alloc_fn::{CandidateStep, Target, quant_candidates};
|
||||
mod iq2_xxs_fn;
|
||||
#[allow(unused_imports)]
|
||||
use iq2_xxs_fn::iq2_xs;
|
||||
|
||||
@@ -229,16 +229,22 @@ pub(super) fn totals(x: &[f32], w: &[f32], l: &[i8]) -> (f32, f32) {
|
||||
}
|
||||
(sx, s2)
|
||||
}
|
||||
pub(super) fn quant_candidates(
|
||||
g: &Grid,
|
||||
inv: f32,
|
||||
x: &[f32],
|
||||
w: &[f32],
|
||||
scale: f32,
|
||||
l: &mut [i8],
|
||||
max: i32,
|
||||
on: &mut [bool],
|
||||
) {
|
||||
/// The values to quantize and their weights.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Target<'a> {
|
||||
pub(super) x: &'a [f32],
|
||||
pub(super) w: &'a [f32],
|
||||
}
|
||||
/// One trial of `quant_candidates`: the inverse step, the scale the groups are resolved at and the level count.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct CandidateStep {
|
||||
pub(super) inv: f32,
|
||||
pub(super) scale: f32,
|
||||
pub(super) max: i32,
|
||||
}
|
||||
pub(super) fn quant_candidates(g: &Grid, target: Target, step: CandidateStep, l: &mut [i8], on: &mut [bool]) {
|
||||
let Target { x, w } = target;
|
||||
let CandidateStep { inv, scale, max } = step;
|
||||
for k in 0..x.len() / g.dim {
|
||||
let at = k * g.dim;
|
||||
for j in 0..g.dim {
|
||||
|
||||
@@ -86,7 +86,9 @@ pub(in super::super) fn search_scale<const N: usize, const G: usize>(
|
||||
let inv = (t.centre + is as f32 * t.step) / max;
|
||||
let mut aux = [0i8; N];
|
||||
let mut ao = [true; G];
|
||||
quant_candidates(g, inv, &b.xv, &b.wa, 1.0 / inv, &mut aux, t.levels, &mut ao);
|
||||
let target = Target { x: &b.xv, w: &b.wa };
|
||||
let step = CandidateStep { inv, scale: 1.0 / inv, max: t.levels };
|
||||
quant_candidates(g, target, step, &mut aux, &mut ao);
|
||||
let (sx, s2) = totals(&b.xv, &b.w, &aux);
|
||||
if s2 > 0.0 && sx * sx > best * s2 {
|
||||
fit.scale = sx / s2;
|
||||
|
||||
@@ -69,7 +69,8 @@ fn iq2_xxs_search(g: &Grid, b: &Block<32>, start: (f32, [i8; 32]), effective: f3
|
||||
for is in -6..=6 {
|
||||
let inv = (5.0 + is as f32 * 0.1) / effective;
|
||||
let mut aux = [0i8; 32];
|
||||
quant_candidates(g, inv, &b.xv, &b.wa, 1.0 / inv, &mut aux, 3, &mut [false; 4]);
|
||||
let step = CandidateStep { inv, scale: 1.0 / inv, max: 3 };
|
||||
quant_candidates(g, Target { x: &b.xv, w: &b.wa }, step, &mut aux, &mut [false; 4]);
|
||||
let (sx, s2) = totals(&b.xv, &b.w, &aux);
|
||||
if s2 > 0.0 && sx * sx > best * s2 {
|
||||
scale = sx / s2;
|
||||
@@ -78,7 +79,8 @@ fn iq2_xxs_search(g: &Grid, b: &Block<32>, start: (f32, [i8; 32]), effective: f3
|
||||
}
|
||||
}
|
||||
if scale > 0.0 {
|
||||
quant_candidates(g, 1.0 / scale, &b.xv, &b.wa, scale, &mut l, 3, &mut [false; 4]);
|
||||
let step = CandidateStep { inv: 1.0 / scale, scale, max: 3 };
|
||||
quant_candidates(g, Target { x: &b.xv, w: &b.wa }, step, &mut l, &mut [false; 4]);
|
||||
let (sx, s2) = totals(&b.xv, &b.w, &l);
|
||||
if s2 > 0.0 {
|
||||
scale = sx / s2;
|
||||
|
||||
@@ -10,10 +10,16 @@ struct Iq3Out {
|
||||
flags: [u32; 8],
|
||||
q3: [u8; 104],
|
||||
}
|
||||
/// The fitted levels and sign bytes of block `ib`.
|
||||
struct BlockFit<'a> {
|
||||
ib: usize,
|
||||
l: &'a [i8; 32],
|
||||
sign: &'a [u8; 4],
|
||||
}
|
||||
impl Iq3Out {
|
||||
/// Stores the grid indices and signs of block `ib`; `fit` is (levels, sign bytes).
|
||||
fn store(&mut self, g: &Grid, full: bool, y: &mut [u8], ib: usize, fit: (&[i8; 32], &[u8; 4])) -> Result<()> {
|
||||
let (l, sign) = fit;
|
||||
/// Stores the grid indices and signs of the block `fit` describes.
|
||||
fn store(&mut self, g: &Grid, full: bool, y: &mut [u8], fit: BlockFit) -> Result<()> {
|
||||
let BlockFit { ib, l, sign } = fit;
|
||||
for k in 0..8 {
|
||||
let index = g.index(&l[k * 4..k * 4 + 4])?;
|
||||
self.q3[ib * 8 + k] = index as u8;
|
||||
@@ -60,7 +66,7 @@ pub(super) fn iq3(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f3
|
||||
let at = ib * 32;
|
||||
let qb = qw.map(|q| &q[at..at + 32]);
|
||||
let Some((scale, l, sign)) = iq3_block(g, full, (&x[at..at + 32], qb), sigma) else { continue };
|
||||
out.store(g, full, y, ib, (&l, &sign))?;
|
||||
out.store(g, full, y, BlockFit { ib, l: &l, sign: &sign })?;
|
||||
out.scales[ib] = scale;
|
||||
if scale > maxs {
|
||||
maxs = scale;
|
||||
|
||||
@@ -95,7 +95,7 @@ pub(in super::super) fn qx(x: &[f32], nmax: i32, l: &mut [i8], mut rmse: i32, qw
|
||||
if early {
|
||||
return if s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv };
|
||||
}
|
||||
qx_search(x, nmax, l, (max, rmse, qw), scale, sx)
|
||||
qx_search(x, nmax, l, (max, rmse, qw), QxStart { scale, sx })
|
||||
}
|
||||
/// The levels `nmax + clamp(round(inv * x))` as stored in `l`.
|
||||
fn qx_levels(x: &[f32], nmax: i32, l: &mut [i8], inv: f32) {
|
||||
@@ -114,9 +114,16 @@ fn qx_sums(x: &[f32], nmax: i32, inv: f32, rmse: i32, qw: Option<&[f32]>) -> (f3
|
||||
}
|
||||
(sx, s2)
|
||||
}
|
||||
/// The scale of the first fit and its weighted sum `sx`, which the search tries to beat.
|
||||
#[derive(Clone, Copy)]
|
||||
struct QxStart {
|
||||
scale: f32,
|
||||
sx: f32,
|
||||
}
|
||||
/// Tries the 18 other scales -(nmax + 0.1 * is) / max and keeps the levels of the best fit; `fit` is (max, rmse, qw).
|
||||
fn qx_search(x: &[f32], nmax: i32, l: &mut [i8], fit: (f32, i32, Option<&[f32]>), mut scale: f32, sx: f32) -> f32 {
|
||||
fn qx_search(x: &[f32], nmax: i32, l: &mut [i8], fit: (f32, i32, Option<&[f32]>), start: QxStart) -> f32 {
|
||||
let (max, rmse, qw) = fit;
|
||||
let QxStart { mut scale, sx } = start;
|
||||
let mut best = scale * sx;
|
||||
for is in (-9..=9).filter(|&is| is != 0) {
|
||||
let inv = -(nmax as f32 + 0.1 * is as f32) / max;
|
||||
@@ -194,15 +201,15 @@ pub(super) fn qkx(x: &[f32], nmax: i32, w: &[f32], l: &mut [u8], p: Qkx) -> (f32
|
||||
let inv = nmax as f32 / (max - min);
|
||||
let mut scale = 1.0 / inv;
|
||||
qkx_fill(x, l, nmax, inv, min);
|
||||
let mut best = qkx_error(x, w, l, scale, min, p.mad);
|
||||
let mut best = qkx_error(x, w, l, Affine { scale, min }, p.mad);
|
||||
let mut aux = [0u8; 32];
|
||||
for is in 0..=p.nstep {
|
||||
let inv = (p.rmin + p.rdelta * is as f32 + nmax as f32) / (max - min);
|
||||
let (sl, sl2, sxl) = qkx_trial(x, w, &mut aux, nmax, inv, min);
|
||||
let (sl, sl2, sxl) = qkx_trial(x, w, &mut aux, LevelMap { nmax, inv, min });
|
||||
let det = sw * sl2 - sl * sl;
|
||||
if det > 0.0 {
|
||||
let (ds, dm) = qkx_solve([sw, sx, sl, sl2, sxl], det);
|
||||
let error = qkx_error(x, w, &aux, ds, dm, p.mad);
|
||||
let error = qkx_error(x, w, &aux, Affine { scale: ds, min: dm }, p.mad);
|
||||
if error < best {
|
||||
l.copy_from_slice(&aux[..x.len()]);
|
||||
best = error;
|
||||
@@ -251,8 +258,15 @@ fn qkx_fill(x: &[f32], l: &mut [u8], nmax: i32, inv: f32, min: f32) {
|
||||
l[i] = nearest(inv * (x[i] - min)).clamp(0, nmax) as u8;
|
||||
}
|
||||
}
|
||||
/// Weighted error of the levels `q` against `x` under the affine map `scale * q + min`.
|
||||
fn qkx_error(x: &[f32], w: &[f32], q: &[u8], scale: f32, min: f32, mad: bool) -> f32 {
|
||||
/// The affine map `scale * q + min` from levels back to values.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Affine {
|
||||
scale: f32,
|
||||
min: f32,
|
||||
}
|
||||
/// Weighted error of the levels `q` against `x` under the affine map `map`.
|
||||
fn qkx_error(x: &[f32], w: &[f32], q: &[u8], map: Affine, mad: bool) -> f32 {
|
||||
let Affine { scale, min } = map;
|
||||
let mut error = 0.0;
|
||||
for i in 0..x.len() {
|
||||
let diff = scale * q[i] as f32 + min - x[i];
|
||||
@@ -260,8 +274,16 @@ fn qkx_error(x: &[f32], w: &[f32], q: &[u8], scale: f32, min: f32, mad: bool) ->
|
||||
}
|
||||
error
|
||||
}
|
||||
/// Quantizes into `aux` at `inv`; the sums (sum w*q, sum w*q*q, sum w*q*x).
|
||||
fn qkx_trial(x: &[f32], w: &[f32], aux: &mut [u8; 32], nmax: i32, inv: f32, min: f32) -> (f32, f32, f32) {
|
||||
/// How values become levels in a qkx trial: `round(inv * (x - min))` clamped to `0..=nmax`.
|
||||
#[derive(Clone, Copy)]
|
||||
struct LevelMap {
|
||||
nmax: i32,
|
||||
inv: f32,
|
||||
min: f32,
|
||||
}
|
||||
/// Quantizes into `aux` under `map`; the sums (sum w*q, sum w*q*q, sum w*q*x).
|
||||
fn qkx_trial(x: &[f32], w: &[f32], aux: &mut [u8; 32], map: LevelMap) -> (f32, f32, f32) {
|
||||
let LevelMap { nmax, inv, min } = map;
|
||||
let (mut sl, mut sl2, mut sxl) = (0.0, 0.0, 0.0);
|
||||
for i in 0..x.len() {
|
||||
let q = nearest(inv * (x[i] - min)).clamp(0, nmax);
|
||||
|
||||
@@ -6,7 +6,8 @@
|
||||
//! cargo test --release -p leleka-native-cpu-expert --test borrowed_group_parity
|
||||
//! (the ignored `group_path_cost` prints the model-free cost of both paths)
|
||||
use leleka_native_cpu_expert::{
|
||||
BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, GateUpFormat, PreparedJob,
|
||||
BorrowedExpert, BorrowedGroup, CpuPool, DirectCpuPool, DownFormat, ExpertBytes, ExpertFormats, GateUpFormat,
|
||||
PreparedJob,
|
||||
};
|
||||
|
||||
const H: usize = 2560;
|
||||
@@ -144,11 +145,12 @@ fn prepare_owned(w: &Work, e: usize, pairs: &[(usize, usize)]) -> PreparedJob {
|
||||
let x = &w.bank[e];
|
||||
let input = gather_input(w.tokens, pairs);
|
||||
PreparedJob::new(
|
||||
w.gu,
|
||||
w.down,
|
||||
x.gate.clone().into_boxed_slice(),
|
||||
x.up.clone().into_boxed_slice(),
|
||||
x.down.clone().into_boxed_slice(),
|
||||
ExpertFormats { gu: w.gu, down: w.down },
|
||||
ExpertBytes {
|
||||
gate: x.gate.clone().into_boxed_slice(),
|
||||
up: x.up.clone().into_boxed_slice(),
|
||||
down: x.down.clone().into_boxed_slice(),
|
||||
},
|
||||
input.into_boxed_slice(),
|
||||
pairs.len(),
|
||||
)
|
||||
@@ -374,7 +376,9 @@ fn prepare_source_copy(w: &Work, e: usize, pairs: &[(usize, usize)]) -> Prepared
|
||||
(x.gate.clone().into_boxed_slice(), x.up.clone().into_boxed_slice(), x.down.clone().into_boxed_slice());
|
||||
assert!(scan(&g, gb) && scan(&u, gb) && scan(&d, db));
|
||||
let input = gather_input(w.tokens, pairs);
|
||||
PreparedJob::new(w.gu, w.down, g, u, d, input.into_boxed_slice(), pairs.len()).expect("owned job")
|
||||
let formats = ExpertFormats { gu: w.gu, down: w.down };
|
||||
PreparedJob::new(formats, ExpertBytes { gate: g, up: u, down: d }, input.into_boxed_slice(), pairs.len())
|
||||
.expect("owned job")
|
||||
}
|
||||
|
||||
fn owned_path_with_source_copy(pool: &mut CpuPool, w: &Work, out: &mut [f32]) {
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//!
|
||||
//! PROBE_WORKERS (default 15, the serve default) PROBE_ROWS (default 4, at most 8)
|
||||
//! cargo test --locked --release -p leleka-native-cpu-expert --test cpu_pool_probe -- --ignored --nocapture
|
||||
use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PreparedJob};
|
||||
use leleka_native_cpu_expert::{CpuPool, DownFormat, ExpertBytes, ExpertFormats, GateUpFormat, PreparedJob};
|
||||
|
||||
const H: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
@@ -40,15 +40,12 @@ fn new_job(gu: GateUpFormat, down: DownFormat, rows: usize) -> Result<PreparedJo
|
||||
let gsize = H / gq * gb * FF;
|
||||
let dsize = FF / dq * db * H;
|
||||
let input = vec![0.5f32; rows * H].into_boxed_slice();
|
||||
PreparedJob::new(
|
||||
gu,
|
||||
down,
|
||||
vec![0u8; gsize].into_boxed_slice(),
|
||||
vec![0u8; gsize].into_boxed_slice(),
|
||||
vec![0u8; dsize].into_boxed_slice(),
|
||||
input,
|
||||
rows,
|
||||
)
|
||||
let bytes = ExpertBytes {
|
||||
gate: vec![0u8; gsize].into_boxed_slice(),
|
||||
up: vec![0u8; gsize].into_boxed_slice(),
|
||||
down: vec![0u8; dsize].into_boxed_slice(),
|
||||
};
|
||||
PreparedJob::new(ExpertFormats { gu, down }, bytes, input, rows)
|
||||
}
|
||||
|
||||
/// Runs one job of the pair through the pool and reports whether the rows come back finite.
|
||||
|
||||
@@ -188,11 +188,12 @@ fn owned_pool() -> Option<leleka_native_cpu_expert::CpuPool> {
|
||||
/// The first expert of `bank` as one owned job over a single token row.
|
||||
fn prepared_job(bank: &[Expert]) -> leleka_native_cpu_expert::PreparedJob {
|
||||
leleka_native_cpu_expert::PreparedJob::new(
|
||||
GU,
|
||||
DOWN,
|
||||
bank[0].gate.clone().into_boxed_slice(),
|
||||
bank[0].up.clone().into_boxed_slice(),
|
||||
bank[0].down.clone().into_boxed_slice(),
|
||||
leleka_native_cpu_expert::ExpertFormats { gu: GU, down: DOWN },
|
||||
leleka_native_cpu_expert::ExpertBytes {
|
||||
gate: bank[0].gate.clone().into_boxed_slice(),
|
||||
up: bank[0].up.clone().into_boxed_slice(),
|
||||
down: bank[0].down.clone().into_boxed_slice(),
|
||||
},
|
||||
tokens(1).into_boxed_slice(),
|
||||
1,
|
||||
)
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
//! reason for the rule). Rust only: no C++ reference, no GPU. Synthetic blobs: random codes, finite FP16 scales.
|
||||
//!
|
||||
//! cargo test -p leleka-native-cpu-expert --test token_count_invariance
|
||||
use leleka_native_cpu_expert::{CpuPool, DownFormat, GateUpFormat, PreparedJob};
|
||||
use leleka_native_cpu_expert::{CpuPool, DownFormat, ExpertBytes, ExpertFormats, GateUpFormat, PreparedJob};
|
||||
|
||||
const H: usize = 2560;
|
||||
const FF: usize = 640;
|
||||
@@ -56,16 +56,13 @@ fn run(
|
||||
tokens: &[f32],
|
||||
n: usize,
|
||||
) -> Vec<f32> {
|
||||
let job = PreparedJob::new(
|
||||
gu,
|
||||
down,
|
||||
blobs[0].clone().into_boxed_slice(),
|
||||
blobs[1].clone().into_boxed_slice(),
|
||||
blobs[2].clone().into_boxed_slice(),
|
||||
tokens[..n * H].to_vec().into_boxed_slice(),
|
||||
n,
|
||||
)
|
||||
.expect("job");
|
||||
let bytes = ExpertBytes {
|
||||
gate: blobs[0].clone().into_boxed_slice(),
|
||||
up: blobs[1].clone().into_boxed_slice(),
|
||||
down: blobs[2].clone().into_boxed_slice(),
|
||||
};
|
||||
let job = PreparedJob::new(ExpertFormats { gu, down }, bytes, tokens[..n * H].to_vec().into_boxed_slice(), n)
|
||||
.expect("job");
|
||||
let done = pool
|
||||
.start(vec![job], 48 << 20)
|
||||
.expect("start")
|
||||
|
||||
@@ -166,16 +166,18 @@ fn render_str(settings: &Settings, key: String, text: &str, out: &mut Vec<(Strin
|
||||
}
|
||||
}
|
||||
|
||||
/// What names one event line: when it happened, how severe it is, who emitted it and what happened.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct EventHead<'a> {
|
||||
pub ts_ms: u64,
|
||||
pub level: Level,
|
||||
pub comp: &'a str,
|
||||
pub ev: &'a str,
|
||||
}
|
||||
|
||||
/// The line for one event (no trailing newline). Pure: the clock and the settings are arguments.
|
||||
pub fn format_line(
|
||||
settings: &Settings,
|
||||
ts_ms: u64,
|
||||
level: Level,
|
||||
comp: &str,
|
||||
ev: &str,
|
||||
fields: &[Field<'_>],
|
||||
suppressed: u64,
|
||||
) -> String {
|
||||
pub fn format_line(settings: &Settings, head: EventHead<'_>, fields: &[Field<'_>], suppressed: u64) -> String {
|
||||
let EventHead { ts_ms, level, comp, ev } = head;
|
||||
let mut rendered = render_fields(settings, fields);
|
||||
if suppressed > 0 {
|
||||
rendered.push(("suppressed".to_owned(), Rendered::Raw(suppressed.to_string())));
|
||||
|
||||
+20
-26
@@ -104,10 +104,7 @@ mod tests {
|
||||
fn a_line_is_one_json_object_with_the_fixed_prefix() {
|
||||
let line = format_line(
|
||||
&JSON,
|
||||
1_793_613_072_345,
|
||||
Level::Warn,
|
||||
"supervisor",
|
||||
"engine_exit",
|
||||
EventHead { ts_ms: 1_793_613_072_345, level: Level::Warn, comp: "supervisor", ev: "engine_exit" },
|
||||
&[
|
||||
("code", 137u32.into()),
|
||||
("reason", "signal 9".into()),
|
||||
@@ -129,10 +126,7 @@ mod tests {
|
||||
fn strings_are_escaped_and_non_finite_numbers_become_null() {
|
||||
let line = format_line(
|
||||
&JSON,
|
||||
0,
|
||||
Level::Info,
|
||||
"api",
|
||||
"x",
|
||||
EventHead { ts_ms: 0, level: Level::Info, comp: "api", ev: "x" },
|
||||
&[("msg", "a\"b\\c\nd\u{1}".into()), ("nan", f64::NAN.into())],
|
||||
0,
|
||||
);
|
||||
@@ -145,10 +139,7 @@ mod tests {
|
||||
fn the_text_format_is_key_value() {
|
||||
let line = format_line(
|
||||
&TEXT,
|
||||
0,
|
||||
Level::Info,
|
||||
"api",
|
||||
"request",
|
||||
EventHead { ts_ms: 0, level: Level::Info, comp: "api", ev: "request" },
|
||||
&[("rid", "req-1".into()), ("msg", "two words".into()), ("n", 5u64.into())],
|
||||
3,
|
||||
);
|
||||
@@ -160,10 +151,7 @@ mod tests {
|
||||
let secret_prompt = "please refactor the payment module for customer 4417-XYZ";
|
||||
let line = format_line(
|
||||
&JSON,
|
||||
0,
|
||||
Level::Info,
|
||||
"api",
|
||||
"request",
|
||||
EventHead { ts_ms: 0, level: Level::Info, comp: "api", ev: "request" },
|
||||
&[
|
||||
("prompt", secret_prompt.into()),
|
||||
("completion", "sure, here is the code".into()),
|
||||
@@ -183,7 +171,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn the_debug_opt_in_adds_lengths_only() {
|
||||
let line = format_line(&DEBUG, 0, Level::Debug, "api", "x", &[("prompt", "0123456789".into())], 0);
|
||||
let line = format_line(
|
||||
&DEBUG,
|
||||
EventHead { ts_ms: 0, level: Level::Debug, comp: "api", ev: "x" },
|
||||
&[("prompt", "0123456789".into())],
|
||||
0,
|
||||
);
|
||||
assert!(
|
||||
line.contains("\"prompt_len\":10")
|
||||
&& line.contains("\"prompt\":\"[redacted]\"")
|
||||
@@ -197,10 +190,7 @@ mod tests {
|
||||
register_secret("sk-live-0123456789abcdefghijklmnop");
|
||||
let line = format_line(
|
||||
&JSON,
|
||||
0,
|
||||
Level::Error,
|
||||
"api",
|
||||
"auth",
|
||||
EventHead { ts_ms: 0, level: Level::Error, comp: "api", ev: "auth" },
|
||||
&[
|
||||
("api_key", "sk-live-0123456789abcdefghijklmnop".into()),
|
||||
("authorization", "Bearer abc".into()),
|
||||
@@ -218,13 +208,17 @@ mod tests {
|
||||
#[test]
|
||||
fn values_and_lines_are_bounded() {
|
||||
let long = "x ".repeat(2000);
|
||||
let line =
|
||||
format_line(&JSON, 0, Level::Info, "api", "x", &[("msg", long.as_str().into()), ("a", 1u64.into())], 0);
|
||||
let line = format_line(
|
||||
&JSON,
|
||||
EventHead { ts_ms: 0, level: Level::Info, comp: "api", ev: "x" },
|
||||
&[("msg", long.as_str().into()), ("a", 1u64.into())],
|
||||
0,
|
||||
);
|
||||
assert!(line.len() < MAX_LINE, "{}", line.len());
|
||||
assert!(line.contains('~'));
|
||||
let many: Vec<(String, u64)> = (0..400).map(|i| (format!("f{i}"), u64::MAX)).collect();
|
||||
let fields: Vec<Field<'_>> = many.iter().map(|(k, v)| (k.as_str(), V::UInt(*v))).collect();
|
||||
let line = format_line(&JSON, 0, Level::Info, "api", "x", &fields, 0);
|
||||
let line = format_line(&JSON, EventHead { ts_ms: 0, level: Level::Info, comp: "api", ev: "x" }, &fields, 0);
|
||||
assert!(line.len() <= MAX_LINE && line.contains("\"trunc\":true"), "{}", line.len());
|
||||
}
|
||||
|
||||
@@ -278,8 +272,6 @@ use impl_level::clean_key;
|
||||
#[allow(unused_imports)]
|
||||
use impl_level::clean_key_dash;
|
||||
#[allow(unused_imports)]
|
||||
pub use impl_level::format_line;
|
||||
#[allow(unused_imports)]
|
||||
use impl_level::json_line;
|
||||
#[allow(unused_imports)]
|
||||
use impl_level::json_string;
|
||||
@@ -289,6 +281,8 @@ use impl_level::render_fields;
|
||||
pub use impl_level::settings;
|
||||
#[allow(unused_imports)]
|
||||
use impl_level::text_line;
|
||||
#[allow(unused_imports)]
|
||||
pub use impl_level::{EventHead, format_line};
|
||||
mod write_stderr_fn;
|
||||
#[allow(unused_imports)]
|
||||
pub use write_stderr_fn::debug;
|
||||
|
||||
@@ -67,7 +67,7 @@ pub fn emit_keyed(level: Level, comp: &str, ev: &str, key: &str, fields: &[Field
|
||||
return;
|
||||
}
|
||||
let text = Settings { format: Format::Text, ..*settings };
|
||||
write_stderr(&format_line(&text, now_ms(), level, comp, ev, fields, 0));
|
||||
write_stderr(&format_line(&text, EventHead { ts_ms: now_ms(), level, comp, ev }, fields, 0));
|
||||
return;
|
||||
}
|
||||
let now = now_ms();
|
||||
@@ -75,14 +75,14 @@ pub fn emit_keyed(level: Level, comp: &str, ev: &str, key: &str, fields: &[Field
|
||||
rate::Verdict::Allow { suppressed } => suppressed,
|
||||
rate::Verdict::Drop => return,
|
||||
};
|
||||
write_stderr(&format_line(settings, now, level, comp, ev, fields, suppressed));
|
||||
write_stderr(&format_line(settings, EventHead { ts_ms: now, level, comp, ev }, fields, suppressed));
|
||||
}
|
||||
|
||||
/// Log an event that is never sampled: lifecycle transitions, which are rare by nature.
|
||||
pub fn emit_always(level: Level, comp: &str, ev: &str, fields: &[Field<'_>]) {
|
||||
let settings = settings();
|
||||
if level >= settings.min_level {
|
||||
write_stderr(&format_line(settings, now_ms(), level, comp, ev, fields, 0));
|
||||
write_stderr(&format_line(settings, EventHead { ts_ms: now_ms(), level, comp, ev }, fields, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -97,7 +97,12 @@ pub fn trace_msg(comp: &str, msg: &str) {
|
||||
if settings.legacy {
|
||||
write_stderr(&redact::scrub(msg));
|
||||
} else {
|
||||
write_stderr(&format_line(settings, now_ms(), Level::Info, comp, "trace", &[("msg", V::Str(msg))], 0));
|
||||
write_stderr(&format_line(
|
||||
settings,
|
||||
EventHead { ts_ms: now_ms(), level: Level::Info, comp, ev: "trace" },
|
||||
&[("msg", V::Str(msg))],
|
||||
0,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -113,7 +118,7 @@ pub fn legacy_line(msg: &str) {
|
||||
/// (so it is rotated with the other logs and outlives the noisy ones), else to stderr. Returns the line length.
|
||||
pub fn record(comp: &str, ev: &str, fields: &[Field<'_>]) -> usize {
|
||||
let settings = settings();
|
||||
let line = format_line(settings, now_ms(), Level::Info, comp, ev, fields, 0);
|
||||
let line = format_line(settings, EventHead { ts_ms: now_ms(), level: Level::Info, comp, ev }, fields, 0);
|
||||
match request_sink() {
|
||||
Some(sink) => {
|
||||
sink.write_line(&line);
|
||||
|
||||
Reference in New Issue
Block a user