STRA-338 size4 s14: WIP of the slice (unverified, committed by the integrator after the workers died)

This commit is contained in:
Pavlo Ratushnyi
2026-11-07 16:35:01 +01:00
parent 5b77c18213
commit 8fd97526b5
30 changed files with 2046 additions and 1729 deletions
@@ -123,6 +123,13 @@ pub(in crate::qwen_forward) struct ChunkCommit {
origin: TargetStepOrigin,
}
/// The rows, witnesses and step origin a fresh chunk transaction starts from.
struct PromptInit {
origin: TargetStepOrigin,
rows: Vec<Row>,
witnesses: Vec<ChunkRowResidual>,
}
pub(in crate::qwen_forward) struct QwenChunkTxn<'session, 'driver> {
session: &'session mut QwenSession<'driver>,
origin: TargetStepOrigin,
@@ -182,41 +189,13 @@ mod refusal_tests {
session.layer_count = 48;
let origin = session.target_origin().unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
QwenChunkTxn {
verification: None,
next_ple: None,
next_gdn: std::array::from_fn(|_| None),
gdn_chunk: None,
next_qsa: std::array::from_fn(|_| None),
session,
origin,
chunk: Rc::new(()),
rows: vec![Row { token: token(3), position, predecessors: [-1, -1], input: None, completed: 0 }],
witnesses: Vec::new(),
next_layer: 0,
next_row: 0,
batch_layer: None,
batch_rows: Vec::new(),
batch_completed: 0,
attention_layer: None,
attention_next: 0,
attention_sources: Vec::new(),
attention_authorized: None,
known_next: Some(token(4)),
output: None,
finished: false,
aborted: false,
end: 1,
windowed: false,
micro_cursor: 0,
active_micro: None,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_micro_width: 64,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_window_journal: Vec::new(),
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_partial_words: 0,
}
let row = Row { token: token(3), position, predecessors: [-1, -1], input: None, completed: 0 };
let init = PromptInit { origin, rows: vec![row], witnesses: Vec::new() };
let mut txn = QwenChunkTxn::fresh(session, init, (Some(token(4)), 1, false));
txn.next_ple = None;
txn.next_gdn = std::array::from_fn(|_| None);
txn.next_qsa = std::array::from_fn(|_| None);
txn
}
#[test]
fn chunk_phase_reader_refuses_aborted_and_reset_session_authority() {
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl GdnChunkStart, impl GdnChunkRow, impl GdnChunkMicro, fn same_window_proof, impl GdnChunkSeal, impl GdnChunkStart ....
//! Moved out of the parent module by STRA-338: impl GdnChunkStart, impl GdnChunkRow, impl GdnChunkMicro, fn
//! same_window_proof, impl GdnChunkSeal, impl GdnChunkStart ....
#[allow(unused_imports)]
use super::*;
@@ -59,7 +59,7 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
let (rows, witnesses) = prompt_rows(session, tokens, context_bound)?;
Ok(Self::fresh(session, PromptInit { origin, rows, witnesses }, (known_next, end, windowed)))
}
fn fresh(
pub(in crate::qwen_forward::session::chunk) fn fresh(
session: &'session mut QwenSession<'driver>,
init: PromptInit,
(known_next, end, windowed): (Option<TokenId>, u64, bool),
@@ -160,12 +160,6 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
}
}
/// The rows, witnesses and step origin a fresh chunk transaction starts from.
struct PromptInit {
origin: TargetStepOrigin,
rows: Vec<Row>,
witnesses: Vec<ChunkRowResidual>,
}
/// The step origin of a prompt of `count` tokens, which must fit the bound session (64 rows, 256 windowed).
fn prompt_origin(
session: &QwenSession<'_>,
@@ -59,20 +59,27 @@ impl<'session, 'driver> QwenChunkTxn<'session, 'driver> {
/// The window is exactly the minted capability, the range is fully computed and no phase is in flight.
fn check_micro_close(&self, window: &ChunkMicroWindow, first: usize, end: usize) -> Result<()> {
let active = self.active_micro.as_ref().ok_or(Error::IdentityMismatch)?;
if !Rc::ptr_eq(&self.chunk, &window.chunk)
|| !Rc::ptr_eq(&active.proof, &window.proof)
|| window.first != first
|| window.end != end
|| window.layer != active.layer
|| self.next_row != end
|| self.attention_next != end
|| self.phase_in_flight()
|| self.rows[first..end].iter().any(|r| r.completed != self.next_layer + 1)
{
if !self.is_minted_window(active, window, (first, end)) || !self.window_fully_computed(first, end) {
return Err(Error::IdentityMismatch);
}
Ok(())
}
/// The window is the capability minted for the active micro window over exactly this range.
fn is_minted_window(&self, active: &ActiveMicroWindow, window: &ChunkMicroWindow, span: (usize, usize)) -> bool {
let (first, end) = span;
Rc::ptr_eq(&self.chunk, &window.chunk)
&& Rc::ptr_eq(&active.proof, &window.proof)
&& window.first == first
&& window.end == end
&& window.layer == active.layer
}
/// Every row of the range is computed through the current layer and no phase is in flight.
fn window_fully_computed(&self, first: usize, end: usize) -> bool {
self.next_row == end
&& self.attention_next == end
&& !self.phase_in_flight()
&& self.rows[first..end].iter().all(|r| r.completed == self.next_layer + 1)
}
/// The infallible cursor transition after a window closed; the last window moves to the next layer.
fn advance_micro(&mut self, end: usize) {
self.active_micro = None;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl VerifiedTargetPrefix, fn verification_extra_charge, fn greedy_prefix.
//! Moved out of the parent module by STRA-338: impl VerifiedTargetPrefix, fn verification_extra_charge, fn
//! greedy_prefix.
#[allow(unused_imports)]
use super::*;
@@ -48,126 +48,138 @@ fn ple_gdn_fixture<'a>(session: &'a mut QwenSession<'static>) -> QwenChunkTxn<'a
let origin = session.target_origin().unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
let input = crate::qwen_forward::input::InputReady::test_fixture(token(3), position, binding);
QwenChunkTxn {
verification: Some(VerificationJournal {
states: vec![PrefixState {
ple: None,
gdn: std::array::from_fn(|_| None),
device_gdn: std::array::from_fn(|_| None),
qsa: std::array::from_fn(|_| None),
head: None,
}],
device_lease: None,
}),
next_ple: None,
next_gdn: std::array::from_fn(|_| None),
gdn_chunk: None,
next_qsa: std::array::from_fn(|_| None),
session,
origin,
chunk: Rc::new(()),
rows: vec![Row {
token: token(3),
position,
predecessors: [-1, -1],
input: Some(Rc::new(input)),
completed: 1,
}],
witnesses: Vec::new(),
next_layer: 1,
next_row: 0,
batch_layer: None,
batch_rows: Vec::new(),
batch_completed: 0,
attention_layer: None,
attention_next: 0,
attention_sources: Vec::new(),
attention_authorized: None,
known_next: None,
output: None,
finished: false,
aborted: false,
end: 1,
windowed: true,
micro_cursor: 0,
active_micro: None,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_micro_width: 64,
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_window_journal: Vec::new(),
#[cfg(all(test, any(target_os = "linux", target_os = "windows"), target_arch = "x86_64"))]
test_partial_words: 0,
let row = Row { token: token(3), position, predecessors: [-1, -1], input: Some(Rc::new(input)), completed: 1 };
let init = PromptInit { origin, rows: vec![row], witnesses: Vec::new() };
let mut txn = QwenChunkTxn::fresh(session, init, (None, 1, true));
txn.verification = Some(single_state_journal());
txn.next_ple = None;
txn.next_gdn = std::array::from_fn(|_| None);
txn.next_qsa = std::array::from_fn(|_| None);
txn.next_layer = 1;
txn
}
fn single_state_journal() -> VerificationJournal {
let state = PrefixState {
ple: None,
gdn: std::array::from_fn(|_| None),
device_gdn: std::array::from_fn(|_| None),
qsa: std::array::from_fn(|_| None),
head: None,
};
VerificationJournal { states: vec![state], device_lease: None }
}
type Txn<'a> = QwenChunkTxn<'a, 'static>;
fn layer_of(index: u64) -> LayerId {
LayerId::new(index, Dimension::new(48).unwrap()).unwrap()
}
fn row_position() -> Position {
Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap()
}
/// Stages the next PLE prior of `layer` as the transaction's own and returns it.
fn stage_next_ple(txn: &mut Txn<'_>, layer: LayerId, position: Position) -> PlePrior {
use crate::qwen_forward::input::PlePending;
let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap();
let pending = PlePending::test_next(&prior, &TokenLayer::new(token(3), position, layer)).unwrap();
pending.validate(&prior, TokenLayer::new(token(3), position, layer)).unwrap();
let next = pending.into_prior();
txn.next_ple = Some(next.clone());
next
}
fn assert_ple_recorded_without_gdn_prior(txn: &mut Txn<'_>, layer: LayerId, position: Position, next: &PlePrior) {
// Original blanket guard still refuses host GDN prior publication.
assert_eq!(txn.verification_row_position(0, position), Err(Error::IdentityMismatch));
assert_eq!(txn.record_verification_prior(0, layer, position), Err(Error::IdentityMismatch));
assert_eq!(txn.record_verification_ple(0, position), Ok(()));
assert!(txn.verification.as_ref().unwrap().states[0].ple.as_ref().unwrap().same_state(next));
assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none());
assert_eq!(txn.gdn_chunk.as_ref().unwrap().accepted, 0);
}
/// Replaces the chunk's GDN anchor by a copy with one field changed (`refusal` 1: layer, 2: end, 3: count).
fn replace_anchor(txn: &mut Txn<'_>, start: &GdnChunkStart, refusal: u32) {
let anchor = &start.0;
txn.gdn_chunk.as_mut().unwrap().start = GdnChunkStart(Rc::new(GdnChunkAnchor {
binding: anchor.binding.clone(),
chunk: anchor.chunk.clone(),
prior: anchor.prior.clone(),
layer: if refusal == 1 { layer_of(0) } else { anchor.layer },
first: anchor.first,
end: if refusal == 2 { 2 } else { anchor.end },
count: if refusal == 3 { 2 } else { anchor.count },
}));
}
/// Refusals 0 to 7 break the chunk, anchor and phase cursors.
fn break_phase_state(txn: &mut Txn<'_>, refusal: u32, start: &GdnChunkStart) {
match refusal {
0 => txn.chunk = Rc::new(()),
1 | 2 | 3 => replace_anchor(txn, start, refusal),
4 => txn.attention_layer = None,
5 => txn.attention_next = 1,
6 => txn.rows[0].completed = 0,
7 => txn.next_row = 1,
_ => unreachable!(),
}
}
/// Refusals 8 to 15 break the journal, the PLE owner, the session or the phase authority.
fn break_authority(txn: &mut Txn<'_>, refusal: u32, layer: LayerId, position: Position) {
use crate::qwen_forward::input::{PleOwner, PlePending};
match refusal {
8 => txn.gdn_chunk.as_mut().unwrap().accepted = 1,
9 => txn.rows[0].position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(),
10 => {
let foreign = PlePrior::zero(txn.session.binding.clone(), &PleOwner::new()).unwrap();
txn.next_ple = Some(
PlePending::test_next(&foreign, &TokenLayer::new(token(3), position, layer)).unwrap().into_prior(),
);
}
11 => txn.aborted = true,
12 => txn.session.reset().unwrap(),
13 => txn.active_micro = None,
14 => txn.batch_layer = Some(layer),
15 => txn.attention_authorized = Some(0),
_ => unreachable!(),
}
}
fn refuse_with(refusal: u32) {
use crate::model_binding::qwen4exp_input::BindingIdentity;
let (layer, position) = (layer_of(1), row_position());
let mut session = QwenSession::test_session(BindingIdentity::test_identity());
let mut txn = ple_gdn_fixture(&mut session);
// Production constructors mint this actual session's anchor/window.
let start = txn.begin_gdn_chunk(layer).unwrap();
let window = txn.open_micro_window(layer).unwrap();
txn.attention_layer = Some(layer);
let next = stage_next_ple(&mut txn, layer, position);
assert_ple_recorded_without_gdn_prior(&mut txn, layer, position, &next);
// Restore the empty private PLE journal slot before each refusal.
txn.verification.as_mut().unwrap().states[0].ple = None;
if refusal < 8 {
break_phase_state(&mut txn, refusal, &start);
} else {
break_authority(&mut txn, refusal, layer, position);
}
let error = txn.record_verification_ple(0, position).unwrap_err();
assert!(matches!(error, Error::IdentityMismatch | Error::Unsupported(Stage::Session)));
assert!(txn.verification.as_ref().unwrap().states[0].ple.is_none());
assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none());
drop(window);
}
#[test]
fn ple_journal_admits_only_current_layer_one_gdn_attention_phase() {
use crate::model_binding::qwen4exp_input::BindingIdentity;
use crate::qwen_forward::input::{PleOwner, PlePending};
let layer = LayerId::new(1, Dimension::new(48).unwrap()).unwrap();
let position = Position::new(0, crate::qwen_forward::contract::position_dimension()).unwrap();
use crate::qwen_forward::input::PlePending;
let (layer, position) = (layer_of(1), row_position());
for refusal in 0..16 {
let mut session = QwenSession::test_session(BindingIdentity::test_identity());
let mut txn = ple_gdn_fixture(&mut session);
// Production constructors mint this actual session's anchor/window.
let start = txn.begin_gdn_chunk(layer).unwrap();
let window = txn.open_micro_window(layer).unwrap();
txn.attention_layer = Some(layer);
let prior = PlePrior::zero(txn.session.binding.clone(), &txn.session.ple_owner).unwrap();
let pending = PlePending::test_next(&prior, &TokenLayer::new(token(3), position, layer)).unwrap();
pending.validate(&prior, TokenLayer::new(token(3), position, layer)).unwrap();
let next = pending.into_prior();
txn.next_ple = Some(next.clone());
// Original blanket guard still refuses host GDN prior publication.
assert_eq!(txn.verification_row_position(0, position), Err(Error::IdentityMismatch));
assert_eq!(txn.record_verification_prior(0, layer, position), Err(Error::IdentityMismatch));
assert_eq!(txn.record_verification_ple(0, position), Ok(()));
assert!(txn.verification.as_ref().unwrap().states[0].ple.as_ref().unwrap().same_state(&next));
assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none());
assert_eq!(txn.gdn_chunk.as_ref().unwrap().accepted, 0);
// Restore the empty private PLE journal slot before each refusal.
txn.verification.as_mut().unwrap().states[0].ple = None;
match refusal {
0 => txn.chunk = Rc::new(()),
1 | 2 | 3 => {
let anchor = &start.0;
txn.gdn_chunk.as_mut().unwrap().start = GdnChunkStart(Rc::new(GdnChunkAnchor {
binding: anchor.binding.clone(),
chunk: anchor.chunk.clone(),
prior: anchor.prior.clone(),
layer: if refusal == 1 {
LayerId::new(0, Dimension::new(48).unwrap()).unwrap()
} else {
anchor.layer
},
first: anchor.first,
end: if refusal == 2 { 2 } else { anchor.end },
count: if refusal == 3 { 2 } else { anchor.count },
}));
}
4 => txn.attention_layer = None,
5 => txn.attention_next = 1,
6 => txn.rows[0].completed = 0,
7 => txn.next_row = 1,
8 => txn.gdn_chunk.as_mut().unwrap().accepted = 1,
9 => txn.rows[0].position = Position::new(1, crate::qwen_forward::contract::position_dimension()).unwrap(),
10 => {
let foreign = PlePrior::zero(txn.session.binding.clone(), &PleOwner::new()).unwrap();
txn.next_ple = Some(
PlePending::test_next(&foreign, &TokenLayer::new(token(3), position, layer)).unwrap().into_prior(),
);
}
11 => txn.aborted = true,
12 => txn.session.reset().unwrap(),
13 => txn.active_micro = None,
14 => txn.batch_layer = Some(layer),
15 => txn.attention_authorized = Some(0),
_ => unreachable!(),
}
let error = txn.record_verification_ple(0, position).unwrap_err();
assert!(matches!(error, Error::IdentityMismatch | Error::Unsupported(Stage::Session)));
assert!(txn.verification.as_ref().unwrap().states[0].ple.is_none());
assert!(txn.verification.as_ref().unwrap().states[0].gdn[1].is_none());
drop(window);
refuse_with(refusal);
}
// The absent-GDN path preserves its existing position/owner/slot rules.
let mut session = QwenSession::test_session(BindingIdentity::test_identity());
@@ -4,7 +4,8 @@
use super::*;
impl OriginalDraftCheckpoint {
/// Host bytes of the ring image (prefix-cache accounting; pages shared with neighbouring points are counted in full).
/// Host bytes of the ring image (prefix-cache accounting; pages shared with neighbouring points are counted in
/// full).
pub(in crate::qwen_forward) fn host_bytes(&self) -> usize {
self.snapshot.encoded_bytes()
}
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl OriginalDraftSession (2), impl OriginalDraftPublication, impl Drop_for_OriginalDraftSession.
//! Moved out of the parent module by STRA-338: impl OriginalDraftSession (2), impl OriginalDraftPublication, impl
//! Drop_for_OriginalDraftSession.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl OriginalPromptInput, impl QwenSession, impl QwenSession, impl OriginalSessionCheckpoint, impl QwenSession, impl ParkedSession ....
//! Moved out of the parent module by STRA-338: impl OriginalPromptInput, impl QwenSession, impl QwenSession, impl
//! OriginalSessionCheckpoint, impl QwenSession, impl ParkedSession ....
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl OriginalPromptInput, impl QwenSession, impl QwenSession, impl OriginalSessionCheckpoint.
//! Moved out of the parent module by STRA-338: impl OriginalPromptInput, impl QwenSession, impl QwenSession, impl
//! OriginalSessionCheckpoint.
#[allow(unused_imports)]
use super::*;
@@ -1,4 +1,5 @@
//! Moved out of the parent module by STRA-338: impl QwenSession, impl ParkedSession, impl ParkedBlock, impl QwenSession.
//! Moved out of the parent module by STRA-338: impl QwenSession, impl ParkedSession, impl ParkedBlock, impl
//! QwenSession.
#[allow(unused_imports)]
use super::*;
@@ -111,7 +112,8 @@ impl<'driver> QwenSession<'driver> {
None => Ok(()),
}
}
/// Every recurrent prior was just replaced: nothing lags any more, and the resident witnesses are the restored ones.
/// Every recurrent prior was just replaced: nothing lags any more, and the resident witnesses are the restored
/// ones.
fn adopt_restored(
&mut self,
(next_position, predecessors): (u64, [i32; 2]),
@@ -66,29 +66,36 @@ fn base_at_position_zero_is_the_zero_priors_and_publication_advances_exactly_the
assert_eq!((origin.next_position(), session.predecessors), (4, [13, 14]));
}
#[test]
fn a_refused_publication_leaves_the_session_untouched() {
let mut session = session(&[0, 1], true);
fn assert_wrong_counts_refused(session: &mut QwenSession<'static>) {
// wrong row count for the priors: the priors end at 2, the accepted prefix at 3
let lineage = state_after(&session, 2);
let lineage = state_after(session, 2);
assert_eq!(session.publish_original_verified(&[1, 2, 3], 1000, lineage).err(), Some(Error::IdentityMismatch));
// beyond the context bound
let lineage = state_after(&session, 2);
let lineage = state_after(session, 2);
assert_eq!(session.publish_original_verified(&[1, 2], 1, lineage).err(), Some(Error::InvalidPosition));
}
fn assert_missing_priors_refused(session: &mut QwenSession<'static>) {
// a missing GDN prior
let mut lineage = state_after(&session, 1);
let mut lineage = state_after(session, 1);
lineage.gdn[1] = None;
assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch));
// a missing PLE prior while PLE is required, and a spurious one while it is not
let mut lineage = state_after(&session, 1);
let mut lineage = state_after(session, 1);
lineage.ple = None;
assert_eq!(session.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch));
let mut plain = self::session(&[0], false);
}
fn assert_spurious_ple_refused() {
let mut plain = session(&[0], false);
let mut lineage = state_after(&plain, 1);
lineage.ple = Some(PlePrior::zero(plain.binding.clone(), &plain.ple_owner).unwrap());
assert_eq!(plain.publish_original_verified(&[1], 1000, lineage).err(), Some(Error::IdentityMismatch));
}
fn assert_bad_token_and_window_shapes_refused(session: &mut QwenSession<'static>) {
// out-of-range token / window shape
let lineage = state_after(&session, 1);
let lineage = state_after(session, 1);
assert_eq!(session.publish_original_verified(&[248_320], 1000, lineage).err(), Some(Error::InvalidToken));
assert_eq!(
session.publish_original_verified(&[], 1000, OriginalVerifiedLineage::empty()).err(),
@@ -98,6 +105,15 @@ fn a_refused_publication_leaves_the_session_untouched() {
session.publish_original_verified(&[1; 9], 1000, OriginalVerifiedLineage::empty()).err(),
Some(Error::IdentityMismatch)
);
}
#[test]
fn a_refused_publication_leaves_the_session_untouched() {
let mut session = session(&[0, 1], true);
assert_wrong_counts_refused(&mut session);
assert_missing_priors_refused(&mut session);
assert_spurious_ple_refused();
assert_bad_token_and_window_shapes_refused(&mut session);
assert_eq!((session.next_position, session.predecessors), (0, [-1, -1]));
assert!(session.ple_state.is_none() && session.gdn_states.iter().all(Option::is_none));
}
@@ -121,6 +137,19 @@ fn priors_of_another_owner_or_layer_are_refused() {
assert_eq!(other.next_position, 1);
}
fn assert_end_of_phase_publication_closes_the_lag(session: &mut QwenSession<'static>) {
// priors at the wrong position are refused; the exact position closes the lag
let wrong = state_after(session, 5);
assert_eq!(session.publish_original_resident_state(wrong.gdn, wrong.ple).err(), Some(Error::IdentityMismatch));
assert_eq!(session.original_state_lag(), Some(0));
let right = state_after(session, 6);
session.publish_original_resident_state(right.gdn, right.ple).unwrap();
assert_eq!(session.original_state_lag(), None);
let base = session.original_verified_base().unwrap();
assert_eq!((base.position, base.state_position), (6, 6));
assert_eq!(base.gdn[0].as_ref().unwrap().next_position(), 6);
}
#[test]
fn rounds_advance_the_lineage_while_the_recurrent_state_lags_and_the_end_of_phase_publication_closes_it() {
let mut session = session(&[0, 1], true);
@@ -135,16 +164,7 @@ fn rounds_advance_the_lineage_while_the_recurrent_state_lags_and_the_end_of_phas
// the host priors still stand at 0 and the base says so
let base = session.original_verified_base().unwrap();
assert_eq!((base.position, base.state_position), (6, 0));
// priors at the wrong position are refused; the exact position closes the lag
let wrong = state_after(&session, 5);
assert_eq!(session.publish_original_resident_state(wrong.gdn, wrong.ple).err(), Some(Error::IdentityMismatch));
assert_eq!(session.original_state_lag(), Some(0));
let right = state_after(&session, 6);
session.publish_original_resident_state(right.gdn, right.ple).unwrap();
assert_eq!(session.original_state_lag(), None);
let base = session.original_verified_base().unwrap();
assert_eq!((base.position, base.state_position), (6, 6));
assert_eq!(base.gdn[0].as_ref().unwrap().next_position(), 6);
assert_end_of_phase_publication_closes_the_lag(&mut session);
// nothing to close any more
let again = state_after(&session, 1);
assert_eq!(session.publish_original_resident_state(again.gdn, again.ple).err(), Some(Error::IdentityMismatch));
@@ -1,20 +1,23 @@
//! Per-round checks over the request's whole token history, made proportional to what changed since the last round.
//!
//! The serve loop keeps the committed tokens of a request twice (the controller's `consumed` and the ledger's `committed`) and,
//! every round, authenticated them against each other and range-checked all of them again: five passes over up to 262,144 `i32`
//! per round (about 0.15 ms at 247k tokens, growing linearly with the context). Both sequences only ever GROW inside one request
//! (a token is appended when a window commits; nothing rewrites a committed token), so a pass that succeeded over the first `n`
//! tokens of a buffer stays true for them and only the tokens appended since need examining.
//! The serve loop keeps the committed tokens of a request twice (the controller's `consumed` and the ledger's
//! `committed`) and, every round, authenticated them against each other and range-checked all of them again: five
//! passes over up to 262,144 `i32` per round (about 0.15 ms at 247k tokens, growing linearly with the context). Both
//! sequences only ever GROW inside one request (a token is appended when a window commits; nothing rewrites a committed
//! token), so a pass that succeeded over the first `n` tokens of a buffer stays true for them and only the tokens
//! appended since need examining.
//!
//! A [`PrefixMemo`] records `(address, length)` of the buffer a check last passed over, plus three of its tokens (first, middle, last)
//! as a cheap identity probe against a different buffer that happens to reuse the address. The next check starts at that length when
//! it sees the same address, the same probe tokens and a buffer at least as long (a reallocated, shorter or different buffer starts
//! over at 0), and every `FULL_EVERY`-th use examines everything again, so an in-place rewrite of an old token (nothing does this; the
//! owners are append-only) would still be found within a bounded number of rounds. The checks are assertions: an answer that passes is the
//! same answer as before; the only difference is that a corrupted old prefix, which cannot happen through the owners' interfaces,
//! is reported up to `FULL_EVERY` rounds later instead of at once.
//! A [`PrefixMemo`] records `(address, length)` of the buffer a check last passed over, plus three of its tokens
//! (first, middle, last) as a cheap identity probe against a different buffer that happens to reuse the address. The
//! next check starts at that length when it sees the same address, the same probe tokens and a buffer at least as long
//! (a reallocated, shorter or different buffer starts over at 0), and every `FULL_EVERY`-th use examines everything
//! again, so an in-place rewrite of an old token (nothing does this; the owners are append-only) would still be found
//! within a bounded number of rounds. The checks are assertions: an answer that passes is the same answer as before;
//! the only difference is that a corrupted old prefix, which cannot happen through the owners' interfaces, is reported
//! up to `FULL_EVERY` rounds later instead of at once.
/// How many consecutive partial checks may pass before the whole history is examined again (about 1/32 of the former cost).
/// How many consecutive partial checks may pass before the whole history is examined again (about 1/32 of the former
/// cost).
pub(crate) const FULL_EVERY: u32 = 32;
/// The `key` of an equality memo (a range memo is keyed by its vocabulary, which is positive).
const EQUAL_KEY: i32 = -1;
@@ -25,7 +28,8 @@ pub(crate) struct PrefixMemo {
len: usize,
partial: u32,
probe: [i32; 3],
/// What the remembered pass checked (the vocabulary of a range check): a pass for another criterion does not carry over.
/// What the remembered pass checked (the vocabulary of a range check): a pass for another criterion does not carry
/// over.
key: i32,
}
@@ -40,7 +44,8 @@ impl PrefixMemo {
pub(crate) const fn new() -> Self {
Self { address: 0, len: 0, partial: 0, probe: [0; 3], key: 0 }
}
/// The index the next check of `tokens` would start at: everything before it passed on an earlier use of the same buffer.
/// The index the next check of `tokens` would start at: everything before it passed on an earlier use of the same
/// buffer.
#[cfg(test)]
pub(crate) fn start(&self, tokens: &[i32]) -> usize {
self.start_for(tokens, self.key)
@@ -80,8 +85,8 @@ impl PrefixMemo {
self.passed_for(tokens, start, vocabulary);
true
}
/// `a == b`, examining only what the memo has not seen. The memo follows `a` (the longer-lived buffer is the caller's choice);
/// `b` is the other owner's buffer, only appended to as well.
/// `a == b`, examining only what the memo has not seen. The memo follows `a` (the longer-lived buffer is the
/// caller's choice); `b` is the other owner's buffer, only appended to as well.
pub(crate) fn equal(&mut self, a: &[i32], b: &[i32]) -> bool {
if a.len() != b.len() {
return false;
@@ -170,39 +175,50 @@ mod tests {
assert!(round > 1, "a partial pass does not re-read the old prefix");
}
fn xorshift(x: &mut u64) -> u64 {
*x ^= *x << 13;
*x ^= *x >> 7;
*x ^= *x << 17;
*x
}
/// Appends the same 1 to 7 random tokens to both buffers.
fn grow_both(a: &mut Vec<i32>, b: &mut Vec<i32>, state: &mut u64) {
let grow = 1 + (xorshift(state) % 7) as usize;
for _ in 0..grow {
let t = (xorshift(state) % 1000) as i32;
a.push(t);
b.push(t);
}
}
fn assert_equality_follows_the_slices(m: &mut PrefixMemo, a: &[i32], b: &mut Vec<i32>, at: (i32, i32)) {
let (case, round) = at;
// a different token appended to one side only is a mismatch of the examined tail
if round % 17 == 5 {
let n = a.len();
b[n - 1] ^= 1;
assert!(!m.equal(a, b), "case {case} round {round}: the new tail differs");
b[n - 1] ^= 1;
}
assert!(m.equal(a, b), "case {case} round {round}: equal buffers");
assert_eq!(m.equal(a, b), a == b.as_slice());
// lengths differ: never equal, whatever was remembered
b.push(1);
assert!(!m.equal(a, b));
b.pop();
}
#[test]
fn equality_examines_the_tail_and_agrees_with_the_slice_comparison_on_random_growth() {
let mut x = 0x2545F4914F6CDD1Du64;
let mut next = move || {
x ^= x << 13;
x ^= x >> 7;
x ^= x << 17;
x
};
let mut state = 0x2545F4914F6CDD1Du64;
for case in 0..50 {
let mut a: Vec<i32> = Vec::with_capacity(5000);
let mut b: Vec<i32> = Vec::with_capacity(5000);
let mut m = PrefixMemo::new();
for round in 0..200 {
let grow = 1 + (next() % 7) as usize;
for _ in 0..grow {
let t = (next() % 1000) as i32;
a.push(t);
b.push(t);
}
// a different token appended to one side only is a mismatch of the examined tail
if round % 17 == 5 {
let n = a.len();
b[n - 1] ^= 1;
assert!(!m.equal(&a, &b), "case {case} round {round}: the new tail differs");
b[n - 1] ^= 1;
}
assert!(m.equal(&a, &b), "case {case} round {round}: equal buffers");
assert_eq!(m.equal(&a, &b), a == b);
// lengths differ: never equal, whatever was remembered
b.push(1);
assert!(!m.equal(&a, &b));
b.pop();
grow_both(&mut a, &mut b, &mut state);
assert_equality_follows_the_slices(&mut m, &a, &mut b, (case, round));
}
}
}
+23 -16
View File
@@ -1,20 +1,25 @@
//! Start-up metadata lines of the serving engine: `leleka-serve meta: <section> v=1 key=value ...` (STRA-325).
//!
//! Operator log only. The lines are written to stderr beside the `leleka-serve cpu:` / `gpu:` kernel lines, change no state and no result, and
//! are machine-parsable: one line per section, the section name is the first token after `meta:`, then `key=value` tokens separated by single
//! blanks. A value never contains a blank or `=` (see `token`). The first token after the section is `v=1`; a change of a key or of its meaning
//! raises it. Sections:
//! Operator log only. The lines are written to stderr beside the `leleka-serve cpu:` / `gpu:` kernel lines, change no
//! state and no result, and are machine-parsable: one line per section, the section name is the first token after
//! `meta:`, then `key=value` tokens separated by single blanks. A value never contains a blank or `=` (see `token`).
//! The first token after the section is `v=1`; a change of a key or of its meaning raises it. Sections:
//!
//! * `build` - the build id: git commit, dirty flag, target triple, cargo features, cargo profile, plus the effective profile name and the hashes
//! `profile_sha256` (of the profile file, handed in by the launcher through `LELEKA_PROFILE_SHA256`, `unset` without one) and `values_sha256`
//! (of the effective tuning values of the `config` section, computed here).
//! * `model` - the model digest as RECORDED (the pinned constant of this build; nothing is hashed here), and size and mtime of the model files.
//! * `config` - the effective tuning: context, prompt chunk, prefix block and tail, cpu workers, KV mode, expert tier, speculation.
//! * `cache` - the engine's own caches at the moment the stack opened: prefix-cache entries and bytes, `engine_state=EMPTY|WARM`. The OS page
//! cache is not the engine's to know and is not probed here (the runner records it, `scripts/e2e/evidence/engine_meta_lines.md`).
//! * `build` - the build id: git commit, dirty flag, target triple, cargo features, cargo profile, plus the effective
//! profile name and the hashes `profile_sha256` (of the profile file, handed in by the launcher through
//! `LELEKA_PROFILE_SHA256`, `unset` without one) and `values_sha256` (of the effective tuning values of the `config`
//! section, computed here).
//! * `model` - the model digest as RECORDED (the pinned constant of this build; nothing is hashed here), and size and
//! mtime of the model files.
//! * `config` - the effective tuning: context, prompt chunk, prefix block and tail, cpu workers, KV mode, expert tier,
//! speculation.
//! * `cache` - the engine's own caches at the moment the stack opened: prefix-cache entries and bytes,
//! `engine_state=EMPTY|WARM`. The OS page cache is not the engine's to know and is not probed here (the runner
//! records it, `scripts/e2e/evidence/engine_meta_lines.md`).
//!
//! The field list and its use by `scripts/e2e/evidence/capture.py` are in `scripts/e2e/evidence/engine_meta_lines.md`; the golden sample
//! `scripts/e2e/evidence/golden/engine_meta_sample.txt` is pinned by a test here and parsed by a test there.
//! The field list and its use by `scripts/e2e/evidence/capture.py` are in `scripts/e2e/evidence/engine_meta_lines.md`;
//! the golden sample `scripts/e2e/evidence/golden/engine_meta_sample.txt` is pinned by a test here and parsed by a test
//! there.
use sha2::{Digest, Sha256};
use std::path::{Path, PathBuf};
@@ -68,8 +73,9 @@ impl BuildInfo {
}
}
/// The profile the launcher selected. The engine itself only receives the profile's VALUES (arguments and environment); the name and the hash
/// of the file come from `LELEKA_PROFILE` and `LELEKA_PROFILE_SHA256` when the launcher sets them. Unset is printed as `none` / `unset`.
/// The profile the launcher selected. The engine itself only receives the profile's VALUES (arguments and environment);
/// the name and the hash of the file come from `LELEKA_PROFILE` and `LELEKA_PROFILE_SHA256` when the launcher sets
/// them. Unset is printed as `none` / `unset`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub(crate) struct ProfileInfo {
pub(crate) name: Option<String>,
@@ -168,7 +174,8 @@ impl ConfigFacts {
("pcie_frac", self.pcie_frac.to_string()),
]
}
/// SHA-256 of `key=value\n` for every field (lower-case hex). Two runs with the same effective values have the same hash.
/// SHA-256 of `key=value\n` for every field (lower-case hex). Two runs with the same effective values have the same
/// hash.
pub(crate) fn values_sha256(&self) -> String {
let mut text = String::new();
for (key, value) in self.fields() {
@@ -61,7 +61,8 @@ pub(super) fn cache() -> CacheFacts {
}
}
/// The golden sample is shared with `scripts/e2e/evidence` (capture.py parses the same file): this pins the format of every line.
/// The golden sample is shared with `scripts/e2e/evidence` (capture.py parses the same file): this pins the format of
/// every line.
#[test]
fn the_meta_lines_match_the_golden_sample_byte_for_byte() {
let mut lines = startup_lines(&build(), &profile(), &model(), &config());
@@ -73,31 +74,37 @@ fn the_meta_lines_match_the_golden_sample_byte_for_byte() {
assert_eq!(produced, golden_meta);
}
fn expected_build_line() -> String {
format!(
"meta: build v=1 commit={COMMIT} dirty=0 target=x86_64-unknown-linux-gnu features=sm86 \
cargo_profile=release profile=rtx5090-32g profile_sha256={PROFILE_SHA} values_sha256={}",
config().values_sha256()
)
}
fn expected_model_line() -> String {
format!(
"meta: model v=1 digest={DIGEST} mapping={MODEL_DIGEST_MAPPING} verify=recorded-no-rehash files=2 \
file0=model-00001-of-00002.gguf:54817524224:1790000000 \
file1=model-00002-of-00002.gguf:28800138432:1790000001"
)
}
const EXPECTED_CONFIG_LINE: &str = "meta: config v=1 context_tokens=262144 kv=int8 slots=1 batch=8192 \
speculation=mtp spec_min_p=0 chunk=8192 prefix_cache=on prefix_block=8192 prefix_tail=reply cpu_workers=15 \
kv_resident=32768 expert_tier=auto expert_per_layer=1 expert_profile=1 pcie_frac=0.45";
const EXPECTED_CACHE_LINE: &str = "meta: cache v=1 engine_state=EMPTY prefix_cache=on prefix_entries=0 \
prefix_blocks=0 prefix_used_bytes=0 prefix_budget_bytes=5713000000 os_page_cache=not-probed";
#[test]
fn the_lines_are_exact() {
let lines = startup_lines(&build(), &profile(), &model(), &config());
assert_eq!(lines.len(), 3);
assert_eq!(
lines[0],
format!(
"meta: build v=1 commit={COMMIT} dirty=0 target=x86_64-unknown-linux-gnu features=sm86 cargo_profile=release profile=rtx5090-32g profile_sha256={PROFILE_SHA} values_sha256={}",
config().values_sha256()
)
);
assert_eq!(
lines[1],
format!(
"meta: model v=1 digest={DIGEST} mapping={MODEL_DIGEST_MAPPING} verify=recorded-no-rehash files=2 file0=model-00001-of-00002.gguf:54817524224:1790000000 file1=model-00002-of-00002.gguf:28800138432:1790000001"
)
);
assert_eq!(
lines[2],
"meta: config v=1 context_tokens=262144 kv=int8 slots=1 batch=8192 speculation=mtp spec_min_p=0 chunk=8192 prefix_cache=on prefix_block=8192 prefix_tail=reply cpu_workers=15 kv_resident=32768 expert_tier=auto expert_per_layer=1 expert_profile=1 pcie_frac=0.45"
);
assert_eq!(
cache_line(&cache()),
"meta: cache v=1 engine_state=EMPTY prefix_cache=on prefix_entries=0 prefix_blocks=0 prefix_used_bytes=0 prefix_budget_bytes=5713000000 os_page_cache=not-probed"
);
assert_eq!(lines[0], expected_build_line());
assert_eq!(lines[1], expected_model_line());
assert_eq!(lines[2], EXPECTED_CONFIG_LINE);
assert_eq!(cache_line(&cache()), EXPECTED_CACHE_LINE);
}
#[test]
@@ -165,7 +172,8 @@ fn a_cache_with_entries_is_warm() {
assert!(cache_line(&off).contains(" engine_state=EMPTY prefix_cache=off "));
}
/// Start-up reads file metadata only: a missing file is `-`, an existing one is its length and mtime, and nothing reads its content.
/// Start-up reads file metadata only: a missing file is `-`, an existing one is its length and mtime, and nothing
/// reads its content.
#[test]
fn model_files_are_statted_never_read() {
let missing = ModelFile::stat(Path::new("/definitely/not/here/model.gguf"));
@@ -174,7 +182,8 @@ fn model_files_are_statted_never_read() {
assert!(here.bytes.is_none() || here.bytes.unwrap() > 0);
}
/// The formatting is a pure function of its inputs (no clock, no environment, no file): the same inputs give the same lines, so enabling the
/// The formatting is a pure function of its inputs (no clock, no environment, no file): the same inputs give the same
/// lines, so enabling the
/// report cannot change a result that does not read stderr.
#[test]
fn formatting_is_deterministic() {
+13 -10
View File
@@ -1,11 +1,13 @@
//! Run-time tuning of the Original serve path: the settings an operator changes on a running engine, which reopens the serve
//! stack (not the weights, the CUDA context or the KAR binding) with new values. `docs/deploy.md`, "Changing the runtime settings".
//! Run-time tuning of the Original serve path: the settings an operator changes on a running engine, which reopens the
//! serve stack (not the weights, the CUDA context or the KAR binding) with new values. `docs/deploy.md`, "Changing the
//! runtime settings".
//!
//! The document is a JSON object whose members are all optional; an absent member keeps its current value. What can change without
//! reloading the model: the context length, the prefill chunk, the resident K/V window, the prefix cache (host RAM budget, request-end
//! checkpoints, block, retention), the CPU expert workers (1..=15, the native pool's limit) and the draft-probability floor. What cannot:
//! the VRAM budget (fixed when the CUDA context is created) and the resident K/V window (`kv_resident`, configured once per process,
//! live job 9r1); those take a restart (`leleka up`).
//! The document is a JSON object whose members are all optional; an absent member keeps its current value. What can
//! change without reloading the model: the context length, the prefill chunk, the resident K/V window, the prefix cache
//! (host RAM budget, request-end checkpoints, block, retention), the CPU expert workers (1..=15, the native pool's
//! limit) and the draft-probability floor. What cannot: the VRAM budget (fixed when the CUDA context is created) and
//! the resident K/V window (`kv_resident`, configured once per process, live job 9r1); those take a restart (`leleka
//! up`).
use crate::backend::{OriginalServeOptions, PrefixCacheOptions, PrefixTail};
use serde::Deserialize;
use serde_json::{Value, json};
@@ -24,8 +26,8 @@ pub struct Tuning {
pub context_tokens: Option<u32>,
/// Prompt chunk of the batched prefill; also the default prefix-cache block.
pub prefill_capacity: Option<usize>,
/// QSA K/V cells kept in VRAM per layer (0 = the whole context; at least 20480 otherwise). Fixed for the life of the process:
/// only the value already in force is accepted; a different one needs a restart.
/// QSA K/V cells kept in VRAM per layer (0 = the whole context; at least 20480 otherwise). Fixed for the life of
/// the process: only the value already in force is accepted; a different one needs a restart.
pub kv_resident: Option<usize>,
/// Host-RAM budget of the prefix cache: `"auto"`, `"off"` (or `"0"`), or a size in MiB.
pub prefix_cache_mib: Option<String>,
@@ -55,7 +57,8 @@ impl Tuning {
Ok(tuning)
}
/// Apply to the current options and context; returns the names of the members that changed value. Nothing is modified on error.
/// Apply to the current options and context; returns the names of the members that changed value. Nothing is
/// modified on error.
pub fn apply(
&self,
options: &mut OriginalServeOptions,
@@ -20,11 +20,13 @@ fn an_empty_or_unknown_document_is_refused() {
assert!(Tuning::parse("not json").is_err());
}
#[test]
fn values_apply_and_the_changed_members_are_named() {
let (mut options, mut context) = base();
let tuning = Tuning::parse(r#"{"context_tokens":65536,"prefix_cache_tail":"reply","prefix_cache_mib":"20480","prefill_capacity":8192,"prefix_cache_block":8192,"prefix_retention_min":30,"cpu_workers":8,"spec_min_p":0.5}"#).unwrap();
let changed = tuning.apply(&mut options, &mut context).unwrap();
const FULL_DOCUMENT: &str = concat!(
r#"{"context_tokens":65536,"prefix_cache_tail":"reply","prefix_cache_mib":"20480","#,
r#""prefill_capacity":8192,"prefix_cache_block":8192,"prefix_retention_min":30,"#,
r#""cpu_workers":8,"spec_min_p":0.5}"#
);
fn assert_full_document_applied(options: &OriginalServeOptions, context: u32) {
assert_eq!(context, 65_536);
assert_eq!(options.prefill_capacity, Some(8192));
assert_eq!(options.cpu_workers, Some(8));
@@ -34,6 +36,9 @@ fn values_apply_and_the_changed_members_are_named() {
(prefix.tail, prefix.budget_bytes, prefix.block_tokens, prefix.retention_s),
(PrefixTail::Reply, Some(20_480 << 20), 8192, Some(1800))
);
}
fn assert_every_member_named(changed: &[&str]) {
for name in [
"context_tokens",
"prefill_capacity",
@@ -46,6 +51,15 @@ fn values_apply_and_the_changed_members_are_named() {
] {
assert!(changed.contains(&name), "{name} in {changed:?}");
}
}
#[test]
fn values_apply_and_the_changed_members_are_named() {
let (mut options, mut context) = base();
let tuning = Tuning::parse(FULL_DOCUMENT).unwrap();
let changed = tuning.apply(&mut options, &mut context).unwrap();
assert_full_document_applied(&options, context);
assert_every_member_named(&changed);
// the same document again changes nothing
assert!(tuning.apply(&mut options, &mut context).unwrap().is_empty());
}
@@ -1,12 +1,13 @@
//! Production serving prints nothing of the bring-up diagnostics.
//!
//! Every `eprintln!("DBG ...")` / `eprintln!("PROBE ...")` in the production code of `leleka-engine-qwen35-cuda` and `leleka-cuda-driver` must be
//! silent unless somebody asked for it: through `bringup_trace!` (`LELEKA_BRINGUP_TRACE`), or under a dedicated opt-in switch of its
//! own (`LELEKA_SERVE_PROFILE`, `LELEKA_SPEC_TRACE`, `LELEKA_SEED_TRACE`, `LELEKA_TRACE_PLE`, ...), which the print has to sit
//! behind within a few lines. Test-only modules (the `#[ignore]`d GPU smokes, whose output is their evidence) are exempt.
//! Every `eprintln!("DBG ...")` / `eprintln!("PROBE ...")` in the production code of `leleka-engine-qwen35-cuda` and
//! `leleka-cuda-driver` must be silent unless somebody asked for it: through `bringup_trace!` (`LELEKA_BRINGUP_TRACE`),
//! or under a dedicated opt-in switch of its own (`LELEKA_SERVE_PROFILE`, `LELEKA_SPEC_TRACE`, `LELEKA_SEED_TRACE`,
//! `LELEKA_TRACE_PLE`, ...), which the print has to sit behind within a few lines. Test-only modules (the `#[ignore]`d
//! GPU smokes, whose output is their evidence) are exempt.
//!
//! This reads the sources; it does not execute anything and needs no GPU. It exists so that a new unguarded `DBG` line cannot slip
//! into a release unnoticed (the review that gated the existing ones is in `docs/port-remaining.md`).
//! This reads the sources; it does not execute anything and needs no GPU. It exists so that a new unguarded `DBG` line
//! cannot slip into a release unnoticed (the review that gated the existing ones is in `docs/port-remaining.md`).
use std::{
fs,
path::{Path, PathBuf},
@@ -41,52 +42,77 @@ fn rust_files(dir: &Path, out: &mut Vec<PathBuf>) {
}
}
/// Files that only exist in test builds: declared as `mod name;` right after a `#[cfg(test)]`-like attribute, or marked `#![cfg(test)]`.
/// The module name of a `mod name;` declaration line (any visibility), or `None`.
fn declared_module(line: &str) -> Option<&str> {
let trimmed = line.trim_start();
let declared = trimmed
.strip_prefix("pub(crate) mod ")
.or_else(|| trimmed.strip_prefix("pub(super) mod "))
.or_else(|| trimmed.strip_prefix("pub mod "))
.or_else(|| trimmed.strip_prefix("mod "));
declared.and_then(|rest| rest.strip_suffix(';'))
}
/// Whether the file marks itself as test-only (`#![cfg(test)]` near the top).
fn marked_cfg_test(text: &str) -> bool {
text.lines()
.take(40)
.any(|l| l.trim_start().starts_with("#![cfg(test)]") || l.trim_start().starts_with("#![cfg(all(test"))
}
/// Whether a line ends the previous item, so the attribute block of a declaration starts below it.
fn ends_previous_item(previous: &str) -> bool {
previous.is_empty()
|| previous.ends_with(';')
|| previous.ends_with('{')
|| previous.ends_with('}')
|| previous.starts_with("//")
}
/// The attribute block of the declaration at `index`: the lines above it up to the previous item (rustfmt splits a long
/// `cfg(all(...))` over several lines).
fn attribute_block(lines: &[&str], index: usize) -> String {
let mut start = index;
while start > 0 && index - start < 12 {
if ends_previous_item(lines[start - 1].trim()) {
break;
}
start -= 1;
}
lines[start..index].join(" ")
}
fn gates_test_only(above: &str) -> bool {
let squeezed: String = above.split_whitespace().collect();
squeezed.contains("cfg(test)") || squeezed.contains("cfg(all(test") || squeezed.contains("cfg(any(test")
}
/// The files a test-only `mod name;` declared in `file` can live in.
fn push_declared_files(gated: &mut Vec<PathBuf>, file: &Path, name: &str, above: &str) {
let dir = file.parent().unwrap();
gated.push(dir.join(format!("{name}.rs")));
gated.push(dir.join(name).join("mod.rs"));
// `#[path = "other_name.rs"] mod name;`
if let Some(path) = above.split("#[path = \"").nth(1).and_then(|rest| rest.split('"').next()) {
gated.push(dir.join(path));
}
}
/// Files that only exist in test builds: declared as `mod name;` right after a `#[cfg(test)]`-like attribute, or marked
/// `#![cfg(test)]`.
fn test_only(files: &[PathBuf]) -> Vec<PathBuf> {
let mut gated = Vec::new();
for file in files {
let text = fs::read_to_string(file).unwrap_or_default();
if text
.lines()
.take(40)
.any(|l| l.trim_start().starts_with("#![cfg(test)]") || l.trim_start().starts_with("#![cfg(all(test"))
{
if marked_cfg_test(&text) {
gated.push(file.clone());
}
let lines: Vec<&str> = text.lines().collect();
for (index, line) in lines.iter().enumerate() {
let trimmed = line.trim_start();
let declared = trimmed
.strip_prefix("pub(crate) mod ")
.or_else(|| trimmed.strip_prefix("pub(super) mod "))
.or_else(|| trimmed.strip_prefix("pub mod "))
.or_else(|| trimmed.strip_prefix("mod "));
let Some(name) = declared.and_then(|rest| rest.strip_suffix(';')) else { continue };
// the attribute block of the declaration: the lines above it up to the previous item (rustfmt splits a long `cfg(all(...))` over several lines)
let mut start = index;
while start > 0 && index - start < 12 {
let previous = lines[start - 1].trim();
if previous.is_empty()
|| previous.ends_with(';')
|| previous.ends_with('{')
|| previous.ends_with('}')
|| previous.starts_with("//")
{
break;
}
start -= 1;
}
let above = lines[start..index].join(" ");
let squeezed: String = above.split_whitespace().collect();
if squeezed.contains("cfg(test)") || squeezed.contains("cfg(all(test") || squeezed.contains("cfg(any(test")
{
let dir = file.parent().unwrap();
gated.push(dir.join(format!("{name}.rs")));
gated.push(dir.join(name).join("mod.rs"));
// `#[path = "other_name.rs"] mod name;`
if let Some(path) = above.split("#[path = \"").nth(1).and_then(|rest| rest.split('"').next()) {
gated.push(dir.join(path));
}
let Some(name) = declared_module(line) else { continue };
let above = attribute_block(&lines, index);
if gates_test_only(&above) {
push_declared_files(&mut gated, file, name, &above);
}
}
}
@@ -94,40 +120,44 @@ fn test_only(files: &[PathBuf]) -> Vec<PathBuf> {
gated
}
/// The children of a test-only file are test-only too: every `mod name;` it declares (split modules, `#[path]` ones included).
/// Where the child module `name` declared at `lines[index]` of a file in `dir` (own folder `own`) can live.
fn child_candidates(dir: &Path, own: &Path, lines: &[&str], index: usize, name: &str) -> Vec<PathBuf> {
let mut candidates =
vec![own.join(format!("{name}.rs")), own.join(name).join("mod.rs"), dir.join(format!("{name}.rs"))];
if let Some(path) = lines[..index]
.iter()
.rev()
.take(3)
.find_map(|l| l.trim().strip_prefix("#[path = \"").and_then(|r| r.split('"').next()))
{
candidates.push(dir.join(path));
}
candidates
}
fn push_children(gated: &mut Vec<PathBuf>, file: &Path, text: &str) {
let Some(dir) = file.parent() else { return };
let own = file.file_stem().map(|stem| dir.join(stem)).unwrap_or_default();
let lines: Vec<&str> = text.lines().collect();
for (index, line) in lines.iter().enumerate() {
let Some(name) = declared_module(line) else { continue };
for candidate in child_candidates(dir, &own, &lines, index, name) {
if candidate.is_file() && !gated.contains(&candidate) {
gated.push(candidate);
}
}
}
}
/// The children of a test-only file are test-only too: every `mod name;` it declares (split modules, `#[path]` ones
/// included).
fn descend(gated: &mut Vec<PathBuf>) {
let mut next = 0;
while next < gated.len() {
let file = gated[next].clone();
next += 1;
let Ok(text) = fs::read_to_string(&file) else { continue };
let Some(dir) = file.parent() else { continue };
let own = file.file_stem().map(|stem| dir.join(stem)).unwrap_or_default();
let lines: Vec<&str> = text.lines().collect();
for (index, line) in lines.iter().enumerate() {
let trimmed = line.trim_start();
let declared = trimmed
.strip_prefix("pub(crate) mod ")
.or_else(|| trimmed.strip_prefix("pub(super) mod "))
.or_else(|| trimmed.strip_prefix("pub mod "))
.or_else(|| trimmed.strip_prefix("mod "));
let Some(name) = declared.and_then(|rest| rest.strip_suffix(';')) else { continue };
let mut candidates =
vec![own.join(format!("{name}.rs")), own.join(name).join("mod.rs"), dir.join(format!("{name}.rs"))];
if let Some(path) = lines[..index]
.iter()
.rev()
.take(3)
.find_map(|l| l.trim().strip_prefix("#[path = \"").and_then(|r| r.split('"').next()))
{
candidates.push(dir.join(path));
}
for candidate in candidates {
if candidate.is_file() && !gated.contains(&candidate) {
gated.push(candidate);
}
}
}
push_children(gated, &file, &text);
}
}
@@ -142,6 +172,46 @@ fn first_literal(lines: &[&str], at: usize, column: usize) -> Option<String> {
Some(text[start..].chars().take(12).collect())
}
/// Where the production part of a file ends: from the first `#[cfg(test)] mod tests` on, the rest is test code.
fn production_end(lines: &[&str]) -> usize {
lines
.iter()
.enumerate()
.position(|(i, l)| {
l.trim() == "#[cfg(test)]" && lines.get(i + 1).is_some_and(|n| n.trim_start().starts_with("mod "))
})
.unwrap_or(lines.len())
}
/// Whether the line at `index` is a `DBG` / `PROBE` print with none of the [`GUARDS`] within [`LOOKBACK`] lines.
fn is_unguarded_print(lines: &[&str], index: usize) -> bool {
let line = lines[index];
let Some(column) =
["eprintln!(", "eprint!(", "println!("].iter().filter_map(|m| line.find(m).map(|c| c + m.len())).min()
else {
return false;
};
let Some(literal) = first_literal(lines, index, column) else { return false };
if !(literal.starts_with("DBG") || literal.starts_with("PROBE")) {
return false;
}
let from = index.saturating_sub(LOOKBACK);
let context = lines[from..=index].join("\n");
!GUARDS.iter().any(|guard| context.contains(guard))
}
fn unguarded_prints(root: &Path, file: &Path, text: &str) -> Vec<String> {
let lines: Vec<&str> = text.lines().collect();
let end = production_end(&lines);
let mut bad = Vec::new();
for (index, line) in lines.iter().enumerate().take(end) {
if is_unguarded_print(&lines, index) {
bad.push(format!("{}:{}: {}", file.strip_prefix(root).unwrap_or(file).display(), index + 1, line.trim()));
}
}
bad
}
fn findings(root: &Path) -> Vec<String> {
let mut files = Vec::new();
for crate_dir in ["crates/engine-qwen35-cuda/src", "crates/cuda-driver/src"] {
@@ -154,36 +224,7 @@ fn findings(root: &Path) -> Vec<String> {
continue;
}
let text = fs::read_to_string(file).unwrap_or_default();
let lines: Vec<&str> = text.lines().collect();
// from the first `#[cfg(test)] mod tests` on, the rest of the file is test code
let end = lines
.iter()
.enumerate()
.position(|(i, l)| {
l.trim() == "#[cfg(test)]" && lines.get(i + 1).is_some_and(|n| n.trim_start().starts_with("mod "))
})
.unwrap_or(lines.len());
for (index, line) in lines.iter().enumerate().take(end) {
let Some(column) =
["eprintln!(", "eprint!(", "println!("].iter().filter_map(|m| line.find(m).map(|c| c + m.len())).min()
else {
continue;
};
let Some(literal) = first_literal(&lines, index, column) else { continue };
if !(literal.starts_with("DBG") || literal.starts_with("PROBE")) {
continue;
}
let from = index.saturating_sub(LOOKBACK);
let context = lines[from..=index].join("\n");
if !GUARDS.iter().any(|guard| context.contains(guard)) {
bad.push(format!(
"{}:{}: {}",
file.strip_prefix(root).unwrap_or(file).display(),
index + 1,
line.trim()
));
}
}
bad.extend(unguarded_prints(root, file, &text));
}
bad
}
@@ -194,7 +235,8 @@ fn every_production_dbg_or_probe_print_is_behind_a_switch() {
let bad = findings(&root);
assert!(
bad.is_empty(),
"these DBG/PROBE prints fire without LELEKA_BRINGUP_TRACE or a switch of their own; route them through bringup_trace! (or add the switch to GUARDS if it is a real opt-in):\n{}",
"these DBG/PROBE prints fire without LELEKA_BRINGUP_TRACE or a switch of their own; \
route them through bringup_trace! (or add the switch to GUARDS if it is a real opt-in):\n{}",
bad.join("\n")
);
}
@@ -27,10 +27,7 @@ fn xor_sum(mut lanes: [f32; 32]) -> [f32; 32] {
// Lane indexing deliberately mirrors the independent frozen reduction order.
#[allow(clippy::needless_range_loop)]
pub fn reference(logits: &[f32; EXPERTS]) -> Option<Reference> {
if logits.iter().any(|value| !value.is_finite()) {
return None;
}
fn softmax(logits: &[f32; EXPERTS]) -> [f32; EXPERTS] {
let maximum = logits.iter().copied().fold(f32::NEG_INFINITY, f32::max);
let mut probabilities = [0.0; EXPERTS];
let mut lane_sums = [0.0; 32];
@@ -47,7 +44,19 @@ pub fn reference(logits: &[f32; EXPERTS]) -> Option<Reference> {
for value in &mut probabilities {
*value *= reciprocal;
}
let mut remaining = probabilities;
probabilities
}
struct Winners {
ids: [i32; SELECTED],
selected: [f32; SELECTED],
selected_lanes: [f32; 32],
}
// Lane indexing deliberately mirrors the independent frozen reduction order.
#[allow(clippy::needless_range_loop)]
fn pick_winners(probabilities: &[f32; EXPERTS]) -> Option<Winners> {
let mut remaining = *probabilities;
let mut ids = [0; SELECTED];
let mut selected = [0.0; SELECTED];
let mut selected_lanes = [0.0; 32];
@@ -65,6 +74,15 @@ pub fn reference(logits: &[f32; EXPERTS]) -> Option<Reference> {
selected_lanes[winner & 31] += remaining[winner];
remaining[winner] = f32::NEG_INFINITY;
}
Some(Winners { ids, selected, selected_lanes })
}
pub fn reference(logits: &[f32; EXPERTS]) -> Option<Reference> {
if logits.iter().any(|value| !value.is_finite()) {
return None;
}
let probabilities = softmax(logits);
let Winners { ids, selected, selected_lanes } = pick_winners(&probabilities)?;
let selected_lane_sum = xor_sum(selected_lanes)[0];
let inverse = 1.0 / selected_lane_sum.max(MIN_DENOMINATOR);
let weights = selected.map(|probability| probability * inverse);
@@ -110,123 +110,174 @@ fn prepare_independent_full_vocabulary_fixture() {
println!("FULL_VOCABULARY_CPU_PREP rows={ROWS} columns={COLUMNS} expected_argmax=248319\n{manifest}");
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
mod device {
use super::*;
use leleka_cuda_driver::{Context, DeviceBuffer, Driver, Q6KProjectionShape};
use std::process::Command;
pub(super) struct Oracle {
pub(super) native: PathBuf,
pub(super) ptx: PathBuf,
}
pub(super) struct Expected<'a> {
pub(super) literal: &'a [u8],
pub(super) native: &'a [u8],
}
struct Buffers<'c> {
dw: DeviceBuffer<'c>,
dx: DeviceBuffer<'c>,
dy: DeviceBuffer<'c>,
}
pub(super) fn oracle_binaries() -> Oracle {
let native = PathBuf::from(std::env::var_os("LELEKA_HEAD_NATIVE_ORACLE").unwrap());
let ptx = PathBuf::from(std::env::var_os("LELEKA_Q6_TRUSTED_PTX").unwrap());
assert!(native.is_absolute() && ptx.is_absolute());
assert_eq!(hash_file(&ptx), PTX_SHA);
assert_eq!(
hash_file(&native),
std::env::var("LELEKA_HEAD_NATIVE_SHA256").expect("independently retained build receipt")
);
Oracle { native, ptx }
}
pub(super) fn check_manifest(root: &Path) {
let manifest = fs::read_to_string(root.join("literal-sha256.txt")).unwrap();
for line in manifest.lines() {
let (sha, name) = line.split_once(" ").unwrap();
assert!(matches!(name, "full-vocabulary.input" | "literal-q8.bin" | "literal-logits.bin"));
assert_eq!(hash_file(&root.join(name)), sha);
}
}
fn header_bytes(magic: &[u32]) -> Vec<u8> {
magic.iter().copied().flat_map(u32::to_le_bytes).collect::<Vec<_>>()
}
pub(super) fn read_input(input_path: &Path) -> (Vec<u8>, Vec<u8>) {
let mut input = fs::File::open(input_path).unwrap();
let mut header = [0; 12];
input.read_exact(&mut header).unwrap();
assert_eq!(header, header_bytes(&[0x3631_4b51_u32, ROWS as u32, COLUMNS as u32]).as_slice());
let mut weights = vec![0; WEIGHT_BYTES];
input.read_exact(&mut weights).unwrap();
for (row, actual) in weights.as_chunks::<2100>().0.iter().enumerate() {
assert_eq!(*actual, packed_row(scale(row)), "independent packed row {row}");
}
let activation = vec![0x42fe_0000_u32.to_le_bytes(); COLUMNS].into_iter().flatten().collect::<Vec<_>>();
let mut actual_activation = vec![0; COLUMNS * 4];
input.read_exact(&mut actual_activation).unwrap();
assert_eq!(actual_activation, activation);
assert_eq!(input.read(&mut [0]).unwrap(), 0);
(weights, activation)
}
pub(super) fn run_native(root: &Path, input_path: &Path, oracle: &Oracle) -> Vec<u8> {
// Finite full-M-only native harness preserves unchanged original kernel
// and independently fresh original plus candidate quantizer scratch.
let native_output = root.join("full-vocabulary.native");
assert!(!native_output.exists());
let process = Command::new("timeout")
.args(["--signal=TERM", "--kill-after=5", "60"])
.arg(&oracle.native)
.arg(input_path)
.arg(&native_output)
.arg(&oracle.ptx)
.output()
.unwrap();
fs::write(root.join("native.stdout"), &process.stdout).unwrap();
fs::write(root.join("native.stderr"), &process.stderr).unwrap();
assert!(process.status.success(), "{}", String::from_utf8_lossy(&process.stderr));
let native_bytes = fs::read(&native_output).unwrap();
assert_eq!(native_bytes.len(), 16 + 2 * Q8_BYTES + LOGIT_BYTES);
native_bytes
}
pub(super) fn check_native_words(native_bytes: &[u8]) -> Vec<u8> {
assert_eq!(&native_bytes[..16], header_bytes(&[0x3631_4f51_u32, ROWS as u32, COLUMNS as u32, 0]).as_slice());
assert_eq!(&native_bytes[16..16 + Q8_BYTES], expected_q8());
assert_eq!(&native_bytes[16 + Q8_BYTES..16 + 2 * Q8_BYTES], expected_q8());
let literal = expected_logits();
assert_eq!(&native_bytes[16 + 2 * Q8_BYTES..], literal);
literal
}
fn upload<'c>(context: &'c Context<'_>, weights: Vec<u8>, activation: &[u8]) -> Buffers<'c> {
let mut dw = context.allocate(WEIGHT_BYTES).unwrap();
dw.copy_from(&weights).unwrap();
drop(weights);
let mut dx = context.allocate(COLUMNS * 4).unwrap();
dx.copy_from(activation).unwrap();
let mut dy = context.allocate(LOGIT_BYTES).unwrap();
dy.copy_from(&vec![0xa5; LOGIT_BYTES]).unwrap();
Buffers { dw, dx, dy }
}
/// Independent strict-greater scan; does not claim private production
/// FiniteLogits/greedy publication or late nonfinite boundary execution.
fn strict_greater_argmax(logits: &[u8]) -> usize {
let (mut best_id, mut best_value) = (0, f32::NEG_INFINITY);
for (id, bytes) in logits.as_chunks::<4>().0.iter().enumerate() {
let value = f32::from_le_bytes(*bytes);
assert!(value.is_finite());
if value > best_value {
best_id = id;
best_value = value;
}
}
best_id
}
fn release_buffers(buffers: Buffers<'_>) {
buffers.dy.release().unwrap();
buffers.dx.release().unwrap();
buffers.dw.release().unwrap();
}
pub(super) fn project_and_compare(root: &Path, weights: Vec<u8>, activation: &[u8], expected: &Expected<'_>) {
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(1 << 30).unwrap();
let mut buffers = upload(&context, weights, activation);
let resident = context.allocated_bytes();
assert_eq!(resident, WEIGHT_BYTES + COLUMNS * 4 + LOGIT_BYTES);
let shape = Q6KProjectionShape { rows: ROWS, columns: COLUMNS };
context.q6_k_q8_1(&buffers.dw, &buffers.dx, &mut buffers.dy, shape).unwrap();
assert_eq!(context.allocated_bytes(), resident, "quantizer scratch/status released");
let mut logits = vec![0; LOGIT_BYTES];
buffers.dy.copy_to(&mut logits).unwrap();
assert_eq!(logits, expected.literal, "all 248320 exact independent F32 words");
assert_eq!(logits, expected.native);
assert_eq!(strict_greater_argmax(&logits), 248319);
let mut unchanged_x = vec![0; COLUMNS * 4];
buffers.dx.copy_to(&mut unchanged_x).unwrap();
assert_eq!(unchanged_x, activation);
fs::write(root.join("full-vocabulary.actual"), &logits).unwrap();
release_buffers(buffers);
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
}
}
#[cfg(all(any(target_os = "linux", target_os = "windows"), target_pointer_width = "64"))]
#[test]
#[ignore = "explicit serialized GPU slot and independently verified original CUDA13.0.88 full-M oracle required"]
fn installed_driver_full_vocabulary_matches_original_and_literal_words() {
use leleka_cuda_driver::{Driver, Q6KProjectionShape};
use std::process::Command;
assert_eq!(std::env::var("LELEKA_CUDA_REAL_GPU").as_deref(), Ok("1"));
let root = evidence_root();
let native = PathBuf::from(std::env::var_os("LELEKA_HEAD_NATIVE_ORACLE").unwrap());
let ptx = PathBuf::from(std::env::var_os("LELEKA_Q6_TRUSTED_PTX").unwrap());
assert!(native.is_absolute() && ptx.is_absolute());
assert_eq!(hash_file(&ptx), PTX_SHA);
assert_eq!(
hash_file(&native),
std::env::var("LELEKA_HEAD_NATIVE_SHA256").expect("independently retained build receipt")
);
let manifest = fs::read_to_string(root.join("literal-sha256.txt")).unwrap();
for line in manifest.lines() {
let (sha, name) = line.split_once(" ").unwrap();
assert!(matches!(name, "full-vocabulary.input" | "literal-q8.bin" | "literal-logits.bin"));
assert_eq!(hash_file(&root.join(name)), sha);
}
let oracle = device::oracle_binaries();
device::check_manifest(&root);
let input_path = root.join("full-vocabulary.input");
let mut input = fs::File::open(&input_path).unwrap();
let mut header = [0; 12];
input.read_exact(&mut header).unwrap();
assert_eq!(
header,
[0x3631_4b51_u32, ROWS as u32, COLUMNS as u32]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect::<Vec<_>>()
.as_slice()
);
let mut weights = vec![0; WEIGHT_BYTES];
input.read_exact(&mut weights).unwrap();
for (row, actual) in weights.as_chunks::<2100>().0.iter().enumerate() {
assert_eq!(*actual, packed_row(scale(row)), "independent packed row {row}");
}
let activation = vec![0x42fe_0000_u32.to_le_bytes(); COLUMNS].into_iter().flatten().collect::<Vec<_>>();
let mut actual_activation = vec![0; COLUMNS * 4];
input.read_exact(&mut actual_activation).unwrap();
assert_eq!(actual_activation, activation);
assert_eq!(input.read(&mut [0]).unwrap(), 0);
drop(input);
// Finite full-M-only native harness preserves unchanged original kernel
// and independently fresh original plus candidate quantizer scratch.
let native_output = root.join("full-vocabulary.native");
assert!(!native_output.exists());
let process = Command::new("timeout")
.args(["--signal=TERM", "--kill-after=5", "60"])
.arg(&native)
.arg(&input_path)
.arg(&native_output)
.arg(&ptx)
.output()
.unwrap();
fs::write(root.join("native.stdout"), &process.stdout).unwrap();
fs::write(root.join("native.stderr"), &process.stderr).unwrap();
assert!(process.status.success(), "{}", String::from_utf8_lossy(&process.stderr));
let native_bytes = fs::read(&native_output).unwrap();
assert_eq!(native_bytes.len(), 16 + 2 * Q8_BYTES + LOGIT_BYTES);
assert_eq!(
&native_bytes[..16],
[0x3631_4f51_u32, ROWS as u32, COLUMNS as u32, 0]
.into_iter()
.flat_map(u32::to_le_bytes)
.collect::<Vec<_>>()
.as_slice()
);
assert_eq!(&native_bytes[16..16 + Q8_BYTES], expected_q8());
assert_eq!(&native_bytes[16 + Q8_BYTES..16 + 2 * Q8_BYTES], expected_q8());
let literal = expected_logits();
assert_eq!(&native_bytes[16 + 2 * Q8_BYTES..], literal);
let driver = Driver::load().unwrap();
let device = driver.device(0).unwrap();
let context = device.create_context(1 << 30).unwrap();
let mut dw = context.allocate(WEIGHT_BYTES).unwrap();
dw.copy_from(&weights).unwrap();
drop(weights);
let mut dx = context.allocate(COLUMNS * 4).unwrap();
dx.copy_from(&activation).unwrap();
let mut dy = context.allocate(LOGIT_BYTES).unwrap();
dy.copy_from(&vec![0xa5; LOGIT_BYTES]).unwrap();
let resident = context.allocated_bytes();
assert_eq!(resident, WEIGHT_BYTES + COLUMNS * 4 + LOGIT_BYTES);
context.q6_k_q8_1(&dw, &dx, &mut dy, Q6KProjectionShape { rows: ROWS, columns: COLUMNS }).unwrap();
assert_eq!(context.allocated_bytes(), resident, "quantizer scratch/status released");
let mut logits = vec![0; LOGIT_BYTES];
dy.copy_to(&mut logits).unwrap();
assert_eq!(logits, literal, "all 248320 exact independent F32 words");
assert_eq!(logits, native_bytes[16 + 2 * Q8_BYTES..]);
// Independent strict-greater scan; does not claim private production
// FiniteLogits/greedy publication or late nonfinite boundary execution.
let (mut best_id, mut best_value) = (0, f32::NEG_INFINITY);
for (id, bytes) in logits.as_chunks::<4>().0.iter().enumerate() {
let value = f32::from_le_bytes(*bytes);
assert!(value.is_finite());
if value > best_value {
best_id = id;
best_value = value;
}
}
assert_eq!(best_id, 248319);
let mut unchanged_x = vec![0; COLUMNS * 4];
dx.copy_to(&mut unchanged_x).unwrap();
assert_eq!(unchanged_x, activation);
fs::write(root.join("full-vocabulary.actual"), &logits).unwrap();
dy.release().unwrap();
dx.release().unwrap();
dw.release().unwrap();
assert_eq!(context.allocated_bytes(), 0);
context.close().unwrap();
let (weights, activation) = device::read_input(&input_path);
let native_bytes = device::run_native(&root, &input_path, &oracle);
let literal = device::check_native_words(&native_bytes);
let expected = device::Expected { literal: &literal, native: &native_bytes[16 + 2 * Q8_BYTES..] };
device::project_and_compare(&root, weights, &activation, &expected);
println!(
"FULL_VOCABULARY_DEVICE PASS rows={ROWS} columns={COLUMNS} logits={ROWS} exact_bits=true argmax=248319 candidate_budget=522478404 native_budget=522484164 cleanup=0 scope=projection_geometry_only"
"FULL_VOCABULARY_DEVICE PASS rows={ROWS} columns={COLUMNS} logits={ROWS} exact_bits=true argmax=248319 \
candidate_budget=522478404 native_budget=522484164 cleanup=0 scope=projection_geometry_only"
);
}
@@ -3,9 +3,6 @@
#[allow(unused_imports)]
use super::*;
mod scale_search;
pub(super) use scale_search::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights};
pub(super) fn alloc<T: Default>(n: usize) -> Result<Vec<T>> {
let mut v = Vec::new();
v.try_reserve_exact(n).map_err(|_| Error::Allocation)?;
@@ -15,29 +12,14 @@ pub(super) fn alloc<T: Default>(n: usize) -> Result<Vec<T>> {
impl Grid {
pub(super) fn new(codes: &[u16], dim: usize, bits: usize, want: usize) -> Result<Self> {
let size = if dim == 8 { 43692 } else { 4096 };
let (points, mut map) = Self::index_points(codes, dim, bits, size)?;
let (points, mut map) = Self::index_codes(codes, dim, bits, size)?;
let mut dist = alloc::<(i32, u16)>(codes.len())?;
let (counts, total) = Self::neighbor_counts(&points, &map, (dim, bits, want), &mut dist)?;
let mut neighbors = alloc::<u16>(total)?;
let mut at = 0;
for i in 0..size {
if map[i] >= 0 {
continue;
}
Self::distances(i, dim, bits, &points, &mut dist);
dist.sort_unstable();
let n = counts[i];
map[i] = -((at + 1) as i32);
neighbors[at] = n as u16;
for j in 0..n {
neighbors[at + 1 + j] = dist[j].1;
}
at += n + 1;
}
let (counts, total) = Self::count_neighbors(&map, &points, (dim, bits, want), &mut dist)?;
let neighbors = Self::index_neighbors(&mut map, &points, (dim, bits), (&counts, total), &mut dist)?;
Ok(Self { points, map, neighbors, dim, bits })
}
/// The grid points of the codes, and the map from code to point index (-1 for codes that are not on the grid).
fn index_points(codes: &[u16], dim: usize, bits: usize, size: usize) -> Result<(Vec<[i8; 8]>, Vec<i32>)> {
/// The lattice points of the codes, and the table from a code to its point (or -1 when off the grid).
fn index_codes(codes: &[u16], dim: usize, bits: usize, size: usize) -> Result<(Vec<[i8; 8]>, Vec<i32>)> {
let mut points = alloc::<[i8; 8]>(codes.len())?;
let mut map = alloc::<i32>(size)?;
map.fill(-1);
@@ -49,29 +31,56 @@ impl Grid {
}
Ok((points, map))
}
/// How many nearest points each off-grid code keeps, and the length of the neighbor table;
/// `shape` is (dim, bits, want).
fn neighbor_counts(
points: &[[i8; 8]],
/// Fills `dist` with the grid points ordered by distance from lattice position `i`.
fn sort_by_distance(i: usize, dim: usize, bits: usize, points: &[[i8; 8]], dist: &mut [(i32, u16)]) {
Self::distances(i, dim, bits, points, dist);
dist.sort_unstable();
}
/// The neighbour count of every off-grid position, and the length of the neighbour table.
fn count_neighbors(
map: &[i32],
shape: (usize, usize, usize),
points: &[[i8; 8]],
(dim, bits, want): (usize, usize, usize),
dist: &mut [(i32, u16)],
) -> Result<(Vec<usize>, usize)> {
let (dim, bits, want) = shape;
let mut counts = alloc::<usize>(map.len())?;
let mut total = 0usize;
for i in 0..map.len() {
if map[i] >= 0 {
continue;
}
Self::distances(i, dim, bits, points, dist);
dist.sort_unstable();
Self::sort_by_distance(i, dim, bits, points, dist);
let n = Self::count(dist, want);
counts[i] = n;
total = total.checked_add(n + 1).ok_or(Error::Allocation)?;
}
Ok((counts, total))
}
/// Builds the neighbour table and points every off-grid map entry at its slot as `-(slot + 1)`.
fn index_neighbors(
map: &mut [i32],
points: &[[i8; 8]],
(dim, bits): (usize, usize),
(counts, total): (&[usize], usize),
dist: &mut [(i32, u16)],
) -> Result<Vec<u16>> {
let mut neighbors = alloc::<u16>(total)?;
let mut at = 0;
for i in 0..map.len() {
if map[i] >= 0 {
continue;
}
Self::sort_by_distance(i, dim, bits, points, dist);
let n = counts[i];
map[i] = -((at + 1) as i32);
neighbors[at] = n as u16;
for j in 0..n {
neighbors[at + 1 + j] = dist[j].1;
}
at += n + 1;
}
Ok(neighbors)
}
pub(super) fn distances(i: usize, dim: usize, bits: usize, p: &[[i8; 8]], dist: &mut [(i32, u16)]) {
for (j, pg) in p.iter().enumerate() {
let mut d = 0;
@@ -108,26 +117,30 @@ impl Grid {
let i = self.map[self.key(l)];
if i < 0 { Err(Error::NativeFailure) } else { Ok(i as usize) }
}
/// The neighbour of the off-grid slot `at` with the smallest weighted error for `scale`.
fn best_neighbor(&self, at: usize, scale: f32, x: &[f32], w: &[f32]) -> usize {
let mut best = f32::MAX;
let mut index = usize::MAX;
for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] {
let p = &self.points[g as usize];
let mut err = 0.0;
for i in 0..self.dim {
let d = scale * p[i] as f32 - x[i];
err += w[i] * d * d;
}
if err < best {
best = err;
index = g as usize;
}
}
index
}
pub(super) fn resolve(&self, l: &mut [i8], x: &[f32], w: &[f32], scale: f32) -> bool {
let mapped = self.map[self.key(l)];
let index = if mapped >= 0 {
mapped as usize
} else {
let at = (-mapped - 1) as usize;
let mut best = f32::MAX;
let mut index = usize::MAX;
for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] {
let p = &self.points[g as usize];
let mut err = 0.0;
for i in 0..self.dim {
let d = scale * p[i] as f32 - x[i];
err += w[i] * d * d;
}
if err < best {
best = err;
index = g as usize;
}
}
let index = self.best_neighbor((-mapped - 1) as usize, scale, x, w);
assert_ne!(index, usize::MAX);
index
};
@@ -181,37 +194,29 @@ pub(in super::super) fn free(k: Kind) -> Result<()> {
pub(super) fn put_h(y: &mut [u8], d: f32) {
y[..2].copy_from_slice(&half_rn(d).to_le_bytes());
}
pub(super) fn signs<const N: usize>(xb: &[f32], w: &[f32], parity: bool) -> ([f32; N], [u8; 4]) {
let mut xv = [0.0; N];
let mut signs = [0u8; 4];
for k in 0..N / 8 {
let mut flips = 0;
let mut s = 0;
for j in 0..8 {
let at = k * 8 + j;
if xb[at] >= 0.0 {
xv[at] = xb[at];
} else {
xv[at] = -xb[at];
flips += 1;
s |= 1 << j;
}
/// The sign mask of the 8-element group starting at `base` (bit `j` set for a negative value), with the flip count;
/// `xv` receives the magnitudes.
fn fold_group<const N: usize>(xb: &[f32], xv: &mut [f32; N], base: usize) -> (u8, usize) {
let mut flips = 0;
let mut s = 0u8;
for j in 0..8 {
let at = base + j;
if xb[at] >= 0.0 {
xv[at] = xb[at];
} else {
xv[at] = -xb[at];
flips += 1;
s |= 1 << j;
}
if parity && flips % 2 == 1 {
let least = least_error(xb, w, k * 8);
xv[k * 8 + least] = -xv[k * 8 + least];
s ^= 1 << least;
}
signs[k] = if parity { s & 127 } else { s };
}
(xv, signs)
(s, flips)
}
/// The position (0..8) in the group at `first` with the smallest weighted square, first one winning ties.
fn least_error(xb: &[f32], w: &[f32], first: usize) -> usize {
/// The position in the group at `base` whose weighted energy is smallest (the first on ties).
fn least_energy_index(xb: &[f32], w: &[f32], base: usize) -> usize {
let mut least = 0;
let mut error = w[first] * xb[first] * xb[first];
let mut error = w[base] * xb[base] * xb[base];
for j in 1..8 {
let at = first + j;
let at = base + j;
let e = w[at] * xb[at] * xb[at];
if e < error {
least = j;
@@ -220,6 +225,20 @@ fn least_error(xb: &[f32], w: &[f32], first: usize) -> usize {
}
least
}
pub(super) fn signs<const N: usize>(xb: &[f32], w: &[f32], parity: bool) -> ([f32; N], [u8; 4]) {
let mut xv = [0.0; N];
let mut signs = [0u8; 4];
for k in 0..N / 8 {
let (mut s, flips) = fold_group(xb, &mut xv, k * 8);
if parity && flips % 2 == 1 {
let least = least_energy_index(xb, w, k * 8);
xv[k * 8 + least] = -xv[k * 8 + least];
s ^= 1 << least;
}
signs[k] = if parity { s & 127 } else { s };
}
(xv, signs)
}
pub(super) fn totals(x: &[f32], w: &[f32], l: &[i8]) -> (f32, f32) {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..x.len() {
@@ -1,22 +1,41 @@
//! Moved out of the parent module by STRA-338: impl Grid, fn iq1_s.
use super::alloc_fn::{sum_sq, weights};
#[allow(unused_imports)]
use super::*;
impl Grid {
/// The neighbour of the off-grid slot `at` with the smallest weighted error when read through `values`.
fn best_valued_neighbor(&self, at: usize, scale: f32, (x, w): (&[f32], &[f32]), values: &[f32; 3]) -> usize {
let mut best = f32::MAX;
let mut index = usize::MAX;
for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] {
let p = &self.points[g as usize];
let mut err = 0.0;
for i in 0..8 {
let q = values[((p[i] - 1) / 2) as usize];
let d = scale * q - x[i];
err += w[i] * d * d;
}
if err < best {
best = err;
index = g as usize;
}
}
index
}
pub(super) fn resolve_one(
&self,
l: &mut [i8],
xw: (&[f32], &[f32]),
x: &[f32],
w: &[f32],
scale: f32,
v: &[f32; 3],
values: &[f32; 3],
) -> Result<(usize, bool)> {
let mapped = self.map[self.key(l)];
if mapped >= 0 {
return Ok((mapped as usize, true));
}
let index = self.best_neighbor((-mapped - 1) as usize, |p| point_error(p, v, scale, xw));
let index = self.best_valued_neighbor((-mapped - 1) as usize, scale, (x, w), values);
// Finite inputs can still overflow this weighted error calculation. Pinned
// GGML's no-finite-best fallback indexes beyond its local point array.
// Refuse that arithmetic domain rather than reproducing an invalid access.
@@ -28,121 +47,9 @@ impl Grid {
}
Ok((index, false))
}
/// The neighbor table entry at `at`: the point with the smallest `err`, the first one winning ties
/// (usize::MAX when no error is below f32::MAX).
fn best_neighbor(&self, at: usize, err: impl Fn(&[i8; 8]) -> f32) -> usize {
let mut best = f32::MAX;
let mut index = usize::MAX;
for &g in &self.neighbors[at + 1..at + 1 + self.neighbors[at] as usize] {
let e = err(&self.points[g as usize]);
if e < best {
best = e;
index = g as usize;
}
}
index
}
}
/// Weighted squared error of the grid point `p`, scaled by `scale` through the values `v`, against `xw` = (x, w).
fn point_error(p: &[i8; 8], v: &[f32; 3], scale: f32, xw: (&[f32], &[f32])) -> f32 {
let (x, w) = xw;
let mut err = 0.0;
for i in 0..8 {
let q = v[((p[i] - 1) / 2) as usize];
let d = scale * q - x[i];
err += w[i] * d * d;
}
err
}
/// Largest magnitude of a block.
pub(super) fn abs_max(xb: &[f32]) -> f32 {
let mut max = xb[0].abs();
for &v in &xb[1..] {
if v.abs() > max {
max = v.abs();
}
}
max
}
/// Level 0 for the first `b1` sorted values, 1 up to `b2`, 2 for the rest; indexed by original position.
pub(super) fn split_levels<const N: usize>(p: &[Pair; N], b1: usize, b2: usize) -> [i8; N] {
let mut l = [0i8; N];
for j in 0..N {
l[p[j].index as usize] = if j < b1 {
0
} else if j < b2 {
1
} else {
2
};
}
l
}
/// Mirrors the levels for a negative scale.
pub(super) fn flip_levels(l: &mut [i8]) {
for q in l {
*q = 2 - *q;
}
}
/// What the IQ1_S search settled on for one block of 32.
struct Iq1Fit {
scale: f32,
shift: i8,
indices: [usize; 4],
}
pub(super) fn iq1_s(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
y.fill(0);
let mut scales = [0.0; 8];
let mut shifts = [1i8; 8];
let mut heads = [0u16; 8];
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
let at = ib * 32;
let xb = &x[at..at + 32];
let w: [f32; 32] = weights(xb, Some(&qw[at..at + 32]), sigma, |v| v * v);
let Some(fit) = iq1_s_block(g, xb, &w)? else { continue };
let mut high = 0u16;
for k in 0..4 {
y[2 + ib * 4 + k] = fit.indices[k] as u8;
high |= ((fit.indices[k] >> 8) as u16) << (3 * k);
}
heads[ib] = high;
scales[ib] = fit.scale;
shifts[ib] = fit.shift;
if fit.scale > maxs {
maxs = fit.scale;
}
}
if maxs == 0.0 {
return Ok(());
}
iq1_s_scales(y, maxs, &scales, &shifts, &mut heads);
Ok(())
}
/// The fit of one block of 32; None for a block the search leaves empty.
fn iq1_s_block(g: &Grid, xb: &[f32], w: &[f32; 32]) -> Result<Option<Iq1Fit>> {
let max = abs_max(xb);
if max < 1e-12 {
return Ok(None);
}
let p = pairs::<32>(xb);
let Some((mut scale, mut shift, b1, b2)) = iq1_s_search(&iq1_prefix(&p, xb, w), max) else { return Ok(None) };
let mut l = split_levels(&p, b1, b2);
if scale < 0.0 {
flip_levels(&mut l);
scale = -scale;
shift = -shift;
}
let values = if shift == 1 { &XP } else { &XM };
let (indices, all) = iq1_s_resolve(g, &mut l, (xb, w), scale, values)?;
if !all {
scale = iq1_s_refit(g, &indices, (xb, w), values, scale);
}
Ok(Some(Iq1Fit { scale, shift, indices }))
}
/// Prefix sums of w*x and w over the values in sorted order (index 0 is the empty prefix).
fn iq1_prefix(p: &[Pair; 32], xb: &[f32], w: &[f32; 32]) -> ([f32; 33], [f32; 33]) {
/// Prefix sums of `w*x` and of `w` along the sorted order `p`.
fn prefix_sums(w: &[f32; 32], xb: &[f32], p: &[Pair; 32]) -> ([f32; 33], [f32; 33]) {
let mut sx = [0.0; 33];
let mut sw = sx;
for j in 0..32 {
@@ -152,41 +59,37 @@ fn iq1_prefix(p: &[Pair; 32], xb: &[f32], w: &[f32; 32]) -> ([f32; 33], [f32; 33
}
(sx, sw)
}
/// The split points and sign with the best fit as (scale, shift, b1, b2); None when no split fits.
fn iq1_s_search(prefix: &([f32; 33], [f32; 33]), max: f32) -> Option<(f32, i8, usize, usize)> {
let mut best = -f32::MAX;
let mut scale = max;
let (mut b1, mut b2, mut shift) = (-1i32, -1i32, 0i8);
for i1 in 0..=32 {
for i2 in i1..=32 {
for (values, s) in [(&XP, 1i8), (&XM, -1i8)] {
let (qx, q2) = iq1_s_sums(prefix, (i1, i2), values);
if q2 > 0.0 && qx * qx > best * q2 {
scale = qx / q2;
best = scale * qx;
b1 = i1 as i32;
b2 = i2 as i32;
shift = s;
}
}
}
}
if b1 < 0 || b2 < 0 || shift == 0 { None } else { Some((scale, shift, b1 as usize, b2 as usize)) }
}
fn iq1_s_sums(prefix: &([f32; 33], [f32; 33]), split: (usize, usize), values: &[f32; 3]) -> (f32, f32) {
let (sx, sw) = prefix;
let (i1, i2) = split;
/// `sum(w*x*v)` and `sum(w*v*v)` of the split at `i1`, `i2` when the three runs take the levels `values`.
fn split_moments(sx: &[f32; 33], sw: &[f32; 33], (i1, i2): (usize, usize), values: &[f32; 3]) -> (f32, f32) {
let qx = (sx[i1] - sx[0]) * values[0] + (sx[i2] - sx[i1]) * values[1] + (sx[32] - sx[i2]) * values[2];
let q2 = (sw[i1] - sw[0]) * values[0] * values[0]
+ (sw[i2] - sw[i1]) * values[1] * values[1]
+ (sw[32] - sw[i2]) * values[2] * values[2];
(qx, q2)
}
/// Grid indices of the four groups of 8 and whether all of them sat on the grid; `xw` is (x, w).
fn iq1_s_resolve(
/// The split of the sorted block with the best fit over both shift variants, if any trial had positive weight.
fn best_split(sx: &[f32; 33], sw: &[f32; 33]) -> Option<Split> {
let mut best = -f32::MAX;
let mut found = None;
for i1 in 0..=32 {
for i2 in i1..=32 {
for (values, tag) in [(&XP, 1i8), (&XM, -1i8)] {
let (qx, q2) = split_moments(sx, sw, (i1, i2), values);
if q2 > 0.0 && qx * qx > best * q2 {
let scale = qx / q2;
best = scale * qx;
found = Some(Split { scale, b1: i1, b2: i2, tag });
}
}
}
}
found
}
/// The grid indices of the four groups of eight, and whether all of them were on the grid already.
fn resolve_s_groups(
g: &Grid,
l: &mut [i8; 32],
xw: (&[f32], &[f32; 32]),
(xb, w): (&[f32], &[f32]),
scale: f32,
values: &[f32; 3],
) -> Result<([usize; 4], bool)> {
@@ -194,28 +97,59 @@ fn iq1_s_resolve(
let mut all = true;
for k in 0..4 {
let at = k * 8;
let (index, on) = g.resolve_one(&mut l[at..at + 8], (&xw.0[at..at + 8], &xw.1[at..at + 8]), scale, values)?;
let (index, on) = g.resolve_one(&mut l[at..at + 8], &xb[at..at + 8], &w[at..at + 8], scale, values)?;
indices[k] = index;
all &= on;
}
Ok((indices, all))
}
/// The scale refit against the chosen grid points; unchanged unless both sums are positive. `xw` is (x, w).
fn iq1_s_refit(g: &Grid, indices: &[usize; 4], xw: (&[f32], &[f32; 32]), values: &[f32; 3], scale: f32) -> f32 {
let (xb, w) = xw;
let (mut qx, mut q2) = (0.0, 0.0);
/// The scale refitted to the resolved grid points, kept when the fit has positive moments.
fn refit_s_scale(g: &Grid, indices: &[usize; 4], (xb, w): (&[f32], &[f32]), values: &[f32; 3], scale: f32) -> f32 {
let mut acc = (0.0, 0.0);
for k in 0..4 {
let p = &g.points[indices[k]];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize];
qx += w[k * 8 + j] * q * xb[k * 8 + j];
q2 += w[k * 8 + j] * q * q;
}
let at = k * 8;
acc = accumulate_group(g, indices[k], (&xb[at..at + 8], &w[at..at + 8]), (values, 1.0), acc);
}
if qx > 0.0 && q2 > 0.0 { qx / q2 } else { scale }
if acc.0 > 0.0 && acc.1 > 0.0 { acc.0 / acc.1 } else { scale }
}
/// The block-scale levels and shift flags (with the 3-bit group heads) and the super-block scale.
fn iq1_s_scales(y: &mut [u8], maxs: f32, scales: &[f32; 8], shifts: &[i8; 8], heads: &mut [u16; 8]) {
/// One fitted IQ1_S sub-block of 32 values: the four grid indices, the scale and the shift sign.
struct S1Block {
indices: [usize; 4],
scale: f32,
shift: i8,
}
fn s1_block(g: &Grid, xb: &[f32], w: &[f32; 32]) -> Result<Option<S1Block>> {
if max_abs(xb) < 1e-12 {
return Ok(None);
}
let p = pairs::<32>(xb);
let (sx, sw) = prefix_sums(w, xb, &p);
let Some(split) = best_split(&sx, &sw) else { return Ok(None) };
let mut l = three_levels(&p, split.b1, split.b2);
let (mut scale, mut shift) = (split.scale, split.tag);
if scale < 0.0 {
flip_levels(&mut l);
scale = -scale;
shift = -shift;
}
let values = if shift == 1 { &XP } else { &XM };
let (indices, all) = resolve_s_groups(g, &mut l, (xb, w), scale, values)?;
if !all {
scale = refit_s_scale(g, &indices, (xb, w), values, scale);
}
Ok(Some(S1Block { indices, scale, shift }))
}
/// Writes the index bytes of sub-block `ib` and returns its word of ninth index bits.
fn s1_put_indices(y: &mut [u8], ib: usize, indices: &[usize; 4]) -> u16 {
let mut high = 0u16;
for k in 0..4 {
y[2 + ib * 4 + k] = indices[k] as u8;
high |= ((indices[k] >> 8) as u16) << (3 * k);
}
high
}
/// Writes the super-block scale and the per-sub-block scale codes with their shift bit.
fn s1_finish(y: &mut [u8], heads: &mut [u16; 8], (scales, shifts): (&[f32; 8], &[i8; 8]), maxs: f32) {
let d = maxs / 15.0;
put_h(y, d * 1.125);
let inv = 1.0 / d;
@@ -228,3 +162,28 @@ fn iq1_s_scales(y: &mut [u8], maxs: f32, scales: &[f32; 8], shifts: &[i8; 8], he
y[34 + ib * 2..36 + ib * 2].copy_from_slice(&heads[ib].to_le_bytes());
}
}
pub(super) fn iq1_s(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
y.fill(0);
let mut scales = [0.0; 8];
let mut shifts = [1i8; 8];
let mut heads = [0u16; 8];
let sigma = 2.0 * sum_squares(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
let at = ib * 32;
let xb = &x[at..at + 32];
let w: [f32; 32] = block_weights(xb, at, Some(qw), sigma, |_| 0.0);
let Some(b) = s1_block(g, xb, &w)? else { continue };
heads[ib] = s1_put_indices(y, ib, &b.indices);
scales[ib] = b.scale;
shifts[ib] = b.shift;
if b.scale > maxs {
maxs = b.scale;
}
}
if maxs == 0.0 {
return Ok(());
}
s1_finish(y, &mut heads, (&scales, &shifts), maxs);
Ok(())
}
@@ -1,99 +1,18 @@
//! Moved out of the parent module by STRA-338: fn iq1_m, fn row.
use super::alloc_fn::{sum_sq, weights};
use super::impl_grid::{abs_max, flip_levels, split_levels};
#[allow(unused_imports)]
use super::*;
/// What the IQ1_M search settled on for one block of 16.
struct Iq1MFit {
scale: f32,
which: usize,
indices: [usize; 2],
}
pub(super) fn iq1_m(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
y.fill(0);
let mut scales = [0.0; 16];
let mut shifts = [0usize; 16];
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let xb = &x[at..at + 16];
let w: [f32; 16] = weights(xb, qw.map(|q| &q[at..at + 16]), sigma, |v| v * v);
let Some(fit) = iq1_m_block(g, xb, &w)? else { continue };
y[2 * ib] = fit.indices[0] as u8;
y[2 * ib + 1] = fit.indices[1] as u8;
y[32 + ib] = (fit.indices[0] >> 8) as u8 | (((fit.indices[1] >> 8) as u8) << 4);
scales[ib] = fit.scale;
shifts[ib] = fit.which;
if fit.scale > maxs {
maxs = fit.scale;
}
}
if maxs == 0.0 {
return Ok(());
}
iq1_m_scales(g, (x, y), (qw, sigma), (&scales, &shifts), maxs);
Ok(())
}
/// The values (+ or - shifted grid) of half `k` of a block of 16 for the shift pattern `which`.
fn half_values(k: usize, which: usize) -> &'static [f32; 3] {
/// The level values of group `k` for the delta pattern `which`: bit 1 picks the first group's sign, bit 0 the second's.
fn group_values(k: usize, which: usize) -> &'static [f32; 3] {
if (k == 0 && which < 2) || (k == 1 && which % 2 == 0) { &XP } else { &XM }
}
/// The fit of one block of 16; None for a block the search leaves empty.
fn iq1_m_block(g: &Grid, xb: &[f32], w: &[f32; 16]) -> Result<Option<Iq1MFit>> {
let max = abs_max(xb);
if max < 1e-7 {
return Ok(None);
}
let p = pairs::<16>(xb);
let Some((mut scale, mut which, b1, b2)) = iq1_m_search(&p, (xb, w), max) else { return Ok(None) };
let mut l = split_levels(&p, b1, b2);
if scale < 0.0 {
flip_levels(&mut l);
scale = -scale;
which = 3 - which;
}
let mut indices = [0usize; 2];
let mut all = true;
for k in 0..2 {
let at = k * 8;
let xw = (&xb[at..at + 8], &w[at..at + 8]);
let (index, on) = g.resolve_one(&mut l[at..at + 8], xw, scale, half_values(k, which))?;
indices[k] = index;
all &= on;
}
if !all {
scale = iq1_m_refit(g, &indices, (xb, w), (which, scale));
}
Ok(Some(Iq1MFit { scale, which, indices }))
/// The level values element `i` takes in the search under delta pattern `k`.
fn search_values(i: usize, k: usize) -> &'static [f32; 3] {
if (i < 8 && k < 2) || (i >= 8 && k % 2 == 0) { &XP } else { &XM }
}
/// The split points and shift pattern with the best fit as (scale, which, b1, b2); None when no split fits.
fn iq1_m_search(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), max: f32) -> Option<(f32, usize, usize, usize)> {
let mut best = -f32::MAX;
let mut scale = max;
let (mut b1, mut b2, mut which) = (-1i32, -1i32, -1i32);
for i1 in 0..=16 {
for i2 in i1..=16 {
let (qx, q2) = iq1_m_sums(p, xw, (i1, i2));
for k in 0..4 {
if q2[k] > 0.0 && qx[k] * qx[k] > best * q2[k] {
scale = qx[k] / q2[k];
best = scale * qx[k];
b1 = i1 as i32;
b2 = i2 as i32;
which = k as i32;
}
}
}
}
if b1 < 0 || b2 < 0 || which < 0 { None } else { Some((scale, which as usize, b1 as usize, b2 as usize)) }
}
/// The weighted sums (sum w*q*x, sum w*q*q) of the four shift patterns for the split `(i1, i2)`.
fn iq1_m_sums(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), split: (usize, usize)) -> ([f32; 4], [f32; 4]) {
let (xb, w) = xw;
let (i1, i2) = split;
/// `sum(w*x*v)` and `sum(w*v*v)` of the split at `i1`, `i2` for each of the four delta patterns.
fn pattern_moments(w: &[f32; 16], xb: &[f32], p: &[Pair; 16], (i1, i2): (usize, usize)) -> ([f32; 4], [f32; 4]) {
let mut qx = [0.0; 4];
let mut q2 = qx;
for j in 0..16 {
@@ -106,63 +25,136 @@ fn iq1_m_sums(p: &[Pair; 16], xw: (&[f32], &[f32; 16]), split: (usize, usize)) -
2
};
for k in 0..4 {
let vals = if (i < 8 && k < 2) || (i >= 8 && k % 2 == 0) { &XP } else { &XM };
let vals = search_values(i, k);
qx[k] += w[i] * vals[value] * xb[i];
q2[k] += w[i] * vals[value] * vals[value];
}
}
(qx, q2)
}
/// The scale refit against the chosen grid points; unchanged unless both sums are positive.
/// `shape` is (which, scale).
fn iq1_m_refit(g: &Grid, indices: &[usize; 2], xw: (&[f32], &[f32; 16]), shape: (usize, f32)) -> f32 {
let (xb, w) = xw;
let (which, scale) = shape;
let (mut qx, mut q2) = (0.0, 0.0);
for k in 0..2 {
let values = half_values(k, which);
let p = &g.points[indices[k]];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize];
qx += w[k * 8 + j] * q * xb[k * 8 + j];
q2 += w[k * 8 + j] * q * q;
/// The split and delta pattern of the sorted block with the best fit, if any trial had positive weight.
fn best_pattern_split(w: &[f32; 16], xb: &[f32], p: &[Pair; 16]) -> Option<Split> {
let mut best = -f32::MAX;
let mut found = None;
for i1 in 0..=16 {
for i2 in i1..=16 {
let (qx, q2) = pattern_moments(w, xb, p, (i1, i2));
for k in 0..4 {
if q2[k] > 0.0 && qx[k] * qx[k] > best * q2[k] {
let scale = qx[k] / q2[k];
best = scale * qx[k];
found = Some(Split { scale, b1: i1, b2: i2, tag: k as i8 });
}
}
}
}
if qx > 0.0 && q2 > 0.0 { qx / q2 } else { scale }
found
}
/// Block-scale levels and shift flags into y, and the super-block scale refit against the stored indices.
/// `xy` is (x, y), `im` is (imatrix, sigma) and `blocks` is (scales, shifts).
fn iq1_m_scales(
/// The grid indices of the two groups of eight, and whether both were on the grid already.
fn resolve_m_groups(
g: &Grid,
xy: (&[f32], &mut [u8]),
im: (Option<&[f32]>, f32),
blocks: (&[f32; 16], &[usize; 16]),
maxs: f32,
) {
let (x, y) = xy;
let (qw, sigma) = im;
let (scales, shifts) = blocks;
let mut d = maxs / 15.0;
let inv = 1.0 / d;
let mut sc = [0u16; 4];
l: &mut [i8; 16],
(xb, w): (&[f32], &[f32]),
(scale, which): (f32, usize),
) -> Result<([usize; 2], bool)> {
let mut indices = [0usize; 2];
let mut all = true;
for k in 0..2 {
let at = k * 8;
let values = group_values(k, which);
let (index, on) = g.resolve_one(&mut l[at..at + 8], &xb[at..at + 8], &w[at..at + 8], scale, values)?;
indices[k] = index;
all &= on;
}
Ok((indices, all))
}
/// The scale refitted to the resolved grid points, kept when the fit has positive moments.
fn refit_m_scale(g: &Grid, indices: &[usize; 2], (xb, w): (&[f32], &[f32]), (scale, which): (f32, usize)) -> f32 {
let mut acc = (0.0, 0.0);
for k in 0..2 {
let at = k * 8;
let values = group_values(k, which);
acc = accumulate_group(g, indices[k], (&xb[at..at + 8], &w[at..at + 8]), (values, 1.0), acc);
}
if acc.0 > 0.0 && acc.1 > 0.0 { acc.0 / acc.1 } else { scale }
}
/// One fitted IQ1_M sub-block of 16 values: the two grid indices, the scale and the delta pattern.
struct M1Block {
indices: [usize; 2],
scale: f32,
which: usize,
}
fn m1_block(g: &Grid, xb: &[f32], w: &[f32; 16]) -> Result<Option<M1Block>> {
if max_abs(xb) < 1e-7 {
return Ok(None);
}
let p = pairs::<16>(xb);
let Some(split) = best_pattern_split(w, xb, &p) else { return Ok(None) };
let mut l = three_levels(&p, split.b1, split.b2);
let (mut scale, mut which) = (split.scale, split.tag as usize);
if scale < 0.0 {
flip_levels(&mut l);
scale = -scale;
which = 3 - which;
}
let (indices, all) = resolve_m_groups(g, &mut l, (xb, w), (scale, which))?;
if !all {
scale = refit_m_scale(g, &indices, (xb, w), (scale, which));
}
Ok(Some(M1Block { indices, scale, which }))
}
/// Writes the index bytes and the ninth-bit nibbles of sub-block `ib`.
fn m1_put_indices(y: &mut [u8], ib: usize, indices: &[usize; 2]) {
y[2 * ib] = indices[0] as u8;
y[2 * ib + 1] = indices[1] as u8;
y[32 + ib] = (indices[0] >> 8) as u8 | (((indices[1] >> 8) as u8) << 4);
}
/// The scale and delta-pattern state of the sub-blocks after the search.
struct M1Scales {
scales: [f32; 16],
shifts: [usize; 16],
maxs: f32,
}
/// Quantizes the sub-block scales to 3 bits (packed four to a word) and ORs each delta pattern into `y[32 + ib]`.
fn write_m1_scale_codes(y: &mut [u8], st: &M1Scales) -> ([u16; 4], [i32; 16]) {
let inv = 1.0 / (st.maxs / 15.0);
let masks = [0u8, 128, 8, 136];
let mut sc = [0u16; 4];
let mut codes = [0i32; 16];
for ib in 0..16 {
let l = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 7);
let l = nearest(0.5 * (inv * st.scales[ib] - 1.0)).clamp(0, 7);
sc[ib / 4] |= (l as u16) << (3 * (ib % 4));
y[32 + ib] |= masks[shifts[ib]];
y[32 + ib] |= masks[st.shifts[ib]];
codes[ib] = l;
}
(sc, codes)
}
/// `sum(w*x*q)` and `sum(w*q*q)` of the stored grid points scaled by their sub-block codes, in sub-block order.
fn m1_stored_moments(
g: &Grid,
y: &[u8],
x: &[f32],
(qw, sigma): (Option<&[f32]>, f32),
st: &M1Scales,
codes: &[i32; 16],
) -> (f32, f32) {
let mut acc = (0.0, 0.0);
for ib in 0..16 {
let at = ib * 16;
let xb = &x[at..at + 16];
let w: [f32; 16] = weights(xb, qw.map(|q| &q[at..at + 16]), sigma, |v| v * v);
iq1_m_accumulate(g, y, (ib, shifts[ib], l), (xb, &w), &mut acc);
let w: [f32; 16] = block_weights(xb, at, qw, sigma, |i| xb[i] * xb[i]);
for k in 0..2 {
let values = group_values(k, st.shifts[ib]);
let index = y[2 * ib + k] as usize | (((y[32 + ib] as usize) << (8 - 4 * k)) & 0x700);
let range = k * 8..k * 8 + 8;
let mult = (2 * codes[ib] + 1) as f32;
acc = accumulate_group(g, index, (&xb[range.clone()], &w[range]), (values, mult), acc);
}
}
if acc.1 > 0.0 {
d = acc.0 / acc.1;
}
iq1_m_store_scales(y, sc, d);
acc
}
/// Spreads the half-precision super-block scale over the top nibbles of the four scale words and stores them.
fn iq1_m_store_scales(y: &mut [u8], mut sc: [u16; 4], d: f32) {
/// Writes the half-float super-block scale into the top nibbles of the four scale words, then the words.
fn put_m1_scale_words(y: &mut [u8], mut sc: [u16; 4], d: f32) {
let packed = half_rn(d * 1.1125);
sc[0] |= (packed & 15) << 12;
sc[1] |= (packed & 0xf0) << 8;
@@ -172,40 +164,54 @@ fn iq1_m_store_scales(y: &mut [u8], mut sc: [u16; 4], d: f32) {
y[48 + i * 2..50 + i * 2].copy_from_slice(&v.to_le_bytes());
}
}
/// Adds block `ib`'s (sum w*q*x, sum w*q*q) at the stored grid indices and block scale level to `acc`;
/// `block` is (ib, shift pattern, scale level).
fn iq1_m_accumulate(g: &Grid, y: &[u8], block: (usize, usize, i32), xw: (&[f32], &[f32; 16]), acc: &mut (f32, f32)) {
let (ib, shift, l) = block;
let (xb, w) = xw;
for k in 0..2 {
let values = half_values(k, shift);
let index = y[2 * ib + k] as usize | (((y[32 + ib] as usize) << (8 - 4 * k)) & 0x700);
let p = &g.points[index];
for j in 0..8 {
let q = values[((p[j] - 1) / 2) as usize] * (2 * l + 1) as f32;
acc.0 += w[k * 8 + j] * q * xb[k * 8 + j];
acc.1 += w[k * 8 + j] * q * q;
fn finish_m1(g: &Grid, y: &mut [u8], x: &[f32], weighting: (Option<&[f32]>, f32), st: &M1Scales) {
let mut d = st.maxs / 15.0;
let (sc, codes) = write_m1_scale_codes(y, st);
let (qx, q2) = m1_stored_moments(g, y, x, weighting, st, &codes);
if q2 > 0.0 {
d = qx / q2;
}
put_m1_scale_words(y, sc, d);
}
pub(super) fn iq1_m(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
y.fill(0);
let mut st = M1Scales { scales: [0.0; 16], shifts: [0; 16], maxs: 0.0 };
let sigma = 2.0 * sum_squares(x) / 256.0;
for ib in 0..16 {
let at = ib * 16;
let xb = &x[at..at + 16];
let w: [f32; 16] = block_weights(xb, at, qw, sigma, |i| xb[i] * xb[i]);
let Some(b) = m1_block(g, xb, &w)? else { continue };
m1_put_indices(y, ib, &b.indices);
st.scales[ib] = b.scale;
st.shifts[ib] = b.which;
if b.scale > st.maxs {
st.maxs = b.scale;
}
}
if st.maxs == 0.0 {
return Ok(());
}
finish_m1(g, y, x, (qw, sigma), &st);
Ok(())
}
fn row_block(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], w: Option<&[f32]>) -> Result<()> {
let required = || w.ok_or(Error::Shape);
match kind {
Kind::Iq2Xxs => required().and_then(|w| iq2_xxs(g, x, y, w)),
Kind::Iq2Xs => required().and_then(|w| iq2_xs(g, x, y, w)),
Kind::Iq2S => iq2_s(g, x, y, w),
Kind::Iq3Xxs | Kind::Iq3S => iq3(g, kind, x, y, w),
Kind::Iq1S => required().and_then(|w| iq1_s(g, x, y, w)),
Kind::Iq1M => iq1_m(g, x, y, w),
_ => Err(Error::Unsupported),
}
}
pub(in super::super) fn row(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let g = grid(kind)?;
for (i, (x, y)) in x.chunks_exact(256).zip(y.chunks_exact_mut(kind.block().1)).enumerate() {
let w = qw.map(|q| &q[i * 256..i * 256 + 256]);
row_block(kind, &g, (x, y), w)?;
row_block(&g, kind, x, y, w)?;
}
Ok(())
}
/// Quantizes one 256-value block with the quantizer of `kind`.
fn row_block(kind: Kind, g: &Grid, xy: (&[f32], &mut [u8]), w: Option<&[f32]>) -> Result<()> {
let (x, y) = xy;
match kind {
Kind::Iq2Xxs => iq2_xxs(g, x, y, w.ok_or(Error::Shape)?),
Kind::Iq2Xs => iq2_xs(g, x, y, w.ok_or(Error::Shape)?),
Kind::Iq2S => iq2_s(g, x, y, w),
Kind::Iq3Xxs | Kind::Iq3S => iq3(g, kind, x, y, w),
Kind::Iq1S => iq1_s(g, x, y, w.ok_or(Error::Shape)?),
Kind::Iq1M => iq1_m(g, x, y, w),
_ => Err(Error::Unsupported),
}
}
@@ -1,36 +1,73 @@
//! Moved out of the parent module by STRA-338: fn iq2_xxs, fn iq2_xs.
use super::alloc_fn::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights};
#[allow(unused_imports)]
use super::*;
pub(super) fn iq2_xxs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
let mut scales = [0.0; 8];
let mut q2 = [0u32; 16];
y.fill(0);
put_h(y, 0.0);
let sigma = sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
let at = ib * 32;
let Some((scale, l, sign)) = iq2_xxs_block(g, &x[at..at + 32], &qw[at..at + 32], sigma) else { continue };
for k in 0..4 {
let i = g.index(&l[k * 8..k * 8 + 8])?;
q2[2 * ib] |= (i as u32) << (8 * k);
q2[2 * ib + 1] |= (sign[k] as u32) << (7 * k);
}
scales[ib] = scale;
if scale > maxs {
maxs = scale;
/// One fitted IQ2_XXS sub-block of 32 values: levels, sign bytes and scale.
struct Xxs {
l: [i8; 32],
sign: [u8; 4],
scale: f32,
}
/// Scale of the best of the 13 trials around `effective`, with the levels it produced.
fn xxs_search(g: &Grid, b: &Folded<32>, effective: f32, first: ([i8; 32], f32)) -> ([i8; 32], f32) {
let (mut l, mut scale) = first;
let mut best = 0.0;
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 (sx, s2) = totals(b.xv, b.w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
scale = sx / s2;
best = scale * sx;
l = aux;
}
}
if maxs != 0.0 {
iq2_xxs_finish(y, &mut q2, &scales, maxs);
(l, scale)
}
/// Re-rounds all levels against the fitted scale and refits the scale to them.
fn xxs_refit(g: &Grid, b: &Folded<32>, l: &mut [i8; 32], scale: f32) -> f32 {
quant_candidates(g, 1.0 / scale, b.xv, b.wa, scale, l, 3, &mut [false; 4]);
let (sx, s2) = totals(b.xv, b.w, l);
if s2 > 0.0 { sx / s2 } else { scale }
}
fn xxs_block(g: &Grid, xb: &[f32], at: usize, qw: &[f32], sigma: f32) -> Option<Xxs> {
let w: [f32; 32] = block_weights(xb, at, Some(qw), sigma, |_| 0.0);
let wa = square_roots(&w);
let (xv, mut sign) = signs::<32>(xb, &w, true);
if max_value(&xv) < 1e-15 {
return None;
}
let mut lp = [0u8; 32];
let mut scale = qp(&xv, 4, &mut lp, &w);
let mut l: [i8; 32] = std::array::from_fn(|i| lp[i] as i8);
let effective = scale * 3.0;
if effective <= 0.0 {
return None;
}
let b = Folded { xv: &xv, w: &w, wa: &wa };
(l, scale) = xxs_search(g, &b, effective, (l, scale));
if scale > 0.0 {
scale = xxs_refit(g, &b, &mut l, scale);
}
if scale < 0.0 {
scale = -scale;
negate_signs(&mut sign, 127);
}
Some(Xxs { l, sign, scale })
}
/// Packs the four grid indices and sign groups of sub-block `ib` into the 32-bit words `q2`.
fn xxs_store(g: &Grid, q2: &mut [u32; 16], ib: usize, b: &Xxs) -> Result<()> {
for k in 0..4 {
let i = g.index(&b.l[k * 8..k * 8 + 8])?;
q2[2 * ib] |= (i as u32) << (8 * k);
q2[2 * ib + 1] |= (b.sign[k] as u32) << (7 * k);
}
Ok(())
}
/// Writes the super-block scale, merges the block scale levels into the packed words and stores them.
fn iq2_xxs_finish(y: &mut [u8], q2: &mut [u32; 16], scales: &[f32; 8], maxs: f32) {
/// Adds the 4-bit sub-block scale codes and writes the packed words.
fn xxs_finish(y: &mut [u8], q2: &mut [u32; 16], scales: &[f32; 8], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d);
let inv = 1.0 / d;
@@ -41,75 +78,60 @@ fn iq2_xxs_finish(y: &mut [u8], q2: &mut [u32; 16], scales: &[f32; 8], maxs: f32
y[2 + i * 4..6 + i * 4].copy_from_slice(&v.to_le_bytes());
}
}
/// (scale, levels, sign bytes) of one block of 32; None for a block that stays empty.
fn iq2_xxs_block(g: &Grid, xb: &[f32], qb: &[f32], sigma: f32) -> Option<(f32, [i8; 32], [u8; 4])> {
let b = Block::<32>::new(xb, weights(xb, Some(qb), sigma, |v| v * v), true);
if vmax(&b.xv) < 1e-15 {
return None;
}
let mut lp = [0u8; 32];
let scale = qp(&b.xv, 4, &mut lp, &b.w);
let effective = scale * 3.0;
if effective <= 0.0 {
return None;
}
let (mut scale, l) = iq2_xxs_search(g, &b, (scale, lp.map(|v| v as i8)), effective);
let mut sign = b.sign;
if scale < 0.0 {
scale = -scale;
flip(&mut sign, 127);
}
Some((scale, l, sign))
}
/// Tries the 13 scales around `effective`, keeps the best levels, then re-quantizes them at the final scale;
/// `start` is the initial (scale, levels).
fn iq2_xxs_search(g: &Grid, b: &Block<32>, start: (f32, [i8; 32]), effective: f32) -> (f32, [i8; 32]) {
let (mut scale, mut l) = start;
let mut best = 0.0;
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 (sx, s2) = totals(&b.xv, &b.w, &aux);
if s2 > 0.0 && sx * sx > best * s2 {
scale = sx / s2;
best = scale * sx;
l = aux;
}
}
if scale > 0.0 {
quant_candidates(g, 1.0 / scale, &b.xv, &b.wa, scale, &mut l, 3, &mut [false; 4]);
let (sx, s2) = totals(&b.xv, &b.w, &l);
if s2 > 0.0 {
scale = sx / s2;
}
}
(scale, l)
}
pub(super) fn iq2_xs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
let mut scales = [0.0; 16];
let mut q2 = [0u16; 32];
pub(super) fn iq2_xxs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
let mut scales = [0.0; 8];
let mut q2 = [0u32; 16];
y.fill(0);
let sigma = sum_sq(x) / 256.0;
put_h(y, 0.0);
let sigma = sum_squares(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let Some((scale, l, sign)) = iq2_xs_block(g, &x[at..at + 16], &qw[at..at + 16], sigma) else { continue };
for k in 0..2 {
q2[2 * ib + k] = g.index(&l[k * 8..k * 8 + 8])? as u16 | ((sign[k] as u16) << 9);
}
scales[ib] = scale;
if scale > maxs {
maxs = scale;
for ib in 0..8 {
let at = ib * 32;
let Some(b) = xxs_block(g, &x[at..at + 32], at, qw, sigma) else { continue };
xxs_store(g, &mut q2, ib, &b)?;
scales[ib] = b.scale;
if b.scale > maxs {
maxs = b.scale;
}
}
if maxs != 0.0 {
iq2_xs_finish(y, &q2, &scales, maxs);
if maxs == 0.0 {
return Ok(());
}
xxs_finish(y, &mut q2, &scales, maxs);
Ok(())
}
/// One fitted IQ2_XS sub-block of 16 values: levels, sign bytes and scale.
struct Xs {
l: [i8; 16],
sign: [u8; 4],
scale: f32,
}
fn xs_block(g: &Grid, xb: &[f32], at: usize, qw: &[f32], sigma: f32) -> Option<Xs> {
let w: [f32; 16] = block_weights(xb, at, Some(qw), sigma, |_| 0.0);
let wa = square_roots(&w);
let (xv, mut sign) = signs::<16>(xb, &w, true);
let max = max_value(&xv);
if max < 1e-15 {
return None;
}
let b = Folded { xv: &xv, w: &w, wa: &wa };
let mut fit = search_scale(g, &b, max, &Plan { center: 5.0, step: 0.1, tries: 9, top: 3 }, [true; 2]);
refit_off_grid(g, &b, &mut fit, 3, false);
if fit.scale < 0.0 {
fit.scale = -fit.scale;
negate_signs(&mut sign[..2], 127);
}
Some(Xs { l: fit.l, sign, scale: fit.scale })
}
/// Packs the two grid indices and 7-bit signs of sub-block `ib` into the 16-bit words `q2`.
fn xs_store(g: &Grid, q2: &mut [u16; 32], ib: usize, b: &Xs) -> Result<()> {
for k in 0..2 {
q2[2 * ib + k] = g.index(&b.l[k * 8..k * 8 + 8])? as u16 | ((b.sign[k] as u16) << 9);
}
Ok(())
}
/// Writes the super-block scale, the block scale levels and the packed words.
fn iq2_xs_finish(y: &mut [u8], q2: &[u16; 32], scales: &[f32; 16], maxs: f32) {
/// Writes the 4-bit sub-block scale codes and the packed words.
fn xs_finish(y: &mut [u8], q2: &[u16; 32], scales: &[f32; 16], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d);
let inv = 1.0 / d;
@@ -121,20 +143,24 @@ fn iq2_xs_finish(y: &mut [u8], q2: &[u16; 32], scales: &[f32; 16], maxs: f32) {
y[2 + i * 2..4 + i * 2].copy_from_slice(&v.to_le_bytes());
}
}
/// (scale, levels, sign bytes) of one block of 16; None for a block that stays empty.
fn iq2_xs_block(g: &Grid, xb: &[f32], qb: &[f32], sigma: f32) -> Option<(f32, [i8; 16], [u8; 4])> {
let b = Block::<16>::new(xb, weights(xb, Some(qb), sigma, |v| v * v), true);
let max = vmax(&b.xv);
if max < 1e-15 {
return None;
pub(super) fn iq2_xs(g: &Grid, x: &[f32], y: &mut [u8], qw: &[f32]) -> Result<()> {
let mut scales = [0.0; 16];
let mut q2 = [0u16; 32];
y.fill(0);
let sigma = sum_squares(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let Some(b) = xs_block(g, &x[at..at + 16], at, qw, sigma) else { continue };
xs_store(g, &mut q2, ib, &b)?;
scales[ib] = b.scale;
if b.scale > maxs {
maxs = b.scale;
}
}
let trial = Trial { centre: 5.0, step: 0.1, tries: 9, levels: 3 };
let mut fit = search_scale::<16, 2>(g, &b, max, trial, [true; 2]);
fix_groups(g, &b, &mut fit, true, 3);
let mut sign = b.sign;
if fit.scale < 0.0 {
fit.scale = -fit.scale;
flip(&mut sign[..2], 127);
if maxs == 0.0 {
return Ok(());
}
Some((fit.scale, fit.l, sign))
xs_finish(y, &q2, &scales, maxs);
Ok(())
}
@@ -1,123 +1,131 @@
//! Moved out of the parent module by STRA-338: fn iq3, fn iq2_s, fn compare_pair, fn pairs.
use super::alloc_fn::{Block, Trial, fix_groups, flip, search_scale, sum_sq, vmax, weights};
#[allow(unused_imports)]
use super::*;
/// The packed output of the IQ3 quantizers while the blocks are being fitted.
struct Iq3Out {
scales: [f32; 8],
flags: [u32; 8],
q3: [u8; 104],
/// One fitted IQ3 sub-block of 32 values: levels, sign bytes and scale.
struct Iq3Block {
l: [i8; 32],
sign: [u8; 4],
scale: f32,
}
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;
for k in 0..8 {
let index = g.index(&l[k * 4..k * 4 + 4])?;
self.q3[ib * 8 + k] = index as u8;
if full {
y[66 + ib] |= ((index >> 8) as u8) << k;
}
}
if full {
y[74 + ib * 4..78 + ib * 4].copy_from_slice(sign);
} else {
self.flags[ib] =
sign[0] as u32 | ((sign[1] as u32) << 7) | ((sign[2] as u32) << 14) | ((sign[3] as u32) << 21);
}
Ok(())
fn iq3_block(g: &Grid, full: bool, xb: &[f32], at: usize, qw: Option<&[f32]>, sigma: f32) -> Option<Iq3Block> {
let w: [f32; 32] = block_weights(xb, at, qw, sigma, |i| xb[i] * xb[i]);
let wa = square_roots(&w);
let (xv, mut sign) = signs::<32>(xb, &w, !full);
let max = max_value(&xv);
if (full && max == 0.0) || (!full && max < 1e-8) {
return None;
}
/// Writes the super-block scale, the block scale levels and the packed indices and flags.
fn finish(&mut self, full: bool, y: &mut [u8], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d * if full { 1.033 } else { 1.0125 });
let inv = 1.0 / d;
for ib in 0..8 {
let s = nearest(0.5 * (inv * self.scales[ib] - 1.0)).clamp(0, 15) as u8;
if full {
y[106 + ib / 2] |= s << (4 * (ib % 2));
} else {
self.flags[ib] |= (s as u32) << 28;
}
let b = Folded { xv: &xv, w: &w, wa: &wa };
let tries = if full { 9 } else { 15 };
let mut fit = search_scale(g, &b, max, &Plan { center: 15.0, step: 0.2, tries, top: 8 }, [!full; 8]);
refit_off_grid(g, &b, &mut fit, 8, full);
if fit.scale < 0.0 {
fit.scale = -fit.scale;
negate_signs(&mut sign, if full { 255 } else { 127 });
}
Some(Iq3Block { l: fit.l, sign, scale: fit.scale })
}
/// Writes the low index bytes of sub-block `ib` to `q3` (and the ninth bits to `y` for IQ3_S).
fn iq3_put_indices(g: &Grid, y: &mut [u8], q3: &mut [u8; 104], full: bool, ib: usize, l: &[i8; 32]) -> Result<()> {
for k in 0..8 {
let index = g.index(&l[k * 4..k * 4 + 4])?;
q3[ib * 8 + k] = index as u8;
if full {
y[66 + ib] |= ((index >> 8) as u8) << k;
}
y[2..66].copy_from_slice(&self.q3[..64]);
if !full {
for (i, v) in self.flags.into_iter().enumerate() {
y[66 + i * 4..70 + i * 4].copy_from_slice(&v.to_le_bytes());
}
}
Ok(())
}
/// IQ3_S keeps the sign bytes as they are, IQ3_XXS packs four 7-bit groups into one word.
fn iq3_put_signs(y: &mut [u8], flags: &mut [u32; 8], full: bool, ib: usize, sign: &[u8; 4]) {
if full {
y[74 + ib * 4..78 + ib * 4].copy_from_slice(sign);
} else {
flags[ib] = sign[0] as u32 | ((sign[1] as u32) << 7) | ((sign[2] as u32) << 14) | ((sign[3] as u32) << 21);
}
}
/// Adds the 4-bit sub-block scale codes and writes the index bytes (and the IQ3_XXS words).
fn iq3_finish(y: &mut [u8], q3: &[u8; 104], flags: &mut [u32; 8], (scales, maxs): (&[f32; 8], f32), full: bool) {
let d = maxs / 31.0;
put_h(y, d * if full { 1.033 } else { 1.0125 });
let inv = 1.0 / d;
for ib in 0..8 {
let s = nearest(0.5 * (inv * scales[ib] - 1.0)).clamp(0, 15) as u8;
if full {
y[106 + ib / 2] |= s << (4 * (ib % 2));
} else {
flags[ib] |= (s as u32) << 28;
}
}
y[2..66].copy_from_slice(&q3[..64]);
if !full {
for (i, v) in flags.iter().enumerate() {
y[66 + i * 4..70 + i * 4].copy_from_slice(&v.to_le_bytes());
}
}
}
pub(super) fn iq3(g: &Grid, kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let full = kind == Kind::Iq3S;
let mut out = Iq3Out { scales: [0.0; 8], flags: [0u32; 8], q3: [0u8; 104] };
let mut scales = [0.0; 8];
let mut flags = [0u32; 8];
let mut q3 = [0u8; 104];
y.fill(0);
let sigma = 2.0 * sum_sq(x) / 256.0;
let sigma = 2.0 * sum_squares(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..8 {
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.scales[ib] = scale;
if scale > maxs {
maxs = scale;
let Some(b) = iq3_block(g, full, &x[at..at + 32], at, qw, sigma) else { continue };
iq3_put_indices(g, y, &mut q3, full, ib, &b.l)?;
iq3_put_signs(y, &mut flags, full, ib, &b.sign);
scales[ib] = b.scale;
if b.scale > maxs {
maxs = b.scale;
}
}
if maxs == 0.0 {
return Ok(());
}
out.finish(full, y, maxs);
iq3_finish(y, &q3, &mut flags, (&scales, maxs), full);
Ok(())
}
/// (scale, levels, sign bytes) of one block of 32; None for a block that stays empty. `xq` is (x, imatrix).
fn iq3_block(g: &Grid, full: bool, xq: (&[f32], Option<&[f32]>), sigma: f32) -> Option<(f32, [i8; 32], [u8; 4])> {
let (xb, qb) = xq;
let b = Block::<32>::new(xb, weights(xb, qb, sigma, |v| v * v), !full);
let max = vmax(&b.xv);
if (full && max == 0.0) || (!full && max < 1e-8) {
/// One fitted IQ2_S sub-block of 16 values: levels, sign bytes and scale.
struct S2Block {
l: [i8; 16],
sign: [u8; 4],
scale: f32,
}
fn s2_block(g: &Grid, xb: &[f32], at: usize, qw: Option<&[f32]>, sigma: f32) -> Option<S2Block> {
let w: [f32; 16] = block_weights(xb, at, qw, sigma, |i| 0.25 * sigma + xb[i] * xb[i]);
let wa = square_roots(&w);
let (xv, mut sign) = signs::<16>(xb, &w, false);
let max = max_value(&xv);
if max < 1e-8 {
return None;
}
let trial = Trial { centre: 15.0, step: 0.2, tries: if full { 9 } else { 15 }, levels: 8 };
let mut fit = search_scale::<32, 8>(g, &b, max, trial, [!full; 8]);
fix_groups(g, &b, &mut fit, !full, 8);
let mut sign = b.sign;
let b = Folded { xv: &xv, w: &w, wa: &wa };
let mut fit = search_scale(g, &b, max, &Plan { center: 5.0, step: 0.1, tries: 9, top: 3 }, [true; 2]);
refit_off_grid(g, &b, &mut fit, 3, false);
if fit.scale < 0.0 {
fit.scale = -fit.scale;
flip(&mut sign, if full { 255 } else { 127 });
negate_signs(&mut sign[..2], 255);
}
Some((fit.scale, fit.l, sign))
Some(S2Block { l: fit.l, sign, scale: fit.scale })
}
pub(super) fn iq2_s(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let mut scales = [0.0; 16];
y.fill(0);
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let qb = qw.map(|q| &q[at..at + 16]);
let Some((scale, l, sign)) = iq2_s_block(g, (&x[at..at + 16], qb), sigma) else { continue };
for k in 0..2 {
let index = g.index(&l[k * 8..k * 8 + 8])?;
let i8 = 2 * ib + k;
y[2 + i8] = index as u8;
y[66 + i8 / 4] |= ((index >> 8) as u8) << (2 * (i8 % 4));
y[34 + i8] = sign[k];
}
scales[ib] = scale;
if scale > maxs {
maxs = scale;
}
}
if maxs != 0.0 {
iq2_s_finish(y, &scales, maxs);
/// Writes the index bytes, ninth bits and sign bytes of the two groups of sub-block `ib`.
fn s2_store(g: &Grid, y: &mut [u8], ib: usize, b: &S2Block) -> Result<()> {
for k in 0..2 {
let index = g.index(&b.l[k * 8..k * 8 + 8])?;
let i8 = 2 * ib + k;
y[2 + i8] = index as u8;
y[66 + i8 / 4] |= ((index >> 8) as u8) << (2 * (i8 % 4));
y[34 + i8] = b.sign[k];
}
Ok(())
}
/// Writes the super-block scale and the block scale levels.
fn iq2_s_finish(y: &mut [u8], scales: &[f32; 16], maxs: f32) {
/// Writes the super-block scale and the 4-bit sub-block scale codes.
fn s2_finish(y: &mut [u8], scales: &[f32; 16], maxs: f32) {
let d = maxs / 31.0;
put_h(y, d * 0.9875);
let inv = 1.0 / d;
@@ -126,23 +134,25 @@ fn iq2_s_finish(y: &mut [u8], scales: &[f32; 16], maxs: f32) {
y[74 + ib / 2] |= s << (4 * (ib % 2));
}
}
/// (scale, levels, sign bytes) of one block of 16; None for a block that stays empty. `xq` is (x, imatrix).
fn iq2_s_block(g: &Grid, xq: (&[f32], Option<&[f32]>), sigma: f32) -> Option<(f32, [i8; 16], [u8; 4])> {
let (xb, qb) = xq;
let b = Block::<16>::new(xb, weights(xb, qb, sigma, |v| 0.25 * sigma + v * v), false);
let max = vmax(&b.xv);
if max < 1e-8 {
return None;
pub(super) fn iq2_s(g: &Grid, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) -> Result<()> {
let mut scales = [0.0; 16];
y.fill(0);
let sigma = 2.0 * sum_squares(x) / 256.0;
let mut maxs = 0.0;
for ib in 0..16 {
let at = ib * 16;
let Some(b) = s2_block(g, &x[at..at + 16], at, qw, sigma) else { continue };
s2_store(g, y, ib, &b)?;
scales[ib] = b.scale;
if b.scale > maxs {
maxs = b.scale;
}
}
let trial = Trial { centre: 5.0, step: 0.1, tries: 9, levels: 3 };
let mut fit = search_scale::<16, 2>(g, &b, max, trial, [true; 2]);
fix_groups(g, &b, &mut fit, true, 3);
let mut sign = b.sign;
if fit.scale < 0.0 {
fit.scale = -fit.scale;
flip(&mut sign[..2], 255);
if maxs == 0.0 {
return Ok(());
}
Some((fit.scale, fit.l, sign))
s2_finish(y, &scales, maxs);
Ok(())
}
pub(super) unsafe extern "C" fn compare_pair(a: *const std::ffi::c_void, b: *const std::ffi::c_void) -> i32 {
unsafe {
@@ -159,8 +169,9 @@ pub(super) unsafe extern "C" fn compare_pair(a: *const std::ffi::c_void, b: *con
}
pub(super) fn pairs<const N: usize>(x: &[f32]) -> [Pair; N] {
let mut p = std::array::from_fn(|j| Pair { value: x[j], index: j as i32 });
// SAFETY: `p` is N initialized repr(C) Pair values and compare_pair reads exactly two of them; qsort retains
// nothing. NaN keys make the comparator inconsistent and can only mis-order the (<= 256 B) array.
// SAFETY: `p` is N initialized repr(C) Pair values and compare_pair reads exactly two of them;
// qsort retains nothing. NaN keys make the comparator inconsistent and can only mis-order the
// (<= 256 B) array.
unsafe {
qsort(p.as_mut_ptr().cast(), N, std::mem::size_of::<Pair>(), compare_pair);
}
@@ -1,6 +1,5 @@
//! Moved out of the parent module by STRA-338: fn best_fp4, fn fp4, fn ternary, fn pack_k2, fn q2k, fn pack_scale3 ....
use super::nearest_fn::{Qkx, Search, sum_sq};
#[allow(unused_imports)]
use super::*;
@@ -38,18 +37,8 @@ pub(super) fn fp4(kind: Kind, x: &[f32], y: &mut [u8]) {
}
}
}
pub(super) fn ternary(kind: Kind, x: &[f32], y: &mut [u8]) {
let (a, _) = max_signed(x);
let inv = if a != 0.0 { 1.0 / a } else { 0.0 };
if kind == Kind::Tq2 {
put_h(y, 64, a);
tq2_levels(x, y, inv);
} else {
put_h(y, 52, a);
tq1_levels(x, y, inv);
}
}
fn tq2_levels(x: &[f32], y: &mut [u8], inv: f32) {
fn ternary_tq2(x: &[f32], y: &mut [u8], a: f32, inv: f32) {
put_h(y, 64, a);
for p in 0..2 {
for j in 0..32 {
let mut q = 0;
@@ -60,20 +49,35 @@ fn tq2_levels(x: &[f32], y: &mut [u8], inv: f32) {
}
}
}
fn tq1_levels(x: &[f32], y: &mut [u8], inv: f32) {
/// One base-3 byte of TQ1_0: `digits` trits taken `step` apart from `x[start + j]`, scaled to eight bits.
fn ternary_tq1_byte(x: &[f32], inv: f32, start: usize, step: usize, j: usize) -> u8 {
let digits = if start == 240 { 4 } else { 5 };
let mut q = 0u16;
for k in 0..digits {
q = q * 3 + ((x[start + k * step + j] * inv).round() as i32 + 1) as u16;
}
if start == 240 {
q *= 3;
}
((q * 256 + 242) / 243) as u8
}
fn ternary_tq1(x: &[f32], y: &mut [u8], a: f32, inv: f32) {
put_h(y, 52, a);
for (start, step, out, n) in [(0, 32, 0, 32), (160, 16, 32, 16), (240, 4, 48, 4)] {
for j in 0..n {
let mut q = 0u16;
for k in 0..if start == 240 { 4 } else { 5 } {
q = q * 3 + ((x[start + k * step + j] * inv).round() as i32 + 1) as u16;
}
if start == 240 {
q *= 3;
}
y[out + j] = ((q * 256 + 242) / 243) as u8;
y[out + j] = ternary_tq1_byte(x, inv, start, step, j);
}
}
}
pub(super) fn ternary(kind: Kind, x: &[f32], y: &mut [u8]) {
let (a, _) = max_signed(x);
let inv = if a != 0.0 { 1.0 / a } else { 0.0 };
if kind == Kind::Tq2 {
ternary_tq2(x, y, a, inv);
} else {
ternary_tq1(x, y, a, inv);
}
}
pub(super) fn pack_k2(l: &[u8], y: &mut [u8]) {
for p in 0..2 {
for j in 0..32 {
@@ -82,60 +86,63 @@ pub(super) fn pack_k2(l: &[u8], y: &mut [u8]) {
}
}
}
pub(super) fn q2k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let mut l = [0u8; 256];
let search = q2k_search(x, &mut l, qw);
let (ls, lm, d, m) = q2k_scales(&search, qw.is_some());
put_h(y, 80, d);
put_h(y, 82, m);
let (d, m) = (h(y, 80), h(y, 82));
q2k_requantize(x, y, [&ls, &lm], (d, m), &mut l);
pack_k2(&l, &mut y[16..80]);
/// The sixteen 16-element sub-block fits of a Q2_K block: scales, minimums, weight sums and their maxima.
struct Q2Fit {
l: [u8; 256],
scales: [f32; 16],
mins: [f32; 16],
sw: [f32; 16],
maxs: f32,
maxm: f32,
}
/// Best (scale, minimum) of each 16-value block, with the levels of that fit in `l`.
fn q2k_search(x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>) -> Search<16> {
let sigma = sum_sq(x) / 256.0;
let mut s = Search::<16>::new();
let plain = Qkx { rmin: -0.5, rdelta: 0.1, nstep: 15, mad: true, third: false };
fn q2_weights(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32) -> [f32; 16] {
std::array::from_fn(|j| if let Some(q) = qw { q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j].abs() })
}
fn q2_subfit(xb: &[f32], w: &[f32; 16], l: &mut [u8], weighted: bool) -> (f32, f32) {
if weighted { qkx(xb, 3, w, l, -0.9, 0.05, 36, false, true) } else { qkx(xb, 3, w, l, -0.5, 0.1, 15, true, false) }
}
fn q2_fit_blocks(x: &[f32], qw: Option<&[f32]>, sigma: f32) -> Q2Fit {
let mut f = Q2Fit { l: [0; 256], scales: [0.0; 16], mins: [0.0; 16], sw: [0.0; 16], maxs: 0.0, maxm: 0.0 };
for k in 0..16 {
let xb = &x[k * 16..k * 16 + 16];
let w: [f32; 16] = std::array::from_fn(|j| {
if let Some(q) = qw { q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j].abs() }
});
let w = q2_weights(xb, qw, k, sigma);
for &v in &w {
s.sw[k] += v;
f.sw[k] += v;
}
let (d, m) = q2_subfit(xb, &w, &mut f.l[k * 16..k * 16 + 16], qw.is_some());
f.scales[k] = d;
f.mins[k] = m;
if d > f.maxs {
f.maxs = d;
}
if m > f.maxm {
f.maxm = m;
}
let (d, m) = if qw.is_some() {
qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], Qkx::WEIGHTED)
} else {
qkx(xb, 3, &w, &mut l[k * 16..k * 16 + 16], plain)
};
s.record(k, d, m);
}
s
f
}
/// The 4-bit scale and minimum levels of the blocks and the super-block (d, m).
fn q2k_scales(s: &Search<16>, weighted: bool) -> ([u8; 16], [u8; 16], f32, f32) {
/// The 4-bit scale and minimum codes of the sixteen sub-blocks, with the super-block scale and minimum.
fn q2_scale_codes(f: &Q2Fit, weighted: bool) -> ([u8; 16], [u8; 16], f32, f32) {
let mut ls = [0u8; 16];
let mut lm = ls;
if weighted {
let (d, m) = (qp(&s.scales, 15, &mut ls, &s.sw), qp(&s.mins, 15, &mut lm, &s.sw));
let d = qp(&f.scales, 15, &mut ls, &f.sw);
let m = qp(&f.mins, 15, &mut lm, &f.sw);
return (ls, lm, d, m);
}
let (si, mi) = s.factors(15.0);
let si = if f.maxs > 0.0 { 15.0 / f.maxs } else { 0.0 };
let mi = if f.maxm > 0.0 { 15.0 / f.maxm } else { 0.0 };
for k in 0..16 {
ls[k] = nearest(si * s.scales[k]) as u8;
lm[k] = nearest(mi * s.mins[k]) as u8;
ls[k] = nearest(si * f.scales[k]) as u8;
lm[k] = nearest(mi * f.mins[k]) as u8;
}
let (d, m) = s.steps(15.0);
(ls, lm, d, m)
(ls, lm, f.maxs / 15.0, f.maxm / 15.0)
}
/// Stores the packed scales in y[..16] and requantizes the values against the stored (rounded) d and m.
fn q2k_requantize(x: &[f32], y: &mut [u8], levels: [&[u8; 16]; 2], dm: (f32, f32), l: &mut [u8; 256]) {
let [ls, lm] = levels;
let (d, m) = dm;
/// Re-derives the levels against the stored (half-rounded) scale and minimum of every sub-block.
fn q2_requantize(x: &[f32], y: &[u8], l: &mut [u8; 256]) {
let d = h(y, 80);
let m = h(y, 82);
for k in 0..16 {
y[k] = ls[k] | (lm[k] << 4);
let ds = d * (y[k] & 15) as f32;
if ds == 0.0 {
continue;
@@ -146,6 +153,18 @@ fn q2k_requantize(x: &[f32], y: &mut [u8], levels: [&[u8; 16]; 2], dm: (f32, f32
}
}
}
pub(super) fn q2k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let sigma = sum_squares(x) / 256.0;
let mut f = q2_fit_blocks(x, qw, sigma);
let (ls, lm, d, m) = q2_scale_codes(&f, qw.is_some());
put_h(y, 80, d);
put_h(y, 82, m);
for k in 0..16 {
y[k] = ls[k] | (lm[k] << 4);
}
q2_requantize(x, y, &mut f.l);
pack_k2(&f.l, &mut y[16..80]);
}
pub(super) fn pack_scale3(l: &[i8; 16], y: &mut [u8]) {
y.fill(0);
for j in 0..16 {
@@ -162,81 +181,89 @@ pub(super) fn unpack_scale3(y: &[u8], j: usize) -> i32 {
let low = if j < 8 { y[j] & 15 } else { y[j - 8] >> 4 };
(low | (((y[8 + j % 4] >> (2 * (j / 4))) & 3) << 4)) as i32 - 32
}
pub(super) fn q3k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let mut l = [0i8; 256];
let (scales, sw, maxs) = q3k_search(x, &mut l, qw);
let mut ls = [0i8; 16];
let d = q3k_scale(&scales, &sw, maxs, &mut ls, qw.is_some());
pack_scale3(&ls, &mut y[96..108]);
put_h(y, 108, d);
let d = h(y, 108);
q3k_requantize(x, y, d, &mut l);
q3k_pack(y, &mut l);
/// The sixteen 16-element sub-block scales of a Q3_K block, their weight sums and the largest-magnitude scale.
struct Q3Fit {
l: [i8; 256],
scales: [f32; 16],
sw: [f32; 16],
maxs: f32,
}
/// The scale of each 16-value block (levels of that fit in `l`), the block weights, and the scale of largest magnitude.
fn q3k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], [f32; 16], f32) {
let mut scales = [0.0; 16];
let mut sw = scales;
let mut maxs = 0.0;
/// The scale of one sub-block and the sum of its weights (zero without an imatrix).
fn q3_subfit(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32, l: &mut [i8]) -> (f32, f32) {
let Some(q) = qw else {
return (q3(xb, l), 0.0);
};
let w: [f32; 16] = std::array::from_fn(|j| q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt());
let mut sw = 0.0;
for &v in &w {
sw += v;
}
(qx(xb, 4, l, 1, Some(&w)), sw)
}
fn q3k_fit_blocks(x: &[f32], qw: Option<&[f32]>, sigma: f32) -> Q3Fit {
let mut f = Q3Fit { l: [0; 256], scales: [0.0; 16], sw: [0.0; 16], maxs: 0.0 };
let mut amax = 0.0;
let sigma = 2.0 * sum_sq(x) / 256.0;
for k in 0..16 {
let xb = &x[k * 16..k * 16 + 16];
scales[k] = if let Some(q) = qw {
let w: [f32; 16] = std::array::from_fn(|j| q[k * 16 + j] * (sigma + xb[j] * xb[j]).sqrt());
for &v in &w {
sw[k] += v;
}
qx(xb, 4, &mut l[k * 16..k * 16 + 16], 1, Some(&w))
} else {
q3(xb, &mut l[k * 16..k * 16 + 16])
};
if scales[k].abs() > amax {
amax = scales[k].abs();
maxs = scales[k];
(f.scales[k], f.sw[k]) = q3_subfit(xb, qw, k, sigma, &mut f.l[k * 16..k * 16 + 16]);
if f.scales[k].abs() > amax {
amax = f.scales[k].abs();
f.maxs = f.scales[k];
}
}
(scales, sw, maxs)
f
}
/// The super-block scale; the 6-bit block scale levels go to `ls`.
fn q3k_scale(scales: &[f32; 16], sw: &[f32; 16], maxs: f32, ls: &mut [i8; 16], weighted: bool) -> f32 {
if weighted {
return qx(scales, 32, ls, 1, Some(sw));
}
if maxs == 0.0 {
return 0.0;
}
let inv = -32.0 / maxs;
for k in 0..16 {
ls[k] = (nearest(inv * scales[k]).clamp(-32, 31) + 32) as i8;
}
1.0 / inv
/// The 6-bit scale codes of the sixteen sub-blocks and the super-block scale.
fn q3k_scale_codes(f: &Q3Fit, weighted: bool) -> ([i8; 16], f32) {
let mut ls = [0i8; 16];
let d = if weighted {
qx(&f.scales, 32, &mut ls, 1, Some(&f.sw))
} else if f.maxs != 0.0 {
let inv = -32.0 / f.maxs;
for k in 0..16 {
ls[k] = (nearest(inv * f.scales[k]).clamp(-32, 31) + 32) as i8;
}
1.0 / inv
} else {
0.0
};
(ls, d)
}
/// Requantizes the values against the stored (rounded) super-block scale `d` and the packed block scales in y.
fn q3k_requantize(x: &[f32], y: &[u8], d: f32, l: &mut [i8; 256]) {
/// Re-derives the levels against the stored (half-rounded) scale of every sub-block.
fn q3k_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) {
let d = h(y, 108);
for k in 0..16 {
let ds = d * unpack_scale3(&y[96..108], k) as f32;
if ds == 0.0 {
continue;
}
for j in 0..16 {
l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-4, 3) + 4) as i8;
if ds != 0.0 {
for j in 0..16 {
l[k * 16 + j] = (nearest(x[k * 16 + j] / ds).clamp(-4, 3) + 4) as i8;
}
}
}
}
/// High bits into y[..32], the low two bits into y[32..96].
fn q3k_pack(y: &mut [u8], l: &mut [i8; 256]) {
/// The high bit of every level goes to the 32-byte mask, the low two bits are packed like Q2_K.
fn q3k_pack_levels(l: &[i8; 256], y: &mut [u8]) {
y[..32].fill(0);
let mut low = [0u8; 256];
for j in 0..256 {
if l[j] > 3 {
let mut level = l[j];
if level > 3 {
y[j % 32] |= 1 << (j / 32);
l[j] -= 4;
level -= 4;
}
low[j] = l[j] as u8;
low[j] = level as u8;
}
pack_k2(&low, &mut y[32..96]);
}
pub(super) fn q3k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let sigma = 2.0 * sum_squares(x) / 256.0;
let mut f = q3k_fit_blocks(x, qw, sigma);
let (ls, d) = q3k_scale_codes(&f, qw.is_some());
pack_scale3(&ls, &mut y[96..108]);
put_h(y, 108, d);
q3k_requantize(x, y, &mut f.l);
q3k_pack_levels(&f.l, y);
}
pub(super) fn pack_scale4(ls: &[u8; 8], lm: &[u8; 8], y: &mut [u8]) {
for j in 0..8 {
let s = ls[j];
@@ -1,62 +1,48 @@
//! Moved out of the parent module by STRA-338: fn iq4, fn row_without_iq.
use super::nearest_fn::sum_sq;
#[allow(unused_imports)]
use super::*;
pub(super) fn iq4(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, ntry: i32) {
let nb = x.len() / 32;
let mut sigma = sum_sq(x);
sigma *= 2.0 / x.len() as f32;
let mut l = [0u8; 256];
y.fill(0);
put_h(y, 0, 0.0);
let (scales, maxs) = iq4_search(x, &mut l, qw, (sigma, ntry));
let head = if kind == Kind::Iq4Xs {
iq4_xs_scales(x, y, &mut l, &scales[..nb], maxs)
} else {
iq4_nl_scale(x, y, &mut l, scales[0], ntry)
};
for k in 0..nb {
pack4(&l[k * 32..k * 32 + 32], &mut y[head + k * 16..head + (k + 1) * 16]);
}
const IQ4_VALUES: &[i8; 16] = &super::super::rust_codebooks::KVALUES_IQ4NL;
/// The levels of up to eight 32-element blocks with their scales and the scale of largest magnitude.
struct Iq4Fit {
l: [u8; 256],
scales: [f32; 8],
maxs: f32,
}
/// The scale of each 32-value block (levels of that fit in `l`) and the scale of largest magnitude;
/// `fit` is (sigma, ntry).
fn iq4_search(x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>, fit: (f32, i32)) -> ([f32; 8], f32) {
let (sigma, ntry) = fit;
let mut scales = [0.0; 8];
let (mut maxs, mut amax) = (0.0, 0.0);
for k in 0..x.len() / 32 {
let xb = &x[k * 32..k * 32 + 32];
let w: [f32; 32] = std::array::from_fn(|j| {
fn iq4_weights(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32) -> [f32; 32] {
std::array::from_fn(
|j| {
if let Some(q) = qw { q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt() } else { xb[j] * xb[j] }
});
scales[k] = iq4_block(xb, &w, &mut l[k * 32..k * 32 + 32], ntry);
if scales[k].abs() > amax {
amax = scales[k].abs();
maxs = scales[k];
}
}
(scales, maxs)
},
)
}
/// The best scale of one block among the 2 * ntry + 1 tried; 0 for an all-zero block, whose levels stay untouched.
fn iq4_block(xb: &[f32], w: &[f32; 32], lb: &mut [u8], ntry: i32) -> f32 {
let values = &super::super::rust_codebooks::KVALUES_IQ4NL;
let (a, max) = max_signed(xb);
if a < EPS {
return 0.0;
}
let d = if ntry > 0 { -max / values[0] as f32 } else { max / values[0] as f32 };
let inv = 1.0 / d;
/// `sum(w*q*x)` and `sum(w*q*q)` of the codebook levels nearest to `inv * xb`.
fn iq4_sums(xb: &[f32], w: &[f32; 32], inv: f32) -> (f32, f32) {
let (mut sx, mut s2) = (0.0, 0.0);
for j in 0..32 {
lb[j] = best_iq4(inv * xb[j]);
let q = IQ4_VALUES[best_iq4(inv * xb[j]) as usize] as f32;
sx += w[j] * q * xb[j];
s2 += w[j] * q * q;
}
(sx, s2)
}
fn iq4_assign_levels(xb: &[f32], inv: f32, l: &mut [u8]) {
for j in 0..32 {
l[j] = best_iq4(inv * xb[j]);
}
}
/// Scale of the first guess (levels written to `l`) improved by the `ntry` neighbouring inverse scales.
fn iq4_fit_block(xb: &[f32], w: &[f32; 32], max: f32, ntry: i32, l: &mut [u8]) -> f32 {
let mut d = if ntry > 0 { -max / IQ4_VALUES[0] as f32 } else { max / IQ4_VALUES[0] as f32 };
let inv = 1.0 / d;
iq4_assign_levels(xb, inv, l);
let (sx, s2) = iq4_sums(xb, w, inv);
let mut d = if s2 > 0.0 { sx / s2 } else { 0.0 };
d = if s2 > 0.0 { sx / s2 } else { 0.0 };
let mut best = d * sx;
for itry in -ntry..=ntry {
let inv = (itry as f32 + values[0] as f32) / max;
let inv = (itry as f32 + IQ4_VALUES[0] as f32) / max;
let (sx, s2) = iq4_sums(xb, w, inv);
if s2 > 0.0 && sx * sx > best * s2 {
d = sx / s2;
@@ -65,85 +51,90 @@ fn iq4_block(xb: &[f32], w: &[f32; 32], lb: &mut [u8], ntry: i32) -> f32 {
}
d
}
/// The weighted sums (sum w*q*x, sum w*q*q) of the codebook values nearest to `inv * x`.
fn iq4_sums(xb: &[f32], w: &[f32; 32], inv: f32) -> (f32, f32) {
let values = &super::super::rust_codebooks::KVALUES_IQ4NL;
let (mut sx, mut s2) = (0.0, 0.0);
for j in 0..32 {
let q = values[best_iq4(inv * xb[j]) as usize] as f32;
sx += w[j] * q * xb[j];
s2 += w[j] * q * q;
fn iq4_fit_blocks(x: &[f32], qw: Option<&[f32]>, sigma: f32, ntry: i32) -> Iq4Fit {
let mut f = Iq4Fit { l: [0; 256], scales: [0.0; 8], maxs: 0.0 };
let mut amax = 0.0;
for k in 0..x.len() / 32 {
let xb = &x[k * 32..k * 32 + 32];
let w = iq4_weights(xb, qw, k, sigma);
let (a, max) = max_signed(xb);
if a < EPS {
f.scales[k] = 0.0;
continue;
}
let d = iq4_fit_block(xb, &w, max, ntry, &mut f.l[k * 32..k * 32 + 32]);
f.scales[k] = d;
if d.abs() > amax {
amax = d.abs();
f.maxs = d;
}
}
(sx, s2)
f
}
/// IQ4_XS: the 6-bit block scales (low four bits in y[4..8], high two in y[2..4]) and the levels against them;
/// the offset of the packed levels.
fn iq4_xs_scales(x: &[f32], y: &mut [u8], l: &mut [u8; 256], scales: &[f32], maxs: f32) -> usize {
let d = -maxs / 32.0;
/// Re-derives the levels of block `k` against the stored scale `ds`.
fn iq4_xs_levels(x: &[f32], l: &mut [u8; 256], k: usize, ds: f32) {
let di = if ds != 0.0 { 1.0 / ds } else { 0.0 };
for j in 0..32 {
l[k * 32 + j] = best_iq4(di * x[k * 32 + j]);
}
}
fn iq4_xs_put_scale(y: &mut [u8], k: usize, code: u8) {
if k % 2 == 0 {
y[4 + k / 2] = code & 15;
} else {
y[4 + k / 2] |= (code & 15) << 4;
}
}
/// IQ4_XS header: the super-block scale, the 6-bit block scales and the levels re-derived against them.
fn iq4_xs_head(x: &[f32], y: &mut [u8], f: &mut Iq4Fit) -> usize {
let d = -f.maxs / 32.0;
put_h(y, 0, d);
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
let mut high = 0u16;
for (k, &scale) in scales.iter().enumerate() {
let s = nearest(inv * scale).clamp(-32, 31);
let ds = d * s as f32;
let di = if ds != 0.0 { 1.0 / ds } else { 0.0 };
for j in 0..32 {
l[k * 32 + j] = best_iq4(di * x[k * 32 + j]);
}
let s = (s + 32) as u8;
if k % 2 == 0 {
y[4 + k / 2] = s & 15;
} else {
y[4 + k / 2] |= (s & 15) << 4;
}
high |= ((s >> 4) as u16) << (2 * k);
for k in 0..x.len() / 32 {
let s = nearest(inv * f.scales[k]).clamp(-32, 31);
iq4_xs_levels(x, &mut f.l, k, d * s as f32);
let code = (s + 32) as u8;
iq4_xs_put_scale(y, k, code);
high |= ((code >> 4) as u16) << (2 * k);
}
y[2..4].copy_from_slice(&high.to_le_bytes());
8
}
/// IQ4_NL: the single scale; with `ntry > 0` the levels are redone against it. The offset of the packed levels.
fn iq4_nl_scale(x: &[f32], y: &mut [u8], l: &mut [u8; 256], scale: f32, ntry: i32) -> usize {
put_h(y, 0, scale);
/// IQ4_NL header: the single block scale; the levels are re-derived against it only for the searched fit.
fn iq4_nl_head(x: &[f32], y: &mut [u8], f: &mut Iq4Fit, ntry: i32) -> usize {
put_h(y, 0, f.scales[0]);
if ntry > 0 {
let inv = if scale != 0.0 { 1.0 / scale } else { 0.0 };
let inv = if f.scales[0] != 0.0 { 1.0 / f.scales[0] } else { 0.0 };
for j in 0..x.len() {
l[j] = best_iq4(inv * x[j]);
f.l[j] = best_iq4(inv * x[j]);
}
}
2
}
/// Reference/weighted rows sharing one imatrix vector per row, as ggml_quantize_chunk.
/// IQ lookup quantizers are registered by the separate pinned grid module.
pub(in super::super) fn row_without_iq(
kind: Kind,
x: &[f32],
y: &mut [u8],
qw: Option<&[f32]>,
reference_iq4: bool,
) -> Result<bool> {
pub(super) fn iq4(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, ntry: i32) {
let mut sigma = sum_squares(x);
sigma *= 2.0 / x.len() as f32;
y.fill(0);
put_h(y, 0, 0.0);
let mut f = iq4_fit_blocks(x, qw, sigma, ntry);
let head = if kind == Kind::Iq4Xs { iq4_xs_head(x, y, &mut f) } else { iq4_nl_head(x, y, &mut f, ntry) };
for k in 0..x.len() / 32 {
pack4(&f.l[k * 32..k * 32 + 32], &mut y[head + k * 16..head + (k + 1) * 16]);
}
}
fn validate_row_shape(kind: Kind, x: &[f32], y: &[u8], qw: Option<&[f32]>) -> Result<()> {
if kind.row_bytes(x.len())? != y.len() || qw.is_some_and(|q| q.len() != x.len()) {
return Err(Error::Shape);
}
let (q, b) = kind.block();
let sigma = sum_sq(x) / x.len() as f32;
for (i, (x, y)) in x.chunks_exact(q).zip(y.chunks_exact_mut(b)).enumerate() {
let w = qw.map(|w| &w[i * q..(i + 1) * q]);
if !block_without_iq(kind, (x, y), w, sigma, reference_iq4) {
return Ok(false);
}
}
Ok(true)
Ok(())
}
/// Quantizes one block of a kind this module handles; false for a kind it does not (the IQ lookup quantizers).
/// `block` is (values, output).
fn block_without_iq(
kind: Kind,
block: (&[f32], &mut [u8]),
w: Option<&[f32]>,
sigma: f32,
reference_iq4: bool,
) -> bool {
let (x, y) = block;
/// Search width of the IQ4 scale: the reference IQ4_NL path takes none.
fn iq4_tries(kind: Kind, reference_iq4: bool) -> i32 {
if reference_iq4 && kind == Kind::Iq4Nl { -1 } else { 7 }
}
/// Quantizes one block of a non-IQ-grid kind; `false` when the kind belongs to the grid module.
fn quantize_block(kind: Kind, x: &[f32], y: &mut [u8], w: Option<&[f32]>, sigma: f32, reference_iq4: bool) -> bool {
match kind {
Kind::F32
| Kind::F16
@@ -161,12 +152,28 @@ fn block_without_iq(
Kind::Q3K => q3k(x, y, w),
Kind::Q4K | Kind::Q5K => q45k(kind == Kind::Q5K, x, y, w),
Kind::Q6K => q6k(x, y, w),
Kind::Iq4Nl | Kind::Iq4Xs => iq4(kind, x, y, w, iq4_ntry(kind, reference_iq4)),
Kind::Iq4Nl | Kind::Iq4Xs => iq4(kind, x, y, w, iq4_tries(kind, reference_iq4)),
_ => return false,
}
true
}
/// Search width of the IQ4 quantizers: 7, or -1 for the reference IQ4_NL.
fn iq4_ntry(kind: Kind, reference_iq4: bool) -> i32 {
if reference_iq4 && kind == Kind::Iq4Nl { -1 } else { 7 }
/// Reference/weighted rows sharing one imatrix vector per row, as ggml_quantize_chunk.
/// IQ lookup quantizers are registered by the separate pinned grid module.
pub(in super::super) fn row_without_iq(
kind: Kind,
x: &[f32],
y: &mut [u8],
qw: Option<&[f32]>,
reference_iq4: bool,
) -> Result<bool> {
validate_row_shape(kind, x, y, qw)?;
let (q, b) = kind.block();
let sigma = sum_squares(x) / x.len() as f32;
for (i, (x, y)) in x.chunks_exact(q).zip(y.chunks_exact_mut(b)).enumerate() {
let w = qw.map(|w| &w[i * q..(i + 1) * q]);
if !quantize_block(kind, x, y, w, sigma, reference_iq4) {
return Ok(false);
}
}
Ok(true)
}
@@ -14,48 +14,6 @@ pub(super) fn put_h(y: &mut [u8], at: usize, x: f32) {
pub(super) fn h(y: &[u8], at: usize) -> f32 {
half(u16::from_le_bytes([y[at], y[at + 1]]))
}
/// Sum of squares, accumulated left to right in f32.
pub(super) fn sum_sq(x: &[f32]) -> f32 {
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
sum
}
/// Per-block (scale, minimum) of a K-quant search, the block weights, and the largest scale and minimum.
pub(super) struct Search<const N: usize> {
pub(super) scales: [f32; N],
pub(super) mins: [f32; N],
pub(super) sw: [f32; N],
maxs: f32,
maxm: f32,
}
impl<const N: usize> Search<N> {
pub(super) fn new() -> Self {
Search { scales: [0.0; N], mins: [0.0; N], sw: [0.0; N], maxs: 0.0, maxm: 0.0 }
}
/// Stores the fit of block `k` and tracks the maxima.
pub(super) fn record(&mut self, k: usize, d: f32, m: f32) {
self.scales[k] = d;
self.mins[k] = m;
if d > self.maxs {
self.maxs = d;
}
if m > self.maxm {
self.maxm = m;
}
}
/// The 1/max factors for rounding scales and minima to `levels` steps (0 when the maximum is not positive).
pub(super) fn factors(&self, levels: f32) -> (f32, f32) {
let si = if self.maxs > 0.0 { levels / self.maxs } else { 0.0 };
let mi = if self.maxm > 0.0 { levels / self.maxm } else { 0.0 };
(si, mi)
}
/// maxs / levels and maxm / levels.
pub(super) fn steps(&self, levels: f32) -> (f32, f32) {
(self.maxs / levels, self.maxm / levels)
}
}
pub(super) fn max_signed(x: &[f32]) -> (f32, f32) {
let (mut a, mut v) = (0.0, 0.0);
for &f in x {
@@ -66,6 +24,14 @@ pub(super) fn max_signed(x: &[f32]) -> (f32, f32) {
}
(a, v)
}
/// Sum of squares in element order.
pub(in super::super) fn sum_squares(x: &[f32]) -> f32 {
let mut sum = 0.0;
for &v in x {
sum += v * v;
}
sum
}
pub(super) fn weight(x: f32, rmse: i32, qw: Option<f32>) -> f32 {
qw.unwrap_or_else(|| match rmse {
1 => x * x,
@@ -74,6 +40,59 @@ pub(super) fn weight(x: f32, rmse: i32, qw: Option<f32>) -> f32 {
_ => x.abs().sqrt(),
})
}
/// The running weighted sums `sum(w*x*q)` and `sum(w*q*q)` of a level assignment.
#[derive(Clone, Copy)]
pub(super) struct Sums {
pub(super) sx: f32,
pub(super) s2: f32,
}
/// One signed-level fit: the block, the largest level magnitude, the weighting rule and the optional weights.
struct SignedFit<'a> {
x: &'a [f32],
nmax: i32,
rmse: i32,
qw: Option<&'a [f32]>,
}
impl SignedFit<'_> {
fn level(&self, inv: f32, i: usize) -> i32 {
nearest(inv * self.x[i]).clamp(-self.nmax, self.nmax - 1)
}
fn weight_at(&self, i: usize) -> f32 {
weight(self.x[i], self.rmse, self.qw.map(|w| w[i]))
}
fn assign_levels(&self, inv: f32, l: &mut [i8]) {
for i in 0..self.x.len() {
l[i] = (self.nmax + self.level(inv, i)) as i8;
}
}
fn sums(&self, inv: f32) -> Sums {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..self.x.len() {
let q = self.level(inv, i);
let w = self.weight_at(i);
sx += w * self.x[i] * q as f32;
s2 += w * q as f32 * q as f32;
}
Sums { sx, s2 }
}
fn search_scale(&self, l: &mut [i8], max: f32, start: f32, first: Sums) -> f32 {
let mut scale = start;
let mut best = scale * first.sx;
for is in -9..=9 {
if is == 0 {
continue;
}
let inv = -(self.nmax as f32 + 0.1 * is as f32) / max;
let Sums { sx, s2 } = self.sums(inv);
if s2 > 0.0 && sx * sx > best * s2 {
self.assign_levels(inv, l);
scale = sx / s2;
best = scale * sx;
}
}
scale
}
}
pub(in super::super) fn qx(x: &[f32], nmax: i32, l: &mut [i8], mut rmse: i32, qw: Option<&[f32]>) -> f32 {
let (amax, max) = max_signed(x);
if amax < EPS {
@@ -82,60 +101,28 @@ pub(in super::super) fn qx(x: &[f32], nmax: i32, l: &mut [i8], mut rmse: i32, qw
}
let inv = -(nmax as f32) / max;
if rmse == 0 {
qx_levels(x, nmax, l, inv);
return 1.0 / inv;
return qx_direct(x, nmax, l, inv);
}
let early = rmse < 0;
if early {
rmse = -rmse;
}
qx_levels(x, nmax, l, inv);
let (sx, s2) = qx_sums(x, nmax, inv, rmse, qw);
let scale = if s2 != 0.0 { sx / s2 } else { 0.0 };
let fit = SignedFit { x, nmax, rmse, qw };
fit.assign_levels(inv, l);
let first = fit.sums(inv);
let scale = if first.s2 != 0.0 { first.sx / first.s2 } else { 0.0 };
if early {
return if s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv };
return if first.s2 > 0.0 { 0.5 * (scale + 1.0 / inv) } else { 1.0 / inv };
}
qx_search(x, nmax, l, (max, rmse, qw), scale, sx)
fit.search_scale(l, max, scale, first)
}
/// The levels `nmax + clamp(round(inv * x))` as stored in `l`.
fn qx_levels(x: &[f32], nmax: i32, l: &mut [i8], inv: f32) {
fn qx_direct(x: &[f32], nmax: i32, l: &mut [i8], inv: f32) -> f32 {
for (&x, l) in x.iter().zip(l) {
*l = (nmax + nearest(inv * x).clamp(-nmax, nmax - 1)) as i8;
}
1.0 / inv
}
/// The weighted sums (sum w*x*q, sum w*q*q) of the levels at `inv`.
fn qx_sums(x: &[f32], nmax: i32, inv: f32, rmse: i32, qw: Option<&[f32]>) -> (f32, f32) {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..x.len() {
let q = nearest(inv * x[i]).clamp(-nmax, nmax - 1);
let w = weight(x[i], rmse, qw.map(|w| w[i]));
sx += w * x[i] * q as f32;
s2 += w * q as f32 * q as f32;
}
(sx, s2)
}
/// 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 {
let (max, rmse, qw) = fit;
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;
let (sx, s2) = qx_sums(x, nmax, inv, rmse, qw);
if s2 > 0.0 && sx * sx > best * s2 {
qx_levels(x, nmax, l, inv);
scale = sx / s2;
best = scale * sx;
}
}
scale
}
pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 {
let (a, max) = max_signed(x);
if a < EPS {
l.fill(0);
return 0.0;
}
let inv = -4.0 / max;
fn q3_start(x: &[f32], l: &mut [i8], inv: f32) -> Sums {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..x.len() {
let q = nearest(inv * x[i]).clamp(-4, 3);
@@ -144,138 +131,188 @@ pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 {
sx += w * x[i] * q as f32;
s2 += w * q as f32 * q as f32;
}
for _ in 0..5 {
if q3_pass(x, l, &mut sx, &mut s2) == 0 {
break;
Sums { sx, s2 }
}
/// Moves element `i` to its best level when that raises the objective; returns the new sums when it moved.
fn q3_move(x: &[f32], l: &mut [i8], i: usize, s: Sums) -> Option<Sums> {
let w = x[i] * x[i];
let mut tx = s.sx - w * x[i] * l[i] as f32;
if tx > 0.0 {
let mut t2 = s.s2 - w * l[i] as f32 * l[i] as f32;
let q = nearest(x[i] * t2 / tx).clamp(-4, 3);
if q != l[i] as i32 {
tx += w * x[i] * q as f32;
t2 += w * q as f32 * q as f32;
if t2 > 0.0 && tx * tx * s.s2 > s.sx * s.sx * t2 {
l[i] = q as i8;
return Some(Sums { sx: tx, s2: t2 });
}
}
}
for l in l {
*l += 4;
}
if s2 > 0.0 { sx / s2 } else { 0.0 }
None
}
/// One sweep moving single levels while the fit improves; the number of levels changed.
fn q3_pass(x: &[f32], l: &mut [i8], sx: &mut f32, s2: &mut f32) -> i32 {
fn q3_pass(x: &[f32], l: &mut [i8], mut s: Sums) -> (Sums, usize) {
let mut changed = 0;
for i in 0..x.len() {
if let Some((q, tx, t2)) = q3_move(x[i], l[i], *sx, *s2) {
l[i] = q;
*sx = tx;
*s2 = t2;
if let Some(moved) = q3_move(x, l, i, s) {
s = moved;
changed += 1;
}
}
changed
(s, changed)
}
/// The new level and sums when changing the level `li` of `xi` improves the fit.
#[allow(clippy::neg_cmp_op_on_partial_ord)]
fn q3_move(xi: f32, li: i8, sx: f32, s2: f32) -> Option<(i8, f32, f32)> {
let w = xi * xi;
let mut tx = sx - w * xi * li as f32;
if !(tx > 0.0) {
return None;
fn q3_refine(x: &[f32], l: &mut [i8], mut s: Sums) -> Sums {
for _ in 0..5 {
let (next, changed) = q3_pass(x, l, s);
s = next;
if changed == 0 {
break;
}
}
let mut t2 = s2 - w * li as f32 * li as f32;
let q = nearest(xi * t2 / tx).clamp(-4, 3);
if q == li as i32 {
return None;
}
tx += w * xi * q as f32;
t2 += w * q as f32 * q as f32;
if t2 > 0.0 && tx * tx * s2 > sx * sx * t2 { Some((q as i8, tx, t2)) } else { None }
s
}
/// qkx2/qkx3 have the same search tree; qkx3 differs in max<=min and implicit x^2 weights.
pub(super) fn qkx(x: &[f32], nmax: i32, w: &[f32], l: &mut [u8], p: Qkx) -> (f32, f32) {
let (mut min, max, sw, sx) = qkx_stats(x, w);
if (p.third && max <= min) || (!p.third && max == min) {
pub(super) fn q3(x: &[f32], l: &mut [i8]) -> f32 {
let (a, max) = max_signed(x);
if a < EPS {
l.fill(0);
return (0.0, -min);
return 0.0;
}
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 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 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 inv = -4.0 / max;
let start = q3_start(x, l, inv);
let s = q3_refine(x, l, start);
for l in l {
*l += 4;
}
if s.s2 > 0.0 { s.sx / s.s2 } else { 0.0 }
}
/// The block to fit with `qkx`: values, weights, the largest level and whether the error is absolute or squared.
struct MinMaxFit<'a> {
x: &'a [f32],
w: &'a [f32],
nmax: i32,
mad: bool,
}
/// Weighted sums of one level trial: `sum(w*q)`, `sum(w*q*q)` and `sum(w*q*x)`.
struct TrialSums {
sl: f32,
sl2: f32,
sxl: f32,
}
impl MinMaxFit<'_> {
fn penalty(&self, diff: f32) -> f32 {
if self.mad { diff.abs() } else { diff * diff }
}
/// Smallest value, largest value, `sum(w)` and `sum(w*x)`.
fn scan(&self) -> (f32, f32, f32, f32) {
let (x, w) = (self.x, self.w);
let (mut min, mut max) = (x[0], x[0]);
let (mut sw, mut sx) = (w[0], w[0] * x[0]);
for i in 1..x.len() {
if x[i] < min {
min = x[i];
}
if x[i] > max {
max = x[i];
}
sw += w[i];
sx += w[i] * x[i];
}
(min, max, sw, sx)
}
/// Writes the plain levels for `inv` and returns the error of that assignment.
fn assign_levels(&self, l: &mut [u8], inv: f32, scale: f32, min: f32) -> f32 {
let (x, w) = (self.x, self.w);
let mut best = 0.0;
for i in 0..x.len() {
l[i] = nearest(inv * (x[i] - min)).clamp(0, self.nmax) as u8;
let diff = scale * l[i] as f32 + min - x[i];
best += w[i] * self.penalty(diff);
}
best
}
fn trial_levels(&self, aux: &mut [u8], inv: f32, min: f32) -> TrialSums {
let (x, w) = (self.x, self.w);
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, self.nmax);
aux[i] = q as u8;
sl += w[i] * q as f32;
sl2 += w[i] * q as f32 * q as f32;
sxl += w[i] * q as f32 * x[i];
}
TrialSums { sl, sl2, sxl }
}
fn trial_error(&self, aux: &[u8], ds: f32, dm: f32) -> f32 {
let (x, w) = (self.x, self.w);
let mut error = 0.0;
for i in 0..x.len() {
let diff = ds * aux[i] as f32 + dm - x[i];
error += w[i] * self.penalty(diff);
}
error
}
}
/// Least-squares scale and minimum of a level trial, or `None` when the system is singular.
fn solve_trial(sw: f32, sx: f32, t: &TrialSums) -> Option<(f32, f32)> {
let det = sw * t.sl2 - t.sl * t.sl;
if det > 0.0 {
let mut ds = (sw * t.sxl - sx * t.sl) / det;
let mut dm = (t.sl2 * sx - t.sl * t.sxl) / det;
if dm > 0.0 {
dm = 0.0;
ds = t.sxl / t.sl2;
}
Some((ds, dm))
} else {
None
}
}
/// The inverse-scale trials of `qkx`: first offset, step and count.
struct Steps {
rmin: f32,
rdelta: f32,
nstep: i32,
}
impl MinMaxFit<'_> {
fn search(&self, l: &mut [u8], steps: Steps, third: bool) -> (f32, f32) {
let (mut min, max, sw, sx) = self.scan();
if min > 0.0 {
min = 0.0;
}
if (third && max <= min) || (!third && max == min) {
l.fill(0);
return (0.0, -min);
}
let inv = self.nmax as f32 / (max - min);
let mut scale = 1.0 / inv;
let mut best = self.assign_levels(l, inv, scale, min);
let mut aux = [0u8; 32];
for is in 0..=steps.nstep {
let inv = (steps.rmin + steps.rdelta * is as f32 + self.nmax as f32) / (max - min);
let trial = self.trial_levels(&mut aux, inv, min);
let Some((ds, dm)) = solve_trial(sw, sx, &trial) else { continue };
let error = self.trial_error(&aux, ds, dm);
if error < best {
l.copy_from_slice(&aux[..x.len()]);
l.copy_from_slice(&aux[..self.x.len()]);
best = error;
scale = ds;
min = dm;
}
}
}
(scale, -min)
}
/// The search parameters of qkx: the first step offset and the step size, the number of steps, whether the error is
/// absolute (not squared), and the qkx3 variant.
#[derive(Clone, Copy)]
pub(super) struct Qkx {
pub(super) rmin: f32,
pub(super) rdelta: f32,
pub(super) nstep: i32,
pub(super) mad: bool,
pub(super) third: bool,
}
impl Qkx {
/// The importance-weighted search of the imatrix quantizers (qkx3).
pub(super) const WEIGHTED: Qkx = Qkx { rmin: -0.9, rdelta: 0.05, nstep: 36, mad: false, third: true };
}
/// (min clamped to <= 0, max, sum w, sum w*x) of the block.
fn qkx_stats(x: &[f32], w: &[f32]) -> (f32, f32, f32, f32) {
let (mut min, mut max) = (x[0], x[0]);
let (mut sw, mut sx) = (w[0], w[0] * x[0]);
for i in 1..x.len() {
if x[i] < min {
min = x[i];
}
if x[i] > max {
max = x[i];
}
sw += w[i];
sx += w[i] * x[i];
}
if min > 0.0 {
min = 0.0;
}
(min, max, sw, sx)
}
fn qkx_fill(x: &[f32], l: &mut [u8], nmax: i32, inv: f32, min: f32) {
for i in 0..x.len() {
l[i] = nearest(inv * (x[i] - min)).clamp(0, nmax) as u8;
(scale, -min)
}
}
/// 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 {
let mut error = 0.0;
for i in 0..x.len() {
let diff = scale * q[i] as f32 + min - x[i];
error += w[i] * if mad { diff.abs() } else { diff * diff };
}
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) {
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);
aux[i] = q as u8;
sl += w[i] * q as f32;
sl2 += w[i] * q as f32 * q as f32;
sxl += w[i] * q as f32 * x[i];
}
(sl, sl2, sxl)
}
/// Scale and (non-positive) minimum of the least-squares fit; `sums` is [sw, sx, sl, sl2, sxl].
fn qkx_solve(sums: [f32; 5], det: f32) -> (f32, f32) {
let [sw, sx, sl, sl2, sxl] = sums;
let ds = (sw * sxl - sx * sl) / det;
let dm = (sl2 * sx - sl * sxl) / det;
if dm > 0.0 { (sxl / sl2, 0.0) } else { (ds, dm) }
/// qkx2/qkx3 have the same search tree; qkx3 differs in max<=min and implicit x^2 weights.
pub(super) fn qkx(
x: &[f32],
nmax: i32,
w: &[f32],
l: &mut [u8],
rmin: f32,
rdelta: f32,
nstep: i32,
mad: bool,
third: bool,
) -> (f32, f32) {
MinMaxFit { x, w, nmax, mad }.search(l, Steps { rmin, rdelta, nstep }, third)
}
@@ -1,72 +1,74 @@
//! Moved out of the parent module by STRA-338: fn q45k, fn q6k, fn best_iq4.
use super::nearest_fn::{Qkx, Search, sum_sq};
#[allow(unused_imports)]
use super::*;
pub(super) fn q45k(five: bool, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let nmax = if five { 31 } else { 15 };
let mut l = [0u8; 256];
let search = q45k_search(five, x, &mut l, qw);
// The sigma.sqrt() of the weighted implementation's no-imatrix branch is not used: public
// quantize_q4/5_K selects reference when qw=None, exactly as pinned GGML.
let (ls, lm, d, m) = q45k_scales(&search, qw.is_some());
pack_scale4(&ls, &lm, &mut y[4..16]);
put_h(y, 0, d);
put_h(y, 2, m);
q45k_requantize(x, y, nmax, &mut l);
q45k_pack(five, y, &l);
/// The eight 32-element sub-block fits of a Q4_K / Q5_K block: scales, minimums, weight sums and their maxima.
struct Subfits {
l: [u8; 256],
scales: [f32; 8],
mins: [f32; 8],
sw: [f32; 8],
maxs: f32,
maxm: f32,
}
/// Best (scale, minimum) of each 32-value block, with the levels of that fit in `l`.
fn q45k_search(five: bool, x: &[f32], l: &mut [u8; 256], qw: Option<&[f32]>) -> Search<8> {
/// The weights of one sub-block: the imatrix scaled by the block energy, or the unweighted magnitude rule.
fn q45_weights(xb: &[f32], qw: Option<&[f32]>, k: usize, sigma: f32) -> [f32; 32] {
if let Some(q) = qw {
std::array::from_fn(|j| q[k * 32 + j] * (sigma + xb[j] * xb[j]).sqrt())
} else {
let avg = (sum_squares(xb) / 32.0).sqrt();
std::array::from_fn(|j| avg + xb[j].abs())
}
}
fn q45_subfit(xb: &[f32], nmax: i32, five: bool, w: &[f32; 32], l: &mut [u8], weighted: bool) -> (f32, f32) {
if weighted {
qkx(xb, nmax, w, l, -0.9, 0.05, 36, false, true)
} else {
let (rmin, nstep) = if five { (-0.5, 15) } else { (-1.0, 20) };
qkx(xb, nmax, w, l, rmin, 0.1, nstep, false, false)
}
}
fn q45_fit_blocks(x: &[f32], qw: Option<&[f32]>, five: bool, sigma: f32) -> Subfits {
let nmax = if five { 31 } else { 15 };
let sigma = 2.0 * sum_sq(x) / 256.0;
let mut s = Search::<8>::new();
let plain = Qkx {
rmin: if five { -0.5 } else { -1.0 },
rdelta: 0.1,
nstep: if five { 15 } else { 20 },
mad: false,
third: false,
};
let mut f = Subfits { l: [0; 256], scales: [0.0; 8], mins: [0.0; 8], sw: [0.0; 8], maxs: 0.0, maxm: 0.0 };
for k in 0..8 {
let xb = &x[k * 32..k * 32 + 32];
let w = q45k_weights(xb, qw.map(|q| &q[k * 32..k * 32 + 32]), sigma);
let w = q45_weights(xb, qw, k, sigma);
for &v in &w {
s.sw[k] += v;
f.sw[k] += v;
}
let (d, m) = q45_subfit(xb, nmax, five, &w, &mut f.l[k * 32..k * 32 + 32], qw.is_some());
f.scales[k] = d;
f.mins[k] = m;
if d > f.maxs {
f.maxs = d;
}
if m > f.maxm {
f.maxm = m;
}
let lb = &mut l[k * 32..k * 32 + 32];
let (d, m) = if qw.is_some() { qkx(xb, nmax, &w, lb, Qkx::WEIGHTED) } else { qkx(xb, nmax, &w, lb, plain) };
s.record(k, d, m);
}
s
f
}
/// Importance weights of a block: imatrix * sqrt(sigma + x^2), or rms + |x| without an imatrix.
fn q45k_weights(xb: &[f32], qb: Option<&[f32]>, sigma: f32) -> [f32; 32] {
if let Some(q) = qb {
return std::array::from_fn(|j| q[j] * (sigma + xb[j] * xb[j]).sqrt());
}
let avg = (sum_sq(xb) / 32.0).sqrt();
std::array::from_fn(|j| avg + xb[j].abs())
}
/// The 6-bit scale and minimum levels of the blocks and the super-block (d, m).
fn q45k_scales(s: &Search<8>, weighted: bool) -> ([u8; 8], [u8; 8], f32, f32) {
/// The 6-bit scale and minimum codes of the eight sub-blocks, with the super-block scale and minimum.
fn q45_scale_codes(f: &Subfits, weighted: bool) -> ([u8; 8], [u8; 8], f32, f32) {
let mut ls = [0u8; 8];
let mut lm = ls;
if weighted {
let (d, m) = (qp(&s.scales, 63, &mut ls, &s.sw), qp(&s.mins, 63, &mut lm, &s.sw));
let d = qp(&f.scales, 63, &mut ls, &f.sw);
let m = qp(&f.mins, 63, &mut lm, &f.sw);
return (ls, lm, d, m);
}
let (si, mi) = s.factors(63.0);
let si = if f.maxs > 0.0 { 63.0 / f.maxs } else { 0.0 };
let mi = if f.maxm > 0.0 { 63.0 / f.maxm } else { 0.0 };
for k in 0..8 {
ls[k] = (nearest(si * s.scales[k]) as u8).min(63);
lm[k] = (nearest(mi * s.mins[k]) as u8).min(63);
ls[k] = (nearest(si * f.scales[k]) as u8).min(63);
lm[k] = (nearest(mi * f.mins[k]) as u8).min(63);
}
let (d, m) = s.steps(63.0);
(ls, lm, d, m)
(ls, lm, f.maxs / 63.0, f.maxm / 63.0)
}
/// Requantizes the values against the stored (rounded) d and m and the packed scales in y.
fn q45k_requantize(x: &[f32], y: &[u8], nmax: i32, l: &mut [u8; 256]) {
/// Re-derives the levels against the stored (half-rounded) scale and minimum of every sub-block.
fn q45_requantize(x: &[f32], y: &[u8], l: &mut [u8; 256], nmax: i32) {
let d = h(y, 0);
let m = h(y, 2);
for k in 0..8 {
@@ -81,8 +83,7 @@ fn q45k_requantize(x: &[f32], y: &[u8], nmax: i32, l: &mut [u8; 256]) {
}
}
}
/// Low nibbles from y[head], and for Q5_K the fifth bits in y[16..48].
fn q45k_pack(five: bool, y: &mut [u8], l: &[u8; 256]) {
fn q45_pack_levels(l: &[u8; 256], y: &mut [u8], five: bool) {
let head = if five {
y[16..48].fill(0);
48
@@ -95,29 +96,31 @@ fn q45k_pack(five: bool, y: &mut [u8], l: &[u8; 256]) {
let b = l[k * 64 + j + 32];
y[head + k * 32 + j] = (a & 15) | ((b & 15) << 4);
if five {
y[16 + j] |= (u8::from(a > 15) << (2 * k)) | (u8::from(b > 15) << (2 * k + 1));
if a > 15 {
y[16 + j] |= 1 << (2 * k);
}
if b > 15 {
y[16 + j] |= 2 << (2 * k);
}
}
}
}
}
pub(super) fn q6k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let mut l = [0i8; 256];
let (scales, maxs, amax) = q6k_search(x, &mut l, qw);
if amax < EPS {
y.fill(0);
put_h(y, 208, 0.0);
return;
}
let inv = -128.0 / maxs;
put_h(y, 208, 1.0 / inv);
for k in 0..16 {
y[192 + k] = nearest(inv * scales[k]).min(127) as i8 as u8;
}
q6k_requantize(x, y, &mut l);
q6k_pack(y, &l);
pub(super) fn q45k(five: bool, x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let nmax = if five { 31 } else { 15 };
let sigma = 2.0 * sum_squares(x) / 256.0;
// The weighted implementation's no-imatrix branch is not used: public
// quantize_q4/5_K selects reference when qw=None, exactly as pinned GGML.
let mut f = q45_fit_blocks(x, qw, five, sigma);
let (ls, lm, d, m) = q45_scale_codes(&f, qw.is_some());
pack_scale4(&ls, &lm, &mut y[4..16]);
put_h(y, 0, d);
put_h(y, 2, m);
q45_requantize(x, y, &mut f.l, nmax);
q45_pack_levels(&f.l, y, five);
}
/// The scale of each 16-value block (levels of that fit in `l`), the scale of largest magnitude and that magnitude.
fn q6k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], f32, f32) {
/// The sixteen 16-element sub-block scales of a Q6_K block, with the one of largest magnitude.
fn q6_fit_blocks(x: &[f32], qw: Option<&[f32]>, l: &mut [i8; 256]) -> ([f32; 16], f32, f32) {
let mut scales = [0.0; 16];
let (mut maxs, mut amax) = (0.0, 0.0);
for k in 0..16 {
@@ -130,8 +133,7 @@ fn q6k_search(x: &[f32], l: &mut [i8; 256], qw: Option<&[f32]>) -> ([f32; 16], f
}
(scales, maxs, amax)
}
/// Requantizes the values against the stored (rounded) super-block scale and the block scales in y[192..208].
fn q6k_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) {
fn q6_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) {
let d = h(y, 208);
for k in 0..16 {
let ds = d * y[192 + k] as i8 as f32;
@@ -143,8 +145,7 @@ fn q6k_requantize(x: &[f32], y: &[u8], l: &mut [i8; 256]) {
}
}
}
/// Low nibbles into y[..128], the high two bits into y[128..192].
fn q6k_pack(y: &mut [u8], l: &[i8; 256]) {
fn q6_pack_levels(l: &[i8; 256], y: &mut [u8]) {
for k in 0..2 {
for j in 0..32 {
let a = l[k * 128 + j] as u8;
@@ -157,6 +158,22 @@ fn q6k_pack(y: &mut [u8], l: &[i8; 256]) {
}
}
}
pub(super) fn q6k(x: &[f32], y: &mut [u8], qw: Option<&[f32]>) {
let mut l = [0i8; 256];
let (scales, maxs, amax) = q6_fit_blocks(x, qw, &mut l);
if amax < EPS {
y.fill(0);
put_h(y, 208, 0.0);
return;
}
let inv = -128.0 / maxs;
put_h(y, 208, 1.0 / inv);
for k in 0..16 {
y[192 + k] = nearest(inv * scales[k]).min(127) as i8 as u8;
}
q6_requantize(x, y, &mut l);
q6_pack_levels(&l, y);
}
pub(super) fn best_iq4(x: f32) -> u8 {
let v = &super::super::rust_codebooks::KVALUES_IQ4NL;
if x <= v[0] as f32 {
@@ -1,112 +1,131 @@
//! Moved out of the parent module by STRA-338: fn qp, fn pack4, fn small, fn e8_half, fn ue4, fn pack_ue4.
use super::nearest_fn::Qkx;
#[allow(unused_imports)]
use super::*;
pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32 {
/// Unsigned level fit of `x` against the weights `w`: the block and the largest level.
struct UnsignedFit<'a> {
x: &'a [f32],
w: &'a [f32],
nmax: i32,
}
impl UnsignedFit<'_> {
fn assign_levels(&self, inv: f32, l: &mut [u8]) {
for i in 0..self.x.len() {
l[i] = nearest(inv * self.x[i]) as u8;
}
}
fn error_at(&self, l: &[u8], scale: f32) -> f32 {
let mut best = 0.0;
for i in 0..self.x.len() {
let d = self.x[i] - scale * l[i] as f32;
best += self.w[i] * d * d;
}
best
}
fn trial_error(&self, ti: f32, ds: f32) -> f32 {
let mut err = 0.0;
for i in 0..self.x.len() {
let q = nearest(ti * self.x[i]).min(self.nmax);
let d = self.x[i] - ds * q as f32;
err += self.w[i] * d * d;
}
err
}
/// The inverse scale among the nine trials around `inv` with the smallest error.
fn search_inverse(&self, max: f32, start: f32, mut best: f32) -> f32 {
let mut inv = start;
for is in -4..=4 {
if is == 0 {
continue;
}
let ti = (0.1 * is as f32 + self.nmax as f32) / max;
let err = self.trial_error(ti, 1.0 / ti);
if err < best {
best = err;
inv = ti;
}
}
inv
}
fn assign_clamped(&self, inv: f32, l: &mut [u8]) -> Sums {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..self.x.len() {
let q = nearest(inv * self.x[i]).min(self.nmax);
l[i] = q as u8;
sx += self.w[i] * self.x[i] * q as f32;
s2 += self.w[i] * q as f32 * q as f32;
}
Sums { sx, s2 }
}
/// Moves element `i` to its best level when that raises the objective; returns the new sums when it moved.
fn move_level(&self, l: &mut [u8], i: usize, s: Sums) -> Option<Sums> {
let (x, w) = (self.x, self.w);
let mut tx = s.sx - w[i] * x[i] * l[i] as f32;
let mut t2 = s.s2 - w[i] * l[i] as f32 * l[i] as f32;
if tx > 0.0 && t2 > 0.0 {
let q = nearest(x[i] * t2 / tx).min(self.nmax);
if q != l[i] as i32 {
tx += w[i] * x[i] * q as f32;
t2 += w[i] * q as f32 * q as f32;
if tx * tx * s.s2 > s.sx * s.sx * t2 {
l[i] = q as u8;
return Some(Sums { sx: tx, s2: t2 });
}
}
}
None
}
fn refine_pass(&self, l: &mut [u8], mut s: Sums) -> (Sums, usize) {
let mut changed = 0;
for i in 0..self.x.len() {
if let Some(moved) = self.move_level(l, i, s) {
s = moved;
changed += 1;
}
}
(s, changed)
}
fn refine_levels(&self, l: &mut [u8], mut s: Sums) -> Sums {
for _ in 0..5 {
let (next, changed) = self.refine_pass(l, s);
s = next;
if changed == 0 {
break;
}
}
s
}
}
fn largest_positive(x: &[f32]) -> f32 {
let mut max = 0.0;
for &x in x {
if x > max {
max = x;
}
}
max
}
pub(in super::super) fn qp(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32]) -> f32 {
let max = largest_positive(x);
if max < EPS {
l.fill(0);
return 0.0;
}
let inv = qp_scale(x, nmax, l, w, max);
qp_refine(x, nmax, l, w, inv)
}
/// The inverse scale among nmax/max and the eight 0.1-steps around it with the smallest weighted error;
/// `l` holds the levels of nmax/max on return.
fn qp_scale(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32], max: f32) -> f32 {
let mut inv = nmax as f32 / max;
for i in 0..x.len() {
l[i] = nearest(inv * x[i]) as u8;
}
let scale = 1.0 / inv;
let mut best = 0.0;
for i in 0..x.len() {
let d = x[i] - scale * l[i] as f32;
best += w[i] * d * d;
}
for is in (-4..=4).filter(|&is| is != 0) {
let ti = (0.1 * is as f32 + nmax as f32) / max;
let err = qp_error(x, nmax, w, ti);
if err < best {
best = err;
inv = ti;
}
}
inv
}
/// Weighted squared error of the levels at the inverse scale `ti`.
fn qp_error(x: &[f32], nmax: i32, w: &[f32], ti: f32) -> f32 {
let ds = 1.0 / ti;
let mut err = 0.0;
for i in 0..x.len() {
let q = nearest(ti * x[i]).min(nmax);
let d = x[i] - ds * q as f32;
err += w[i] * d * d;
}
err
}
/// Levels at `inv`, then up to five sweeps moving single levels while the fit improves; the scale.
fn qp_refine(x: &[f32], nmax: i32, l: &mut [u8], w: &[f32], inv: f32) -> f32 {
let (mut sx, mut s2) = (0.0, 0.0);
for i in 0..x.len() {
let q = nearest(inv * x[i]).min(nmax);
l[i] = q as u8;
sx += w[i] * x[i] * q as f32;
s2 += w[i] * q as f32 * q as f32;
}
for _ in 0..5 {
let mut changed = 0;
for i in 0..x.len() {
if let Some((q, tx, t2)) = qp_move(x[i], w[i], l[i], nmax, (sx, s2)) {
l[i] = q;
sx = tx;
s2 = t2;
changed += 1;
}
}
if changed == 0 {
break;
}
}
if s2 > 0.0 { sx / s2 } else { 0.0 }
}
/// The new level and sums when changing the level `li` of `xi` (weight `wi`) improves the fit; `sums` is (sx, s2).
fn qp_move(xi: f32, wi: f32, li: u8, nmax: i32, sums: (f32, f32)) -> Option<(u8, f32, f32)> {
let (sx, s2) = sums;
let mut tx = sx - wi * xi * li as f32;
let mut t2 = s2 - wi * li as f32 * li as f32;
if !(tx > 0.0 && t2 > 0.0) {
return None;
}
let q = nearest(xi * t2 / tx).min(nmax);
if q == li as i32 {
return None;
}
tx += wi * xi * q as f32;
t2 += wi * q as f32 * q as f32;
if tx * tx * s2 > sx * sx * t2 { Some((q as u8, tx, t2)) } else { None }
let fit = UnsignedFit { x, w, nmax };
let inv = nmax as f32 / max;
fit.assign_levels(inv, l);
let best = fit.error_at(l, 1.0 / inv);
let inv = fit.search_inverse(max, inv, best);
let start = fit.assign_clamped(inv, l);
let s = fit.refine_levels(l, start);
if s.s2 > 0.0 { s.sx / s.s2 } else { 0.0 }
}
pub(super) fn pack4(l: &[u8], y: &mut [u8]) {
for j in 0..16 {
y[j] = l[j] | (l[j + 16] << 4);
}
}
pub(super) fn small(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) {
match kind {
Kind::F32 | Kind::F16 | Kind::Bf16 => small_float(kind, x, y),
Kind::Q1Zero => small_q1(x, y),
Kind::Q2Zero => small_q2(x, y),
Kind::Q8Zero => small_q8(x, y),
_ => small_q45(kind, x, y, qw, sigma),
}
}
fn small_float(kind: Kind, x: &[f32], y: &mut [u8]) {
match kind {
Kind::F32 => y.copy_from_slice(&x[0].to_le_bytes()),
@@ -154,51 +173,28 @@ fn small_q8(x: &[f32], y: &mut [u8]) {
y[j + 2] = (x[j] * inv).round() as i8 as u8;
}
}
/// What distinguishes Q4_0/Q4_1/Q5_0/Q5_1: a minimum is stored, five bits, and the top level.
#[derive(Clone, Copy)]
struct Shape {
is_min: bool,
five: bool,
nmax: i32,
}
fn small_q45(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) {
let five = matches!(kind, Kind::Q5Zero | Kind::Q5One);
let shape = Shape { is_min: matches!(kind, Kind::Q4One | Kind::Q5One), five, nmax: if five { 31 } else { 15 } };
/// The 32 levels with their scale and minimum.
type SmallFit = ([u8; 32], f32, f32);
/// Weighted fit of a 32-element block; `is_min` selects the scale-plus-minimum form.
fn small_weighted(is_min: bool, five: bool, x: &[f32], qw: &[f32], sigma: f32) -> SmallFit {
let mut l = [0u8; 32];
let (d, m) = match qw {
Some(qw) => small_weighted(x, qw, sigma, shape, &mut l),
None if shape.is_min => small_plain_min(x, shape, &mut l),
None => small_plain_sym(x, shape, &mut l),
};
put_h(y, 0, d);
let head = if shape.is_min {
put_h(y, 2, m);
4
} else {
2
};
if five {
pack5(&l, y, head);
} else {
pack4(&l, &mut y[head..]);
}
}
/// Levels from the importance-weighted search; (scale, minimum).
fn small_weighted(x: &[f32], qw: &[f32], sigma: f32, shape: Shape, l: &mut [u8; 32]) -> (f32, f32) {
let nmax = if five { 31 } else { 15 };
let w = std::array::from_fn::<_, 32, _>(|j| qw[j] * (sigma + x[j] * x[j]).sqrt());
if shape.is_min {
let (s, m) = qkx(x, shape.nmax, &w, l, Qkx::WEIGHTED);
return (s, -m);
if is_min {
let (s, m) = qkx(x, nmax, &w, &mut l, -0.9, 0.05, 36, false, true);
(l, s, -m)
} else {
let mut q = [0i8; 32];
let d = qx(x, if five { 16 } else { 8 }, &mut q, 1, Some(&w));
for j in 0..32 {
l[j] = q[j] as u8;
}
(l, d, 0.0)
}
let mut q = [0i8; 32];
let d = qx(x, if shape.five { 16 } else { 8 }, &mut q, 1, Some(&w));
for j in 0..32 {
l[j] = q[j] as u8;
}
(d, 0.0)
}
/// Reference levels of Q4_1/Q5_1 from the min and max of the block; (scale, minimum).
fn small_plain_min(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) {
fn small_min_max(five: bool, x: &[f32]) -> SmallFit {
let mut l = [0u8; 32];
let nmax = if five { 31 } else { 15 };
let (mut min, mut max) = (f32::MAX, -f32::MAX);
for &v in x {
if v < min {
@@ -208,27 +204,35 @@ fn small_plain_min(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) {
max = v;
}
}
let d = (max - min) / shape.nmax as f32;
let d = (max - min) / nmax as f32;
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
for j in 0..32 {
let q = ((x[j] - min) * inv + 0.5) as i32;
l[j] = if shape.five { q as u8 } else { q.min(15) as u8 };
l[j] = if five { q as u8 } else { q.min(15) as u8 };
}
(d, min)
(l, d, min)
}
/// Reference levels of Q4_0/Q5_0 around the centre level; (scale, 0).
fn small_plain_sym(x: &[f32], shape: Shape, l: &mut [u8; 32]) -> (f32, f32) {
fn small_centered(five: bool, x: &[f32]) -> SmallFit {
let mut l = [0u8; 32];
let nmax = if five { 31 } else { 15 };
let (_, max) = max_signed(x);
let center = if shape.five { 16 } else { 8 };
let center = if five { 16 } else { 8 };
let d = max / -(center as f32);
let inv = if d != 0.0 { 1.0 / d } else { 0.0 };
for j in 0..32 {
l[j] = ((x[j] * inv + center as f32 + 0.5) as i8 as i32).min(shape.nmax) as u8;
l[j] = ((x[j] * inv + center as f32 + 0.5) as i8 as i32).min(nmax) as u8;
}
(d, 0.0)
(l, d, 0.0)
}
/// Five-bit packing: the low nibbles at `head + 4`, the fifth bits as a little-endian u32 at `head`.
fn pack5(l: &[u8; 32], y: &mut [u8], head: usize) {
fn small_levels(is_min: bool, five: bool, x: &[f32], qw: Option<&[f32]>, sigma: f32) -> SmallFit {
match qw {
Some(qw) => small_weighted(is_min, five, x, qw, sigma),
None if is_min => small_min_max(five, x),
None => small_centered(five, x),
}
}
/// Five-bit levels: the low nibbles after the 4-byte high-bit word at `head`.
fn pack_five(l: &[u8; 32], y: &mut [u8], head: usize) {
let mut hi = 0u32;
for j in 0..16 {
y[head + 4 + j] = (l[j] & 15) | ((l[j + 16] & 15) << 4);
@@ -237,6 +241,30 @@ fn pack5(l: &[u8; 32], y: &mut [u8], head: usize) {
}
y[head..head + 4].copy_from_slice(&hi.to_le_bytes());
}
fn small_q45(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) {
let is_min = matches!(kind, Kind::Q4One | Kind::Q5One);
let five = matches!(kind, Kind::Q5Zero | Kind::Q5One);
let (l, d, m) = small_levels(is_min, five, x, qw, sigma);
put_h(y, 0, d);
let head = if is_min { 4 } else { 2 };
if is_min {
put_h(y, 2, m);
}
if five {
pack_five(&l, y, head);
} else {
pack4(&l, &mut y[head..]);
}
}
pub(super) fn small(kind: Kind, x: &[f32], y: &mut [u8], qw: Option<&[f32]>, sigma: f32) {
match kind {
Kind::F32 | Kind::F16 | Kind::Bf16 => small_float(kind, x, y),
Kind::Q1Zero => small_q1(x, y),
Kind::Q2Zero => small_q2(x, y),
Kind::Q8Zero => small_q8(x, y),
_ => small_q45(kind, x, y, qw, sigma),
}
}
pub(super) fn e8_half(e: u8) -> f32 {
f32::from_bits(if e < 2 { 0x00200000u32 << e } else { ((e as u32) - 1) << 23 })
}